完全なCネストはlua 5を遍歴する.3 tableおよびprintの書き換え方法
2651 ワード
この章の学習を通じて、tableのネスト遍歴をマスターすることができます.tableの内部は何層のtableをネストしてもいいです.書き換えたprintでは、パラメータを何個書いてもネストtableを何個書いてもコンテンツを出力できます.
g_stringAは筆者のライブラリの中の1つの文字列クラスで、直接下のコードを使ってコンパイルして通過しないで、g_stringAを別のクラスに置き換える.
GxxLuaManager::GetStringFromLuaをluaに置き換えるtostring
下のコードを見てみると、tableを巡るネストの論理が理解できるはずです.
print関数を再登録すれば置き換えられます
lua_register(m_L, "print", gxx_print);
luaスクリプトを実行します.
出力結果:
{name=Guo,age=18,fav={1=観光,2=スポーツ,3=美人}}
g_stringAは筆者のライブラリの中の1つの文字列クラスで、直接下のコードを使ってコンパイルして通過しないで、g_stringAを別のクラスに置き換える.
GxxLuaManager::GetStringFromLuaをluaに置き換えるtostring
下のコードを見てみると、tableを巡るネストの論理が理解できるはずです.
void gxx_table_to_str( lua_State* L, int idx, g_stringA& res)
{
if (!lua_istable(L, idx))
{
return;
}
else {
res.AppendChar('{');
// table
lua_pushvalue(L, idx);
int it = lua_gettop(L);
// nil , key
lua_pushnil(L);
while (lua_next(L, it))
{
// :-1 => value; -2 => key; index => table
// key , lua_tostring key
lua_pushvalue(L, -2);
// :-1 => key; -2 => value; -3 => key; index => table
if (!lua_istable(L, -2))
{
// table
const char* key = lua_tostring(L, -1);
if(lua_isboolean(L, -2))
res.AppendFormat("%s=%s,", key, lua_toboolean(L, -2) ? "true" : "false");
else if(lua_isfunction(L, -2))
res.AppendFormat("%s=%s,", key, "function");
else
res.AppendFormat("%s=%s,", key, GxxLuaManager::GetStringFromLua(L, -2));
}
else
{
const char* key = lua_tostring(L, -1);
res.Append(key);
res.AppendChar('=');
// -2 => value
gxx_table_to_str(L, -2, res);
//lua_pop(L, 1);
res.AppendChar(',');
}
// value key, key lua_next
lua_pop(L, 2);
// :-1 => key; index => table
}
// :index => table ( lua_next 0 key )
res.TrimRight(',');
res.AppendChar('}');
// table
lua_pop(L, 1);
}
}
int gxx_print( lua_State* L )
{
int n = lua_gettop(L);
g_stringA strPrint;
for (int p = 1; p <= n; p++)
{
if (lua_istable(L, p))
gxx_table_to_str(L, p, strPrint);
else if(lua_isboolean(L, p))
strPrint.Append(lua_toboolean(L, p) ? "true" : "false");
else if(lua_isfunction(L, p))
strPrint.Append("function");
else
strPrint.Append(GxxLuaManager::GetStringFromLua(L, p));
strPrint.AppendChar('\t');
}
strPrint.TrimRight('\t');
TRACE(strPrint);
TRACE("\r
");
return 0;
}
print関数を再登録すれば置き換えられます
lua_register(m_L, "print", gxx_print);
luaスクリプトを実行します.
a = {
name = 'Guo',
age = '18',
fav = {' ',' ',' '}
}
print (a)
出力結果:
{name=Guo,age=18,fav={1=観光,2=スポーツ,3=美人}}