Consider this small Lua test script.
g1 = "Global 1"
g2 = "Global 2"
function test ()
local l1
print(g1,g2,l1)
end
test()
Assume you pause the execution at print(g1,g2,l1) and from C++ get all the global variables with this C code:
lua_pushglobaltable(L);
lua_pushnil(L);
while (lua_next(L,-2) != 0) {
const char* name = lua_tostring(L,-2);
// How do I tell a user defined
// global variable (now in name)
// from all other environment variables?
lua_pop(L,1);
}
lua_pop(L,1); // global table
When I get the name
of a global entry, how can I tell if this is a global variable defined by the user in the script, like g1 and g2?
Since the user can freely write the script, I can't search for a specific global, I need to tell them apart somehow.
My solution was to build a hash table of the global environment before I loaded the main script. When I need to get the user defined globals I only display globals not present in the hash table. In this way the script can run at full speed without keeping track of globals in in runtime.
Example of my solution (this is the short version of my implementation):
The function
HashName
takes a string and returns the hash key for it as anunsigned int
, use whatever Hash algorithm you like here...When you need to display the globals, call
PrintGlobals()
(I do it from ahook
routine)