I am using Lua to write scipts and embed them in C++. I use LuaBridge in this process.
In my Lua script, I have some variables which need to be retrieved at first for usage in C++, besides, I have a very simple function:
run = function()
print ("state is on!")
end
This function, however, is only called under a specific condition. i.e. only called when a "true" is obtained from C++ codes after a series of complicated calculations.
Limited by my Lua and LuaBridge knowledge, what I know is: after I do
loadscript(L, "script.lua")
lua_pcall(L,0,0,0)
I can read out variables and functions from Lua script by using
LuaRef blabla = getGlobal(L, "blabla")
But now, I need to read out variables and use them at first, then in a member function
LuaRunner::LuaRun(){}
defined in a separate C++ class
class LuaRunner
the condition will be obatined and this run() function will be called if the condition is "true". It would be best to call this run() function right in the C++ member function
LuaRunner::LuaRun(){}
due to restriction of further processing.
Therefore, I was wondering whether this would be possible:
Read out the function using
LuaRef run = getGlobal(L, "run")
together with other variables at the beginning and "save" this run() function somewhere in C++ codes (perhaps as a class member function), and then the run() function can be called later on by a pointer or an object in the same class. Would this be possible? If possible, how to do it? Or any other good ideas?
It's possible to store luabridge::LuaRef's in C++ to call them later just as you normally call any other function. Though sometimes there's no need to store LuaRef's anywhere. Once you load the script, all functions stay in your lua_State, unless you set them to nil or override them by loading another script which uses the same names for functions. You can get them by using getGlobal function. If your Lua function takes arguments, you can pass them, using LuaRef's operator() like this:
if(...) { // your call condition
LuaRef f = getGlobal(L, "someFunction");
f(arg1, arg2, ...); // if your function takes no arguments, just use f();
}