lua 元表与元方法
元表
相关函数
# setmetatable(table,metatable): 为表设置元表
Sets the metatable for the given table. This function returns table.
If metatable is nil, removes the metatable of the given table.
If the original metatable has a __metatable field, raises an error.
* 为table设置元表metatable,返回设置后的表table
* 如果元表为nil,则会删除原先设置的元表
* 如果元表(metatable)中存在__metatable字段,setmetatable失败
* 注:5.4.4版本元表中含有__metatable字段,不会报错,可正常设置
# getmetatable(table): 获取指定表对象的元表
If object does not have a metatable, returns nil. Otherwise,
if the object's metatable has a __metatable field, returns the
associated value. Otherwise, returns the metatable of the given object
* 表对象没有元表,返回nil
* 如果表对象的元表有字段__metatable,返回字段对应的值
* 否则返回元表对象
示例:元表设置、获取
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
-- 表对象t、元表meta
> t={1,2,3,4,5,6}
> meta={}
-- 为t设置元表meta,设置后返回表对象t
> setmetatable(t,meta)
table: 0x600000314140
-- 获取t的元表
> getmetatable(t)
table: 0x600000310100
-- 遍历输出t
> for key,value in pairs(setmetatable(t,meta)) do print(key,value) end
1 1
2 2
3 3
4 4
5 5
6 6
-- 遍历输出meta
> for key,value in pairs(getmetatable(t)) do print(key,value) end
-- 设置元表:key='瓜田李下'
> meta.key='瓜田李下'
-- 遍历输出meta
> for key,value in pairs(getmetatable(t)) do print(key,value) end
key 瓜田李下
示例:元表含有__metatable字段
Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
> t={1,2,3,4,5,6}
> meta={__metatable='瓜田李下'}
-- 设置元表,可正常设置
> setmetatable(t,meta)
table: 0x60000029c8c0
-- 获取元表,返回元表__metatable字段对应的value
> getmetatable(t,meta)
瓜田李下