🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Metamethod __call

The __call metamethod makes a table callable like a function. Calling the table runs the __call field with the table and the call arguments.

A call can add to a stored count

A counter table starts at zero. Each call adds its step to the stored count and returns the new count.

local t = {count = 0}
setmetatable(t, {__call = function(t, step)
  t.count = t.count + step
  return t.count
end})
local a = t(5)
local b = t(3)
print(a, b)

A call can greet by name

A greeter table has no stored greeting. Its call field builds a greeting from the name in the call.

local greet = {}
setmetatable(greet, {__call = function(t, name)
  return "Hello, " .. name
end})
print(greet("Mia"))

A call can double a stored value

A calculator table holds a value of six. Its call field returns twice that stored value.

local calc = {value = 6}
setmetatable(calc, {__call = function(t)
  return t.value * 2
end})
print(calc())

Example

local add = {base = 10}
setmetatable(add, {__call = function(t, a, b)
  return t.base + a + b
end})
local x = add(1, 2)
local y = add(5, 0)
print(x, y)
print(add.base)

Key points

  • Callable table: a table with a __call field can be used in a call.
  • First argument: the table itself reaches the __call field as its first argument.
  • Call arguments: the values in the call reach the __call field after the table.
  • Return value: the result of the __call field becomes the result of the call.
  • Stored fields: the __call field can read and change fields stored in the table.

In this example, an adder table holds a base of ten. Each call adds the base and the two call arguments. The base itself stays ten after both calls.

Note

a table without a __call field cannot be called.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when a table with a __call field is called?