为什么 Lua 中的某些表在调用 print(sometable) 时显示不同?

发布于 2024-09-15 04:57:48 字数 675 浏览 2 评论 0原文

当我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

递刀给你 2024-09-22 04:57:48

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

当使用表调用 tostring 时,并且表的元表具有 __tostring 字段,则 tostring 以表作为参数调用相应的值,并使用调用的结果作为其结果。

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

The print function uses tostring to convert its arguments to strings.

When tostring is called with a table, and the table's metatable has a __tostring field, then tostring 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 from xml.eval(s).

夜光 2024-09-22 04:57:48

您可以在表的元表上定义函数 __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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文