用c++访问Lua全局表



如何使用c++访问已经存在于Lua中的全局表?下面是我尝试过的代码。我试着创建一个全局变量,并尝试在Lua中修改一个local到local,但事情似乎不工作

        lua_State *lua_state = luaL_newstate();
        luaL_openlibs(lua_state);
        // lua_createtable(lua_state, 0, 81);
        // for (int i = 1; i <= 81; i++)
        // {
        //  lua_pushnumber(lua_state, i);
        //  lua_pushnumber(lua_state, grid_[i - 1]);
        //  lua_settable(lua_state, -3);
        // }
        // 
        // lua_setglobal(lua_state, "arg");
        // lua_createtable(lua_state, 81, 1);
        // 
        // for (int i = 1; i <= 81; i++)
        // {
        //  lua_pushnumber(lua_state, i);
        //  lua_pushnumber(lua_state, grid_[i - 1]);
        //  lua_settable(lua_state, -3);
        // }
        // lua_setglobal(lua_state, "arg");

        luaL_loadfile(lua_state, "main.lua");
        lua_call(lua_state, 0, 0);
        int t = 2;
        /* table is in the stack at index 't' */
        lua_pushnil(lua_state);  /* first key */
        while (lua_next(lua_state, t) != 0) {
            /* uses 'key' (at index -2) and 'value' (at index -1) */
            printf("%s - %sn",
                lua_typename(lua_state, lua_type(lua_state, -2)),
                lua_typename(lua_state, lua_type(lua_state, -1)));
            /* removes 'value'; keeps 'key' for next iteration */
            lua_pop(lua_state, 1);
        }

Lua

problem =
{
    {9, 0, 0, 1, 0, 0, 0, 0, 5},
    {0, 0, 5, 0, 9, 0, 2, 0, 1},
    {8, 0, 0, 0, 4, 0, 0, 0, 0},
    {0, 0, 0, 0, 8, 0, 0, 0, 0},
    {0, 0, 0, 7, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 2, 6, 0, 0, 9},
    {2, 0, 0, 3, 0, 0, 0, 0, 6},
    {0, 0, 0, 2, 0, 0, 9, 0, 0},
    {0, 0, 1, 9, 0, 4, 5, 7, 0},
}
更新1

int main()
{
    lua_State *lua_state = luaL_newstate();
    luaL_openlibs(lua_state);
    luaL_loadfile(lua_state, "main.lua");
    lua_getglobal(lua_state, "problem");
    //lua_pushglobaltable(lua_state);       // Get global table
    lua_pushnil(lua_state);               // put a nil key on stack
    while (lua_next(lua_state, -2) != 0) { // key(-1) is replaced by the next key(-1) in table(-2)
        std::string name = lua_tostring(lua_state, -2);  // Get key(-2) name
        std::cout << name << std::endl;
        lua_pop(lua_state, 1);               // remove value(-1), now key on top at(-1)
    }
    lua_pop(lua_state, 1);                 // remove global table(-1)
    lua_call(lua_state, 0, 0);
    return 0;
}

Lua

problem =
{
    {9, 0, 0, 1, 0, 0, 0, 0, 5},
    {0, 0, 5, 0, 9, 0, 2, 0, 1},
    {8, 0, 0, 0, 4, 0, 0, 0, 0},
    {0, 0, 0, 0, 8, 0, 0, 0, 0},
    {0, 0, 0, 7, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 2, 6, 0, 0, 9},
    {2, 0, 0, 3, 0, 0, 0, 0, 6},
    {0, 0, 0, 2, 0, 0, 9, 0, 0},
    {0, 0, 1, 9, 0, 4, 5, 7, 0},
}
print("Lua Works")
user_input = io.read();

你没有任何值可以在Lua堆栈上迭代。
int t=2;不反映任何东西,你的脚本不返回值留在堆栈上。
关于访问全局表的示例,请参见PIL: 25.1 - Table Manipulation。

最新更新