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);
}
數據結構

相關文章
相關標籤/搜索