如何解决我不明白这里的语法 编辑:
我在 roblox devforum 上看到一篇关于元表的帖子,在代理表部分我不明白这段代码的语法
local function TrackDownTable()
local t = {x = 5}
local proxy = setmetatable({},{
__index = function(_,key)
print("User indexed table with "..key)
return t[key]
end,__newindex = function(_,key,value)
print("User made or update the field "..key.." with the value "..value.." in table")
t[key] = value
end
})
return proxy
end
local t = TrackDownTable()
t.x = 5
print(t.x)
在这部分
local t = TrackDownTable()
t.x = 5
local t = TrackdownTable()
有什么作用?以及这部分 t.x = 5
如何访问 proxy
表?
解决方法
这是一个非常简单的代理演示表。
代理表是控制表访问的表。例如,您可以使用它来跟踪表访问或实现只读表。
如果不通过代理表,您就无法访问或修改该表的数据。
其实很简单。 TrackDownTable 创建 t
,它只是一些演示表。我们只需要一个简单的表来演示表访问。因此,我们创建了一个包含单个字段 {x=5}
local proxy = setmetatable({},{
__index = function(_,key)
print("User indexed table with "..key)
return t[key]
end,__newindex = function(_,key,value)
print("User made or update the field "..key.." with the value "..value.." in table")
t[key] = value
end
})
可以改写为:
local metatable = {}
metatable.__index = function(_,key)
print("User indexed table with "..key)
return t[key]
end
metatable.__newindex = function(_,value)
print("User made or update the field "..key.." with the value "..value.." in table")
t[key] = value
end
local proxy = {}
setmetatable(proxy,metatable)
此代码简单地创建了一个带有 __index
和 __newindex
元方法的元表,并将其设置为我们演示表的元表。
__index
在您索引代理字段时被调用。
__newindex
在您为代理中的索引赋值时被调用。
编辑:
想知道这个assignmentt.x=5是怎么传给代理的 table as ``local t = TrackDownTable() ``` 当 t.x = 5 发生什么 是不是,它把 5 作为参数传递给函数?
t.x = 5
是索引分配。如果你执行这个 Lua 会检查在 "x"
中是否有键为 t
的字段。由于 t["x"]
在此范围内为零,它将检查是否存在元表。有,所以它会调用我们的 __newindex
元方法,它有 3 个参数(表、键、值)
所以我们实际上调用了 getmetatable(t).__index(t,"x",5)
,它会在内部将值分配给 TrackDownTable 中定义的本地 t.x
。
在这个例子中两个表都被命名为 t
有点误导。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。