Operating on global variables
Lua global variables are accessible for the whole Lua state. Consider this Lua code:
whom = "C++" function hello() print("Hello " .. whom) end
The hello
function uses the global variable whom
to print out a greeting.
How do we get and set this Lua global variable from C++? We will now extend LuaExecutor
to do this and use the hello
function to test it. In this chapter, we will only implement the method to work with string variables to focus primarily on the mechanism.
Getting global variables
You use the Lua library lua_getglobal
function to get global variables. Its prototype is as follows:
int lua_getglobal (lua_State *L, const char *name);
lua_getglobal
expects two parameters. The first one is the Lua state. The second one is the name for the global variable. lua_getglobal
pushes the value of the global variable onto the stack and returns its type. The types are defined as follows: