Include function


How would one add a include function
example <odbc.h>


i was able to accomplish what was needed - but i am sure there is a better way

first i added a function

std::string SCRIPT_include(std::string filename) {
    std::string app_root_path = boost::filesystem::current_path().generic_string();
    std::string scriptfile;

    if ( == '/') scriptfile = app_root_path + "/scripts" + filename;
    else scriptfile = app_root_path + "/scripts/" + filename;
    char *b = FileGet((char *)scriptfile.c_str());
    if (b)
        std::string o = b;
        return o;
    return "";

chai.add(chaiscript::fun(&SCRIPT_include), "include");
// script


works perfectly variables created in the include are used in current script

i would like to be able to remove the eval() and just use the include in the script
since there is no global pointer for chai i am unable to do that - is there a way to pass the current chai to c++ functions?


Personally I would have either used the use (ensures that a file is only included once) or eval_file (includes a file as many times as you want to) functions. See the cheatsheet:

To answer your question about binding of parameters with chaiscript registered functions, you can easily pull in the current ChaiScript context if you wanted to, either using a C++11 lambda, or the automatic binding feature of ChaiScript.

//function decl
std::string load_script(chaiscript::ChaiScript &chai, const std::string &filename);
// automatic bind first parameter of function
chai.add(chaiscript::fun(&load_script, std::ref(chai)), "load_script");
// lambda
chai.add(chaiscript::fun([&chai](const std::string &s){ return load_script(chai,s); }), "load_script");


the built in use function is what i wanted - as soon as i added the sciptpath all was well
std::vectorstd::string _scriptpath;
_scriptpath.push_back( path );
chaiscript::ChaiScript chai(chaiscript::Std_Lib::library(),_scriptpath,_scriptpath);

if i did not add the script path - example: c:\scripts\ - you require the full path of the file
have you thought of being able to add relative paths . for example …\scripts\file.cpp


It might be worth adding some kind of use_relative() (I think that’s how Ruby does it?)

In general ChaiScript doesn’t really have filesystem facilities. There would be some debate as to whether or not they should be added, since the average user really doesn’t want to give the script-writer that much access to the system…