为什么 Lua 中的某些表在调用 print(sometable) 时显示不同?
当我使用 luaxml 解析 XML 字符串时所看到的行为让我感到困惑。 Lua 文档指出,在表变量上调用 print()
print(type(t))
print(t)
会产生如下输出:
t2: table
t2: table: 0095CB98
但是,当我这样使用 luaxml 时:
require "luaxml"
s = "<a> <first> 1st </first> <second> 2nd </second> </a>"
t = xml.eval(s)
print("t: ", type(t))
print("t: ", t)
我得到以下输出:
t: table
t: <a>
<first>1st</first>
<second>2nd</second>
</a>
Why does print(t)
不返回与第一个示例类似的结果?
I'm confused by behavior I'm seeing when I use luaxml to parse an XML string. The Lua doc states that calling print() on a table variable as such:
print(type(t))
print(t)
will result in output like this:
t2: table
t2: table: 0095CB98
However, when I use luaxml as such:
require "luaxml"
s = "<a> <first> 1st </first> <second> 2nd </second> </a>"
t = xml.eval(s)
print("t: ", type(t))
print("t: ", t)
I get the following output:
t: table
t: <a>
<first>1st</first>
<second>2nd</second>
</a>
Why does print(t)
not return a result that looks like the first example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
print
函数使用tostring
将其参数转换为字符串。当使用表调用
tostring
时,并且表的元表具有__tostring
字段,则tostring
以表作为参数调用相应的值,并使用调用的结果作为其结果。我怀疑luaxml在从
xml.eval(s)
返回的表上有这样一个__tostring
元方法。The
print
function usestostring
to convert its arguments to strings.When
tostring
is called with a table, and the table's metatable has a__tostring
field, thentostring
calls the corresponding value with the table as an argument, and uses the result of the call as its result.I suspect that luaxml has such a
__tostring
metamethod on the table returned fromxml.eval(s)
.您可以在表的元表上定义函数
__tostring
来获取此结果。当您将该表传递给 print() 时,如果您的元表上有一个 __tostring 函数,则 print() 将输出评估该函数的结果,而不是使用默认方法(仅打印内存)表的地址)。You can define the function
__tostring
on a table's metatable to get this result. When you pass that table to print(), if you have a__tostring
function on your metatable, print() will output the result of evaluating that function instead of using the default method (which just prints the memory address of the table).