从C++调用Lua函数。

我在网上搜了很多例子,但是没有一个能正常工作(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() 函数。我尝试在 LCO 状态中查找函数。

点赞
用户107090
用户107090

luaL_loadbuffer 加载脚本但不运行它。只有在脚本运行时才会定义 onData

尝试使用 luaL_dostring 代替 luaL_loadbuffer

或者在 lua_getglobal 之前添加 lua_pcall(CO,0,0,0)

此外,您需要使用 lua_resume(CO,NULL,1)data 传递给 onData

2013-12-10 12:57:49