Declareing a 'global' instance of chaiscript::ChaiScript


#1
chaiscript::ChaiScript chai(chaiscript::Std_Lib::library());

or

chaiscript::ChaiScript chai;

both seem to run ‘initialisation’ code when executed.

I think of ‘chai’ in these cases as being the scripting ‘Engine’ and I would like to make the same engine available to different places in my game.

For example, my TerrainLayer class wants to run a script (in a separate file called Terrain.chai") and my Entity class wants to run a script called “InitEntity.chai”

So my thought was to declare chai in a utility class and have, in my TerrainLayer class, something like:

TerrainLayer::Initialise()
{
    Utility::GetInstance->GetScriptEngine().eval_file("Terrain.chai:);
}

and a similar method in my entity class.

but I can’t seem to work out how to define an instance of the chai object such that I can reference it like this…

If I declare it as described at the start of this post, I seem to only be able to do so successfully as a local variable within a function - I can’t define it in a header file, nor as a global (well, I can declare it but it won’t work as described - I get linker errors for example)

So, in short(!) can I declare somehow (or make available somehow) a chaiscript object so that I can access it from many other classes?

Thanks


#2

Warning, you probably don’t want to do this

Instead: Please strongly consider creating a chaiscript instance then passing it into each function call that might need to use it.

This is a much better solution, and the option I used in Spiced. This gives you the flexibility to do things like swap out your scripting engine, use multiple instances of the scripting engine, etc.

Also note that if you run into any problems with the below solution I may not be able to support you because they could be specific to your compiler/platform/codebase

Now that I’ve warned you…

Do not even consider using this method if you are using MSVC 2013 or earlier

I’m reluctant to explain how to make a singleton in C++, because there are many varied issues with singletons that can sometimes bite you in unexpected ways.

However, many of these problems were solved with C++11, so I guess I’ll share.

//chaiscript_singleton.hpp

class ChaiScript_Singleton
{
public:
  static ChaiScript::chaiscript& get_instance();
};
//chaiscript_singleton.cpp

ChaiScript::chaiscript &ChaiScript_Singleton::get_instance()
{
  static chaiscript::ChaiScript chai;
  return chai;
}

This method uses the “construct on first use” idiom, which means the static object chai is constructed and initialized the first time the get_instance method is called.

Usage would be like you are suggesting.

ChaiScript_Singleton::get_instance().eval_file("Terrain.chai")

I guess I’ll say this: I’m warning you that this is probably a bad idea in the long run.


Hopefully that was enough disclaimers…


#3

Hmmmm. reading between the lines, I think you’re leaning towards not using my suggested solution :smile: