[Lua]c解析lua 嵌套table

void ParseLuaTable(lua_State *L)
{
    if (!lua_istable(L, -1))
    {
        return;
    }

    lua_pushnil(L);
    while (lua_next(L, -2))
    {
        fprintf(stdout, "%s : %s    ", luaL_typename(L,-2), luaL_typename(L,-1));
        int nKeyType = lua_type(L, -2);
        int nValueType = lua_type(L, -1);

        if (nKeyType == LUA_TNUMBER)
        {
            fprintf(stdout, "%g,", lua_tonumber(L, -2));
        }
        else if (nKeyType == LUA_TSTRING)
        {
            fprintf(stdout, "\"%s\",", lua_tostring(L, -2));
        }
        fprintf(stdout, "   ");  
        if (nValueType == LUA_TNUMBER)
        {
            fprintf(stdout, "%g", lua_tonumber(L, -1));
        }
        else if (nValueType == LUA_TSTRING)
        {
            fprintf(stdout, "\"%s\"", lua_tostring(L, -1));
        }
        else if (nValueType == LUA_TTABLE)
        {
            fprintf(stdout, "\n");
            ParseLuaTable(L);
        }   

        lua_pop(L, 1);
        fprintf(stdout, "\n");   
    }
}

int test()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    int error = 0;

    // test.lua 
    //s = {
    //g = "g",
    //b = "b",
    //r = 2,
    //t = {
    //    width = 100,
    //    height = 200,
    //    path = "path",
    //    te = { a = 1, b = 2}
    //},
    //
    //3,
    //4,
    //5,
    //"test"
    //}
    //
    
    luaL_loadfile(L, "test.lua");
    error = lua_pcall(L, 0, 0, 0);
    if (error) {
        fprintf(stderr, "%s", lua_tostring(L, -1));
        lua_pop(L, 1);/* pop error message from the stack */
    }
    
    lua_getglobal(L, "s");
    ParseLuaTable(L);

    if (error) {
        fprintf(stderr, "%s", lua_tostring(L, -1));
        lua_pop(L, 1);/* pop error message from the stack */
    }

    return 0;
}

 

posted on 2013-02-04 14:37  快乐的大猪  阅读(1522)  评论(0编辑  收藏  举报

导航