1

ネストされたテーブルで定義された値があると仮定します: tab["m"]["b"] = {}. Lua では、前のステートメントで定義できます。

C APIでも可能ですか?tab具体的には、、などを個別に押す代わりにm、単一の文字列で値を選択しますtab["m"]["b"]

(以下のコードのように) 単一の値で行われるように、それを押して選択することはできません。

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

1 に答える 1

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);
于 2014-05-24T22:05:35.740 に答える