Codectionary / Developer documentation / Luau

Luau callable tables

The __call metamethod lets a table behave like a function while retaining state in fields. The first argument to the metamethod is the called table, followed by ordinary call arguments.

Syntax

setmetatable(state, {__call = function(self, value) ... end})

Examples

Luau callable tables

Run as a standalone current Luau script, or as a Script in Roblox Studio ServerScriptService. No Roblox engine APIs are required; type-annotated syntax is not standard Lua.

local counter = setmetatable({total = 0}, {
    __call = function(self, amount)
        self.total += amount
        return self.total
    end
})
print(counter(3))
print(counter(4))
print(counter.total)
  1. Output: 3, 7, 7. Both calls mutate the same state table before returning the running total.

Best practices

  • Use callable tables only when the call syntax makes the API clearer. Document mutation and keep metatables stable after construction.

Runtime & versions

Luau host; Roblox engine examples require Roblox Studio. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Luau documentation

Specifications & further reading