Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 780
Max Kielland Avatar asked Dec 10 '13 12:12

Max Kielland


1 Answers

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.

like image 94
lhf Avatar answered Oct 18 '22 07:10

lhf