Lua中的重载表__tostring函数

我有一个简单的问题:我想在 Lua 中使 print 函数打印表的内容,而不仅仅是打印单词 "table" 和一个内存地址。例如:

> tab = {}
> tab[1]="hello"
> tab[2]="there"
>
> print(tab)
table: 0x158ab10
-- 应该是
1   hello
2   there

我知道我可以通过执行类似于以下内容来实现此效果:

for i,v in pairs(tab) do print(i,v) end

但我希望它仅在执行 print(tab) 时发生,而不必每次编写循环。能做到吗?

点赞
用户151501
用户151501

你需要在每个创建的表格上设置 __tostring()。一个简单的方法是使用漂亮打印技术。

请查看此链接:http://lua-users.org/wiki/TableSerialization

2012-10-12 17:21:23
用户221509
用户221509

你可以通过覆盖全局的 tostring() 函数来实现。这也是 print() 在其参数上调用的函数。

如果你不想编写任何代码,可以尝试 Steve Donovan 的 Microlight 库。你可以按如下方式使用它:

tostring = require "ml".tstring
tab = {"abc", 3.14, print, key="value", otherkey={1, 2, 3}}
print(tab) --> {"abc",3.14,function: 0x7f5a40,key="value",otherkey={1,2,3}}
2012-10-13 14:41:49