Adding static methods


Given the following:

struct Library
static bool initialize(std::string name);

Is it possibly to add the function to the ChaiScript module and access it like:



#include <chaiscript/chaiscript.hpp>
#include <iostream>

struct Foo {
	static void bar() {
		std::cout << "FOOBAR" << std::endl;

int main() {
	chaiscript::ChaiScript chai;

	// Probably most solid way:
	chai.add(chaiscript::fun(&Foo::bar), "Foo_bar");

	// This might not work if you want to actually use Foo as class,
	// not only for its statics.
	chai.register_namespace([](chaiscript::Namespace & foo){
		foo["bar"] = chaiscript::var(chaiscript::fun(&Foo::bar));

Using _ was the most immediate alternative. I guess I will settle down with that, since registering as a namespace looks more tedious and, as you mentioned, probably the class might not be usable later.

You could also add it like:

chai.add(chaiscript::fun([](const Library &, const std::string &name){ return Library::initialize(name); }, "initializer");

Just treat it as a member function, but throw away the “this” object. It’d work the same from the ChaiScript perspective.

1 Like

Wouldn’t this need a variable of type Library first? The error would look something like the following, if the code is Library.initialize.

Error: "Can not find object: Library"