简体   繁体   中英

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).

I have a simple function in Lua

function onData ( data )
  print ( data )
end

I want to call onData from C++ and tried this:

// 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. I have tried to look for the function in both the L and CO states.

luaL_loadbuffer loads the script but does not run it. onData will only be defined when the script is run.

Try calling luaL_dostring instead of luaL_loadbuffer .

Or add lua_pcall(CO,0,0,0) before lua_getglobal .

Moreover, you need lua_resume(CO,NULL,1) to pass data to onData .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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