Lua Guide
Search…
Metatables
Metatables are the underlying implementation of objects in Lua, they define custom behaviors such as addition between 2 objects, subtraction, accessing the value, etc.
Each of those are called metamethods, and they all begin with __.
All metamethods (Lua 5.1)
1
__eq : Equality : a == b
2
__le : Less than : a < b
3
__ge : Greater than : a > b
4
__add : Addition : a + b
5
__sub : Subtraction : a - b
6
__mul : Multiplication : a * b
7
__div : Division : a / b
8
__pow : Exponentation : a ^ b
9
__unm : Negation : -a
10
__mod : Modulus : a % b
11
__concat : Concatenation : a .. b
12
__metatable : Metatable : getmetatable(a)
13
__call : Call : table()
14
__index : Indexing : table.x | table['x']
15
__newindex : New Index : table.x = 'abc'
16
__mode : Weak References : mt.__mode = 'k'
17
__tostring : String Conversion : tostring(a)
Copied!
By default whenever you have a string, it has a metatable attached to it as you can see here:
1
local s = "abc"
2
3
print(getmetatable(s)) -- {__index = table: 0x56458af94c30}
4
5
for k, v in pairs(getmetatable(s).__index) do
6
print(k, v)
7
end
Copied!
When attempting to index the string, it instead returns the string library table. Which is why if you run this code, you'll see the __index of the metatable print this out:
1
dump function: 0x557e9eddcba0
2
byte function: 0x557e9eddcd70
3
reverse function: 0x557e9eddba30
4
lower function: 0x557e9eddbcd0
5
gsub function: 0x557e9eddd810
6
upper function: 0x557e9eddb980
7
sub function: 0x557e9eddcc50
8
match function: 0x557e9eddd7f0
9
gmatch function: 0x557e9eddc000
10
rep function: 0x557e9eddbae0
11
len function: 0x557e9eddbc70
12
char function: 0x557e9eddc060
13
format function: 0x557e9eddc1c0
14
find function: 0x557e9eddd800
Copied!
You can directly access these by indexing the string directly, instead of going through the string library:
1
local s = "abc"
2
print(s.len(s)) -- 3
3
print(s:len()) -- 3
Copied!
The second print uses the : syntactic sugar, both are equivalent, but the second is preferred for shorter code. The left hand of the : will be inserted as the first argument to string.len, and will result in the equivalent code: string.len(s).
You can create your own tables and define metatables for them to do as you'd like, like so:
1
local t = {1, 2, 3}
2
3
print(tostring(t)) -- table: 0x55b410c31620
4
5
setmetatable(t, {
6
__tostring = function(self)
7
return table.concat(self, ', ')
8
end
9
})
10
11
print(tostring(t)) -- __tostring invoked, output is 1, 2, 3
Copied!
Here we define a custom metamethod for the tostring function for the table, which instead calls table.concat to concatenate all table values in sequence with a separator of , inbetween each value.
Copy link