开发者

Why do some tables in Lua display differently when print(sometable) is called on them?

开发者 https://www.devze.com 2023-01-12 18:10 出处:网络
I\'m confused by behavior I\'m seeing 开发者_如何学Gowhen I use luaxml to parse an XML string.The Lua doc states that calling print() on a table variable as such:

I'm confused by behavior I'm seeing 开发者_如何学Gowhen 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?


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).


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号