Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all Lua global variables in C++ [duplicate]

I have been searching for quite a while now and I haven't found a way to fetch all the global variables from C++. Consider this small Lua test script.

myGlobal1 = "Global 1"
myGlobal2 = 2

function test()
  local l1=0
  print (myGlobal1,myGlobal2,l1)
end

test()

Assume you pause the execution at print (myGlobal1,myGlobal2,l1) and from C++ get all the global variables (myGlobal1 and myGlobal2). These examples are arbitrary, the global variables, from a C++ point of view, are unknown.

I have been looking at lua_getglobal() but then I need to know the name of the variable first. I looked at lua_getupvalue() but only got "_ENV" as result.

I guess I can use lua_getglobal() as soon I know the name of them, but how do I get the list of global variables (from C++)? I do have the lua_Debug structure at this point (if it is to any help)

EDIT This post wasn't originally about iterating through a table, it was about how to find the user's own globals.

However, I posted a solution to how this can be done here.

like image 952
Max Kielland Avatar asked Dec 11 '13 15:12

Max Kielland


1 Answers

Okay I solved it.

lua_pushglobaltable(L);       // Get global table
lua_pushnil(L);               // put a nil key on stack
while (lua_next(L,-2) != 0) { // key(-1) is replaced by the next key(-1) in table(-2)
  name = lua_tostring(L,-2);  // Get key(-2) name
  lua_pop(L,1);               // remove value(-1), now key on top at(-1)
}
lua_pop(L,1);                 // remove global table(-1)

When lua_next() can't find more entries the key name is popped leaving the table on top(-1).

Next problem would be to distinguish my own globals from the rest of the table entries...

like image 89
Max Kielland Avatar answered Nov 15 '22 12:11

Max Kielland