我在谷歌上搜索了高低并找到了示例,但它们似乎都不起作用(Lua 5.2)。
我在 Lua 中有一个简单的函数
function onData ( data )
print ( data )
end
我想从 C++ 调用 onData
并试过这个:
// Create new Lua state
L = luaL_newstate();
// Load all Lua libraries
luaL_openlibs(L);
// Create co-routine
CO = lua_newthread(L);
// Load and compile script
AnsiString script(Frame->Script_Edit->Text);
if (luaL_loadbuffer(CO,script.c_str(),script.Length(),AnsiString(Name).c_str()) == LUA_OK) {
Compiled = true;
} else {
cs_error(CO, "Compiler error: "); // Print compiler error
Compiled = false;
}
// Script compiled and ready?
if (Compiled == true) {
lua_getglobal(CO, "onData"); // <-------- Doesn't find the function
if( !lua_isfunction(CO,-1)) {
lua_pop(CO,1);
return;
}
lua_pushlstring(CO,data,len);
lua_resume(CO,NULL,0)
}
如您所见,我将脚本作为协同例程启动,因此我可以在其上使用 lua_yield()
函数。我试图在 L
和 CO
状态下寻找函数。
最佳答案
luaL_loadbuffer
加载脚本但不运行它。 onData
只会在脚本运行时定义。
尝试调用 luaL_dostring
而不是 luaL_loadbuffer
。
或者在lua_getglobal
之前添加lua_pcall(CO,0,0,0)
。
此外,你需要lua_resume(CO,NULL,1)
将data
传递给onData
。
关于c++ - 从 C++ 调用 Lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20495108/