• c++获取lua嵌套table某属性的值


    开发环境:vs2012

    lua版本:LuaJIT-2.0.2

    lua文件作为配置文件,c++读取这个配置。

    lua配置结构如下

    SceneConfig = 
    {
        [1] = { name ="lsySB", sex = 1},
        [2] = 2
    }

    我们读取SceneConfig[1].name的值,这是一个嵌套的table

    int main()
    {
        lua_State *luaState = lua_open();              
            // 创建 Lua 状态. 其实就是一个数据结构.
        luaL_openlibs(luaState);                            
            // 加载所有标准库, 例如: print 等.
        luaL_dofile(luaState, "../Debug/test.lua");
        //index为0,表示把栈全清空
        lua_settop(luaState, 0);
        //根配置入栈
        lua_getglobal(luaState, "SceneConfig");
        //key入栈
        lua_pushinteger(luaState, 1);
        //key弹出得到key对应的table入栈
        lua_gettable(luaState, 1);
            //子Key入栈,此时内table索引为-2
            lua_pushstring(luaState, "name");
            //得到name对应的值,key出栈,值入栈
            lua_gettable(luaState, -2);
        
        //获得栈顶值    
        cout << lua_tostring(luaState, -1) << endl;
        //栈顶值出栈
        lua_pop(luaState, 1);
        //压入key值
        lua_pushstring(luaState,"sex");
        //弹出key值,对应的值入栈
        lua_gettable(luaState, -2);
        //得到栈顶值
        cout << lua_tointeger(luaState, -1) << endl;
        getchar();
    }   

    首先得到全局变量,然后压入key,1,这里1是int,而不能用“1”,根据这个key取出来的是里面的table即Sceneconfig[1]的值,

    重复上述过程,name压入栈然后得出name的值。

    上述过程是最原始的一种方法,下面有个简单的方法。

    通过

    int lua_getfield (lua_State *L, int index, const char *k);

    把 t[k] 的值压栈, 这里的 t 是索引指向的值。 在 Lua 中,这个函数可能触发对应 "index" 事件对应的元方法。

    这里很容易的可以通过key得到table的值,相当于lua的标准库做了一个封装

  • 相关阅读:
    【leetcode刷题笔记】Merge Intervals
    【leetcode刷题笔记】Implement strStr()
    【leetcode刷题笔记】Rotate List
    【leetcode刷题笔记】Merge k Sorted Lists
    【leetcode刷题笔记】Longest Substring Without Repeating Characters
    【leetcode刷题笔记】Scramble String
    【leetcode刷题笔记】Anagrams
    【leetcode刷题笔记】Distinct Subsequences
    【leetcode刷题笔记】Remove Duplicates from Sorted List II
    结语与感悟
  • 原文地址:https://www.cnblogs.com/beyond-time-space/p/4646286.html
Copyright © 2020-2023  润新知