1696

8 分钟

#Lua 的 setmetatable 函数

setmetatable (table, metatable)

说明

将对象 table 的元表设为 metatable;如果 table 已有的元表包含 __metatable 字段则会引发错误。

参数

  • table - 要设置元表的对象,在 Lua 中必须是表
  • metatable - 要设置的元表,如果是 nil 则移除对象的元表

返回值

  • 返回 table

#示例

local t1 = {value = 10} local t2 = {value = 20} -- 元表,重载运算符 local metatable = { __add = function(x, y) return {value = x.value + y.value} end, __sub = function(x, y) return {value = x.value - y.value} end, __mul = function(x, y) return {value = x.value * y.value} end, __div = function(x, y) return {value = x.value / y.value} end, } -- 设置元表 setmetatable(t1, metatable) setmetatable(t2, metatable) -- 使用 print((t1 + t2).value) print((t1 - t2).value) print((t1 * t2).value) print((t1 / t2).value)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#元表的字段说明

按照惯例,Lua 使用的所有元表键都由两个下划线后跟小写拉丁字母组成。

  • __add - 加法(+)运算符
  • __sub - 减法(-)运算符
  • __mul - 乘法(*)运算符
  • __div - 除法(/)运算符
  • __mod - 模(%)运算符
  • __pow - 指数(^)运算符
  • __unm - 负(-)运算符
  • __idiv - 向下取整除法(//)运算符
  • __band - 按位与(&)运算
  • __bor - 按位或(|)运算符
  • __bxor - 按位异或(~)运算符
  • __bnot - 按位非运算(~)运算符
  • __shr - 按位左移(<<)运算符
  • __shl - 按位右移(>>)运算符
  • __concat - 连接(..)运算符
  • __len - 长度(#)运算符
  • __eq - 等于(==)运算符
  • __lt - 小于(<)运算符
  • __le - 小于或等于(<=)运算符
  • __index - 索引访问操作 table[key],当 table 不是表或 key 字段不存在时,通过这个字段访问
  • __newindex - 索引赋值操作 table[key] = value,当 table 不是表或 key 字段不存在时,通过这个字段赋值
  • __call - 调用参数 func(...),当 func 不是函数时,通过这个字段进行调用
  • __gc - 对象被垃圾收集时触发
  • __close - 对象离开作用域时触发
  • __name - 对象的名称

#推荐阅读

setmetatable - Lua 5.4 Reference Manual

创建于 2025/10/4

更新于 2025/10/4