tags:

views:

45

answers:

2

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?
Thanks,
-Gerald

+4  A: 

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

Doug Currie
I suspected something of this nature was the case, but didn't know print() behaved in this fashion. Is there a way to "reflect" (not sure if that term has meaning here) on the table object in question to see its metamethods?
Gerald
I'll answer my own question since your answer above lead me to a solution: mt = getmetatable(t) for key, value in pairs(mt) do print(key, value) endwill print the metamethods....And setmetatable(t, nil) removes it if need be as well Thanks! -Gerald
Gerald
Btw, if anyone reading this is using luaxml be advised that the table returned by xml.eval() is indexed starting with 0, not 1.
Gerald
A: 
Jason Coco