Lua Metamethods: Tostring and Concat
The __tostring and __concat metamethods control how a table turns into text. They define the printed form of a table and how it joins with other text.
A point prints as a pair in brackets
A point holds an x and a y. Its text field returns the pair in round brackets.
local p = {x = 3, y = 4}
setmetatable(p, {__tostring = function(t)
return "(" .. t.x .. ", " .. t.y .. ")"
end})
print(p)A label joins on either side
An item holds a label of box. Its join field handles the item on the left and on the right.
local item = {label = "box"}
setmetatable(item, {__concat = function(a, b)
if type(a) == "table" then
return a.label .. b
else
return a .. b.label
end
end})
print(item .. " is ready")
print("Item " .. item)Tostring gives the same string as print
A money table holds dollars and cents. The tostring function uses the same field as print.
local m = {dollars = 12, cents = 50}
setmetatable(m, {__tostring = function(t)
return "$" .. t.dollars .. "." .. t.cents
end})
print(m)
print(tostring(m))Example
local p = {x = 2, y = 5}
setmetatable(p, {__tostring = function(t)
return "(" .. t.x .. ", " .. t.y .. ")"
end, __concat = function(a, b)
if type(a) == "table" then
return "(" .. a.x .. ", " .. a.y .. ")" .. b
else
return a .. "(" .. b.x .. ", " .. b.y .. ")"
end
end
})
print(p)
print(p .. " moved")
print("Point " .. p)Key points
- __tostring: the field Lua calls to turn a table into a string for printing.
- __concat: the field Lua calls when a table is joined with another value.
- Print: printing a table with a __tostring field shows the string that field returns.
- Join result: a __concat field should return the joined string.
- Both orders: a __concat field must handle the table on either side of the join.
In this example, a point holds an x and a y with both text fields set. Printing the point shows the pair in round brackets. Joining the point on either side keeps the same pair form in the joined string.
Note
a table without a __tostring field does not show its fields when printed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does print show for a table with a __tostring field?