• Lua 栈【转】【学习笔记】


    table在Lua中唯一的数据结构,其它语言提供的各种数据结构Lua都是用table来实现的 。下面是一个C API操作table的例子。

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

    int main()
    {
            
    lua_State *L;
            L = luaL_newstate();
            luaL_openlibs(L);

            // ta = {'AA', 'BB', {'CC', 'DD'}}
            lua_newtable(L);
            //依次将各个元素放入table
            lua_pushnumber(L,1);
            lua_pushstring(L, "AA");
            lua_rawset(L,1);

            lua_pushnumber(L,2);
            lua_pushstring(L, "BB");
            lua_rawset(L,1);

            lua_pushnumber(L,3);
            lua_newtable(L);
            lua_pushstring(L, "CC");
            lua_rawseti(L,-2,1);

            lua_pushstring(L, "DD");
            lua_rawseti(L,-2,2);
            lua_rawset(L,1);

            lua_setglobal(L,"ta");
            //此时栈中为空,此处省略其他操作
            //将ta压入栈顶
            lua_getglobal(L, "ta");
            //获得第一个元素
            lua_rawgeti(L, 1,1);
            if(lua_type(L,-1) == LUA_TSTRING)
                    printf("%s", lua_tostring(L,-1));
            lua_pop(L,1);

            lua_rawgeti(L, 1,2);
            if(lua_type(L,-1) == LUA_TSTRING)
                    printf("%s", lua_tostring(L,-1));
            lua_pop(L,1);

            lua_rawgeti(L, 1,3);
            if(lua_type(L,-1) == LUA_TTABLE)
            {
                    //因为第三个元素是table,所以继续获得它的第一个元素
                    lua_rawgeti(L, -1,1);
                    if(lua_type(L,-1) == LUA_TSTRING)
                            printf("%s", lua_tostring(L,-1));
                    lua_pop(L,1);

                    lua_rawgeti(L, -1,2);
                    if(lua_type(L,-1) == LUA_TSTRING)
                            printf("%s", lua_tostring(L,-1));
                    lua_pop(L,1);                
            }
            lua_pop(L,1); //此时栈顶为ta
                                 
            lua_close(L);
    }

  • 相关阅读:
    阅读《构建之法(第三版)》提出的问题
    职位部门管理系统
    JSON
    hashcode()和equals()方法
    JSF和Facelets的生命周期
    认识applet
    认识ajax
    hello1.java分析
    vue中的防抖和节流
    vue项目搭建
  • 原文地址:https://www.cnblogs.com/perzy/p/3226788.html
Copyright © 2020-2023  润新知