为什么在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>

为什么 print(t) 没有返回类似第一个示例的结果呢?

原文链接 https://stackoverflow.com/questions/3536307

点赞
stackoverflow用户33252
stackoverflow用户33252

print 函数使用 tostring 将参数转换为字符串。

tostring 被调用时传入的是一个表,并且这个表的元表中具有 __tostring 域,那么 tostring 会使用传入的表作为参数调用相应的值,并将调用的结果作为它的结果。

我怀疑 luaxml 将在从 xml.eval(s) 返回的表中具有这样的 __tostring 元方法。

2010-08-21 04:35:45
stackoverflow用户34218
stackoverflow用户34218

你可以在表的元表上定义函数__tostring来得到这个结果。当你将这个表传递给print()时,如果你的元表上有一个__tostring函数,print()将输出评估该函数的结果,而不是使用默认方法(仅打印表的内存地址)。

2010-08-21 04:37:22