循环遍历C ++中的所有Lua全局变量 [英] Loop through all Lua global variables in C++

查看:1378
本文介绍了循环遍历C ++中的所有Lua全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找相当长的一段时间,我还没有找到一种方法从C ++中获取所有全局变量。考虑这个小的Lua测试脚本。

  myGlobal1 =Global 1
myGlobal2 = 2

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

test()
print(myGlobal1,myGlobal2,l1)
和从 C ++获取所有全局变量( myGlobal1 myGlobal2 )。这些例子是任意的,从C ++的角度来看,全局变量是未知的。



我一直在寻找 lua_getglobal() code>但我需要首先知道变量的名称。我查看了 lua_getupvalue(),但只得到了 _ENV 作为结果。



我想尽快知道它们的名字,我可以使用 lua_getglobal(),但是如何获得全局变量列表(来自C ++) ?在这一点上我确实有 lua_Debug 结构(如果有任何帮助的话)



编辑
这篇文章最初并不是关于如何查找用户自己的全局变量,而是关于如何查找用户自己的全局变量。



然而,我发布了一个解决方案如何完成这项工作此处 a>。

好的,我解决了它。

  lua_pushglobaltable(L); //获取全局表
lua_pushnil(L); //(lua_next(L,-2)!= 0){// key(-1)被表(-2)中的下一个键(-1)替换时,在栈
上放置一个零键
name = lua_tostring(L,-2); //获取密钥(-2)名称
lua_pop(L,1); //取值(-1),现在在(-1)
}处
lua_pop(L,1); //删除全局表(-1)

lua_next() code>找不到更多的条目,键名弹出,离开表(-1)。



接下来的问题是区分我自己的全局变量从表格条目的其余部分... ...

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.

解决方案

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...

这篇关于循环遍历C ++中的所有Lua全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆