2013-11-24 1 views
0

나는이 같은 루아에 테이블을 반환해야합니다다차원 테이블을 C 함수에서 lua로 반환하는 방법은 무엇입니까?

{ 
    [0] = { ["field1"] = "1", ["field2"] = "2" , ["field3"] = "3" }, 
    [1] = { ["field1"] = "10" , ["field2"] = "20", ["field3"] = "30" } 
} 

을하지만 C의 관점에서와 lua_를 사용하여 는 또한, 0과 1 단지 예입니다 * 기능, 그것은 그 같은 더 어레이를 포함 할 수 있습니다 . 누구든지 나를 도울 수 있습니까?

+0

왜 'C++'태그가 지정되어 있습니까? – Walter

+0

나는 그것을 c로 태그를 붙였습니까? – ReBirTH

답변

3

lua_createtable(), lua_pushnumber(), lua_setfield()lua_settable()을 사용하는 간단한 예입니다.

나는 당신이 어떤 종류의 래퍼를 작성하고 있다고 가정했다. 하지만 여전히 거의 동일합니다.

/* Pushes multidimentional table on top of Lua VM stack. */ 
int 
l_push_multidim_table(lua_State *L) 
{ 
    /* Creates parent table of size 2 array elements: */ 
    lua_createtable(L, 2, 0); 

    /* Puts key of the first child table on-top of Lua VM stack: */ 
    lua_pushnumber(L, 1); 

    /*Creates first child table of size 3 non-array elements: */ 
    lua_createtable(L, 0, 3); 

    /* Fills the first child table: */ 
    lua_pushnumber(L, 1); 
    lua_setfield(L, -2, "field1"); 

    lua_pushnumber(L, 2); 
    /* setfield() pops the value from Lua VM stack. */ 
    lua_setfield(L, -2, "field2"); 

    lua_pushnumber(L, 3); 
    lua_setfield(L, -2, "field3"); 

    /* Remember, child table is on-top of the stack. 
    * lua_settable() pops key, value pair from Lua VM stack. */ 
    lua_settable(L, -3); 

    /* Pushes they key value for the second child table: */ 
    lua_pushnumber(L, 2); 

    /*Creates second child table of size 3 non-array elements: */ 
    lua_createtable(L, 0, 3); 

    /* Fills the second child table: */ 
    lua_pushnumber(L, 10); 
    lua_setfield(L, -2, "field1"); 

    lua_pushnumber(L, 20); 
    lua_setfield(L, -2, "field2"); 

    lua_pushnumber(L, 30); 
    lua_setfield(L, -2, "field3"); 

    /* Remember, child table is still on-top of the stack. 
    * lua_settable pops the key, value pair from Lua VM stack 
    * And puts child table into the parent. */ 
    lua_settable(L, -3); 

    /* Returns number of output tables: 
    * (1 multidimentional)   */ 
    return 1; 
} 

참고 : 루아 배열 값은 보통 1부터 시작합니다. 대체로 잘 작동합니다.

관련 문제