Whenever I run the program, it prints nothing to the console. This works fine if I don't use a class and just do it all in main().
The moment I put it in a class, I start having problems. What am I doing wrong?
using namespace luabridge;
myClass::myClass()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
getGlobalNamespace(L).beginClass<myClass>("myClass").addFunction("printMessage", &myClass::printMessage).endClass();
luaL_dofile(L, "test.lua");
lua_pcall(L, 0, 0, 0);
}
void myClass::printMessage(const std::string& s)
{
std::cout << s << std::endl;
}
My lua script "test.lua"
I've tried
c = myClass()
c:printMessage("You can call C++ functions from Lua!")
and
myClass:printMessage("You can call C++ functions from Lua!")
and
printMessage("You can call C++ functions from Lua!")
There are three options to do what you want:
If you want to construct a myClass
instance in lua, and use it like your first example, you need to also export a constructor after the beginClass
:
.addConstructor <void (*) (void)> ()
Construct a myClass
instance in C++, and then pass it to lua using some other function. Then lua may access it like:
myClassInstance:printMessage("Hello")
Make printMessage
static, and export it with the following:
.addStaticFunction("printMessage", &myClass::printMessage)
Then you can call it in lua using:
myClass.printMessage("Hello")
Notice the difference between .
and :
in the calls. .
accesses like a static and :
accesses like an instance.