在 C++ 中循环遍历所有 Lua 全局变量

2021-12-30 00:00:00 global-variables lua c++ lua-5.2

我已经搜索了很长时间,但我还没有找到从 C++ 中获取所有全局变量的方法.考虑这个小的 Lua 测试脚本.

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()

假设您在 print (myGlobal1,myGlobal2,l1) 处暂停执行并从 C++ 获取所有全局变量(myGlobal1myGlobal2).这些例子是任意的,全局变量,从 C++ 的角度来看,是未知的.

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.

我一直在查看 lua_getglobal() 但后来我需要先知道变量的名称.我查看了 lua_getupvalue() 但只得到了_ENV"作为结果.

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.

我想我可以在知道它们的名称后立即使用 lua_getglobal(),但是如何获取全局变量列表(来自 C++)?我现在确实有 lua_Debug 结构(如果有帮助的话)

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.

推荐答案

好的,我解决了.

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)

lua_next() 找不到更多条目时,键名会弹出,将表格留在顶部 (-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...

相关文章