简体   繁体   English

Lua C 5.1 - 遍历所有全局值

[英]Lua C 5.1 - Iterating through all global values

Recently I have been exploring the luac 5.1 api and I was wondering if it is possible to loop through every global value in the 5.1 api, I know it is possible to do this in 5.2 ( referenced here ) as lua_pushglobaltable(lua_State*) exists.最近我一直在探索 luac 5.1 api,我想知道是否可以遍历 5.1 api 中的每个全局值,我知道在 5.2 中可以做到这一点( 在此处引用),因为 lua_pushState*(a) 存在。 I know there is LUA_GLOBALSINDEX however I'm not sure how to use it for this purpose.我知道有 LUA_GLOBALSINDEX 但是我不确定如何将它用于此目的。 Any help would be greatly appreciated!任何帮助将不胜感激!

Thanks:)谢谢:)

You can use the code in the answer you've mentioned. 您可以使用您提到的答案中的代码。 Just do this: 这样做:

#define lua_pushglobaltable(L) lua_pushvalue(L,LUA_GLOBALSINDEX)

Here is a complete program that lists all global variables. 这是一个列出所有全局变量的完整程序。 If you remove the define, it works in Lua 5.2 and 5.3. 如果删除了define,它在Lua 5.2和5.3中有效。

#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

#define lua_pushglobaltable(L) lua_pushvalue(L,LUA_GLOBALSINDEX)

int main(void)
{
    lua_State *L=luaL_newstate();
    luaL_openlibs(L);
    lua_pushglobaltable(L);
    lua_pushnil(L);
    while (lua_next(L,-2) != 0) {
        puts(lua_tostring(L,-2));
        lua_pop(L,1);
    }
    lua_pop(L,1);
    lua_close(L);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM