あなたが見る必要がある2つのことがあります:
- への次の呼び出しの前に、元のキーがスタックに残されていることを確認して
lua_next
ください。luaL_checkstring
非文字列キーを文字列に変換します (結果の文字列がテーブルにないため、無効なキーになります)。これはluaL_checkstring
、元のキーの代わりにキーのコピーを渡すことで最も簡単に実行できます。
- ループを通過するたびにスタック構造を保持する (つまり、プッシュするだけの数の値をポップする) ことを確認してください。
関数は の負の値に対してのみ機能しますindex
。キーを押した後も がテーブルを指しているindex--;
ことを確認するのは正しいですが、負の場合 (つまり、スタックの上部に対して相対的) に限ります。が絶対インデックスまたは疑似インデックスの場合、これにより、間違った項目。最も簡単な回避策は、テーブルへの別の参照をスタックの一番上にプッシュすることです。index
index
index
デモ用の最小限の C プログラムを次に示します。
#include <lauxlib.h>
#include <lua.h>
static void iterate_and_print(lua_State *L, int index);
int main(int ac, char **av)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// Create a table and put it on the top of the stack
luaL_loadstring(L, "return {one=1,[2]='two',three=3}");
lua_call(L, 0, 1);
iterate_and_print(L, -1);
return 0;
}
static void iterate_and_print(lua_State *L, int index)
{
// Push another reference to the table on top of the stack (so we know
// where it is, and this function can work for negative, positive and
// pseudo indices
lua_pushvalue(L, index);
// stack now contains: -1 => table
lua_pushnil(L);
// stack now contains: -1 => nil; -2 => table
while (lua_next(L, -2))
{
// stack now contains: -1 => value; -2 => key; -3 => table
// copy the key so that lua_tostring does not modify the original
lua_pushvalue(L, -2);
// stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
const char *key = lua_tostring(L, -1);
const char *value = lua_tostring(L, -2);
printf("%s => %s\n", key, value);
// pop value + copy of key, leaving original key
lua_pop(L, 2);
// stack now contains: -1 => key; -2 => table
}
// stack now contains: -1 => table (when lua_next returns 0 it pops the key
// but does not push anything.)
// Pop table
lua_pop(L, 1);
// Stack is now the same as it was on entry to this function
}