Lesson 35 of 55
9 mins readPython Custom Stringification & Callable Tables (__tostring, __call)
In Plain English
`__tostring` defines how `tostring(t)` and `print(t)` display a table. `__call` allows a table to be invoked directly like a function (`t(args)`).
Deep Dive: How It Works
__tostring: Returns a formatted description string when table is converted to string.
__call: Intercepts `table_instance(arg1, arg2)` calls.
Functor Pattern: Tables that hold internal state and act as callable functions.
Core Rules to Remember

__tostring for Debugging: Replaces generic `table: 0x...` memory addresses with meaningful text.

__call for Callable Tables: Allows table instances to be invoked directly as functions.
Live Interactive Example
Hit Run Code to see it liveCallable Tables and tostring formatting
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output Console
Click "Run Code" to view the rendered output.
How it works: __tostring formatted the print output and __call scaled the coordinate.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Implement __tostring on Entity
Create a table `local entity = { name = "Hero", hp = 100 }`.
Add a metatable with `__tostring = function(e) return e.name .. " [HP: " .. e.hp .. "]" end`.
Print `"Entity: " .. tostring(entity)`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.