我在lua文件中有一张桌子。
这是表:
main = {}
main["first"] = {
{name = "sammy", type = "dog", age = 2, color = "blue"},
{name = "tom", type = "cat", age = 3, color = "orange"},
.
.
.
.
}
main["second"] = {
{name = "grim", type = "cow", age = 1, color = "green"},
{name = "jerry", type = "horse", age = 2, color = "grey"},
.
.
.
.
}
该表有两个表。我想阅读main中的所有表格。所以我写了这段代码。(我使用delphi。plua_state表示lua_state的指针)
这是我的代码:
procedure TForm1.PrintTable(l: Plua_State);
var
TempStr : String;
begin
lua_pushnil(l);
TempStr := '';
while lua_next(l,-2) <> 0 do
begin
case lua_type(l,-1) of
LUA_TTABLE :
PrintTable(l);
else
TempStr := TempStr + lual_checkstring(L, -2) + '='
+ lua_typename(L, lua_type(L, -1)) + ',';
end;
lua_pop(l,1);
end;
fStringList.Add(TempStr);
end;
该代码在主表中打印键和值类型。但是,如果我更改lua_typename(L, lua_type(L, -1))
为lual_checkstring(L, -1)
,则无法使用。我要打印键和值。
如何打印值?
使用lua_next
多个字符串API函数时,请务必小心,因为它们会更改堆栈上的值,这会造成混淆lua_next
。从手册:
在遍历表时,请勿直接在键上调用lua_tolstring,除非您知道键实际上是字符串。回想一下lua_tolstring可能会更改给定索引处的值;这混淆了对lua_next的下一次调用。
因此,呼吁lua_tostring,lua_tolstring,或luaL_checklstring通过推一键lua_next
将改变键为一个字符串。
如您所知,最好lua_type
在调用lua_tolstring
(或调用它的任何API函数)之前确保该值确实是字符串,或者推送可以弹出的键的副本,而保留lua_next
未经修改的原始键的返回值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句