6

我在谷歌上下搜索并找到了一些例子,但它们似乎都不起作用(Lua 5.2)。

我在 Lua 中有一个简单的功能

function onData ( data )
  print ( data )
end

我想onData从 C++ 调用并尝试了这个:

// 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状态中寻找函数。

4

1 回答 1

4

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

尝试调用luaL_dostring而不是luaL_loadbuffer.

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

此外,您需要lua_resume(CO,NULL,1)传递dataonData.

于 2013-12-10T12:57:49.943 回答