Lua - Customizing String Representation
Lua provides a default string representation of tables in 0xXXXXXXXX format but we often need to get a more informative representation of a Lua table. This helps in tracing or debugging. To assist in this functionality, Lua provides __tostring metamethod which is called in following scenarios −
table is printed using print statement.
tostring() function is called with table as argument to get the string representation.
Lua calls the implementation function of __tostring metamethod when print statement or tostring() function is called on a table. If __tostring is not present or metatable is not defined at all then Lua will return the default representation in 0xXXXXXXXX format. Let's check each scenario with help of examples.
Example - String representation of a table without __tostring metamethod
In case, we're not having __tostring metamethod for the table, Lua will give a default format in example below −
main.lua
-- define a table
local person = { name = "Julie", age = 30 }
-- prints person in table: 0xXXXXXXXX format
print(person)
-- tostring() method too returns the same default format string
print(tostring(person))
Output
When we run the above program, we will get the following output−
table: 0x562cdb1c4f40 table: 0x562cdb1c4f40
Example - Implementing __tostring metamethod
In below example, we've a more relevant example where we are implementing a __tostring metamethod to get a human readable formatted string as shown below −
main.lua
-- define a table
local person = { name = "Julie", age = 30 }
setmetatable(person, {
__tostring = function(t)
return "[Name: "..t.name .. ", Age: " .. t.age.."]"
end })
-- prints person in table: [Name: Julie, Age: 30 ] format
print(person)
-- tostring() method too returns the same format string
print(tostring(person))
Output
When we run the above program, we will get the following output−
[Name: Julie, Age: 30] [Name: Julie, Age: 30]