zoukankan      html  css  js  c++  java
  • 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);
    }

  • 相关阅读:
    字符串个数的麻烦
    最长单调递增子序列LIS(《算法导论》15.4-5题)
    LCS问题
    关于nextLine()与nextInt()
    调用内部类里,在静态类中调用动态方法的问题
    RTL底层释放或回收对象
    软件需求分、架构设计与建模最佳实践
    Spring@Autowired java.lang.NullPointerException 空指针
    MAC下安装REDIS和REDIS可视化工具RDM并连接REDIS
    Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.apache.catalina.connector.CoyoteWriter and no properties discovered to create BeanSerializer
  • 原文地址:https://www.cnblogs.com/perzy/p/3226788.html
Copyright © 2011-2022 走看看