menu_book Course Curriculum (Lua) expand_more
__tostring
Learn __tostring in Lua through a focused explanation, a dedicated topic-specific example, an engineering boundary, and a mastery check.
__tostring is an atomic Lua topic inside Metatables. The example uses the named construct directly so you can see its syntax, data flow, and observable behavior.
Read the code by locating the exact feature named __tostring, then trace the value before and after that feature runs. This lesson is intentionally isolated from neighboring topics: changing identifiers alone would not reproduce the same behavior because the construct itself is different.
Topic-specific example
local t=setmetatable({id=7},{__tostring=function(x)return "Item#"..x.id end});print(t)
For __tostring, test the boundary that makes the feature meaningful: invalid input, an empty value, a missing branch, lifecycle/cleanup, or a type/runtime constraint. Do not infer correctness only from the happy path.