These are chat archives for ChaiScript/ChaiScript

Jun 2018
Christian Aguilera
Jun 23 2018 14:04

Hi everybody,

I spent some time this morning experimenting with ChaiScript, and wrote this basic example:

#include <memory>
#include <string>
#include <unordered_map>

#include <chaiscript/chaiscript.hpp>

class Interface final
    void setAttr(const std::string& key, const std::string& value) {
        m_attributes[key] = value;

    const std::string& getAttr(const std::string& key) {
        return m_attributes[key];

    std::unordered_map<std::string, std::string> m_attributes;

void execute(Interface& interface, const std::string& script)
    chaiscript::ChaiScript chai;

    // Add types.
    chaiscript::ModulePtr m(std::make_unique<chaiscript::Module>());
        {{chaiscript::fun(&Interface::setAttr), "setAttr"},
         {chaiscript::fun(&Interface::getAttr), "getAttr"}}

    // Bind global variables.
    chai.add(chaiscript::var(&interface), "interface");

    // Parse and run the script.

int main(int argc, const char* argv[])
    if (argc <= 1) { return -1; }

    Interface interface;
    const std::string script = argv[1];
    execute(interface, script);

    return 0;

It surprised me how easy it was to get it working.

So, here is the question. I would like to invoke the execute() function many times, with different Interface objects, but with the same script program. Ideally, I'd like to reuse the same chaiscript::ChaiScript chai instance to avoid parsing/interpreting the program each time. Is this possible at the moment with ChaiScript?


Christian Aguilera
Jun 23 2018 15:00
I've just learned that eval_file() (or eval(), or the operator()) can be evaluated several times. That is probably the answer to my previous question. A function execute() in ChaiScript can be defined with eval_file(), and then the function can be invoked several times, with different arguments, with chai("execute(interface);");