我对函数调用via .和via 之间的区别感到困惑:
> x = {foo = function(a,b) return a end, bar = function(a,b) return b end, }
> return x.foo(3,4)
3
> return x.bar(3,4)
4
> return x:foo(3,4)
table: 0x10a120
> return x:bar(3,4)
3
Run Code Online (Sandbox Code Playgroud)
什么是:做什么?
如何向表类型添加方法?我正在尝试编写一个搜索表值的方法.到目前为止我有.
function table:contains(value)
for _, v in ipairs(self) do
if v == value then return true end
end
return false
end
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试做以下事情时.
t = {'four', 'five', 'six'}
t:contains('five')
Run Code Online (Sandbox Code Playgroud)
我收到了错误.
stdin:1: attempt to call method 'contains' (a nil value)
Run Code Online (Sandbox Code Playgroud)
有什么建议?
很明显,getmetatable可以访问几种类型的元表:
getmetatable("")
getmetatable({})
getmetatable(newproxy(true))
Run Code Online (Sandbox Code Playgroud)
然而,似乎你无法获得其他类型的元数据(除了函数).似乎没有办法访问数字,布尔值或零的元数据.
我也想知道是否能够访问整个表类型的元表.能够做这样的事情:
({}) + ({})
Run Code Online (Sandbox Code Playgroud)