2014-05-24 5 views
1

중첩 테이블에 정의 된 값이 있다고 가정합니다. tab["m"]["b"] = {}. 루아에서는 이전 문장으로 정의 할 수 있습니다.Lua C API를 사용하여 선택기 문자열로 중첩 값 선택

C API에서도 가능합니까? 특히 tab, m 등을 개별적으로 푸시하는 대신 단일 문자열 tab["m"]["b"]으로 값을 선택하십시오.

단일 값으로 수행하는 것처럼 (아래 코드와 같이) 밀고 선택하는 것은 효과가 없습니다.

lua_pushstring(state, "tab[\"m\"][\"b\"]"); 
lua_gettable(state, LUA_GLOBALSINDEX); 

답변

2

C API에서는 불가능합니다. 이 기능이 필요한 경우 도우미 함수를 추가하여 할 수 있습니다.

/* Pushes onto the stack the element t[k_1][...][k_n] 
* where t is the value at the given index and 
* k_1, ..., k_n are the elements at the top of the stack 
* (k_1 being furthest from the top of the stack and 
* k_n being at very the top of the stack). 
*/ 
void recursive_gettable(lua_State *L, int index, int n) /*[-n,+1,e]*/ { 
    luaL_checkstack(L, 2, NULL);   /*[k_1,...,k_n]*/ 
    lua_pushvalue(L, index);    /*[k_1,...,k_n,t]*/ 
    for (int i = 1; i <= n; ++i) { 
     lua_pushvalue(L, -(n+1)+(i-1)); /*[k_1,...,k_n,t[...][k_(i-1)],k_i]*/ 
     lua_gettable(L, -2);    /*[k_1,...,k_n,t[...][k_i]]*/ 
    } 
    lua_replace(L, -1, -(n+1));   /*[t[...][k_n],k_2,...,k_n]*/ 
    lua_pop(L, n-1);      /*[t[...][k_n]] */ 
} 

/*usage:*/ 
luaL_checkstack(L, 3, NULL); 
lua_pushstring(L, "tab"); 
lua_pushstring(L, "m"); 
lua_pushstring(L, "b"); 
recursive_gettable(L, LUA_GLOBALSINDEX, 3);