简体   繁体   English

从C ++调用Lua函数

[英]Call a Lua function from C++

I have google high and low and found examples, but none of them seems to work (Lua 5.2). 我有谷歌的高低,并找到了例子,但似乎没有一个工作(Lua 5.2)。

I have a simple function in Lua 我在Lua中有一个简单的功能

function onData ( data )
  print ( data )
end

I want to call onData from C++ and tried this: 我想从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)
}

As you can see I'm starting my script as a co-routine so I can use the lua_yield() function on it. 正如您所看到的,我正在将脚本作为一个协同例程启动,因此我可以在其上使用lua_yield()函数。 I have tried to look for the function in both the L and CO states. 我试图在LCO状态下寻找功能。

luaL_loadbuffer loads the script but does not run it. luaL_loadbuffer加载脚本但不运行它。 onData will only be defined when the script is run. onData仅在脚本运行时定义。

Try calling luaL_dostring instead of luaL_loadbuffer . 尝试调用luaL_dostring而不是luaL_loadbuffer

Or add lua_pcall(CO,0,0,0) before lua_getglobal . 或者在lua_getglobal之前添加lua_pcall(CO,0,0,0)

Moreover, you need lua_resume(CO,NULL,1) to pass data to onData . 此外,您需要lua_resume(CO,NULL,1)data传递给onData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM