gpt4 book ai didi

variables - Lua 元表变量声明

转载 作者:行者123 更新时间:2023-12-04 18:21:07 24 4
gpt4 key购买 nike

我不知道如何命名这个问题,因为我对正在发生的事情了解得不够多。(随意编辑)

考虑下面的代码。

函数对象:new()
o = o 或 {
x = 0
}
setmetatable(o, self)
self.__index = 自我
自我.y = 0

返回
结尾

表 = 对象:新()

后面的变量(o.x 和 self.y)有什么区别?

如果我 print_r变量 table ,只返回 x。然而,table.xtable.y可以访问。这让我意识到两者之间是有区别的。

有人可以解释有什么区别以及将变量放在不同位置的原因是什么?

最佳答案

What are the differences between the variables (o.x and self.y) later on?



你这里有两张 table , object o .
object:new内部, self引用表 object .所以 self.y是表中的一个字段 object .

o 是您在每次调用 object:new 时创建的新表. o.x是表中的一个字段 o .

o表只有一项: o["x"] ,因此当您遍历表中的条目时(如 print_r 所做的那样),这就是您将看到的全部内容。

那为什么 o.y给你一个值(value)?因为你设置表 objecto的元表,该元表的 __index字段集,因此当索引尝试在 o 上失败时, Lua 将通过 o 重试的元表(如果它有 __index 集)。

一点代码可能会使这一点更清楚:
o = { x = 33 }

print(o.x, o.y) --> 33 nil

-- let's give o a metatable
mt = { y = 20 }
setmetatable(o, mt)

-- we've given o a metatable, but that metatable doesn't have an __index member set
print(o.y) --> nil

-- metatable `handlers` are normally functions that handle events
-- here we create a handler for indexing a table if the key doesn't exist in the table:
mt.__index = function(t,k)
print("An attempt was made to index table", t, "with the key", k)
return 5150
end

-- we've given o's metatable a handler for indexing which always returns 5150
print(o.x) --> 33
print(o.y) --> 5150
print(o.z) --> 5150
print(o.donut) --> 5150

-- note that Lua has a "rawget" function, which bypasses the metatable mechanics
print(rawget(o,'x')) --> 33, we get a value, because o actually contains "x"
print(rawget(o,'y')) --> nil, back to nil, because the metatable is being ignored

-- the __index metatable handler is special. Instead of providing a function
-- to handle missing key events, you can give it a table. If an index attempt fails,
-- it will try again in the __index table
mt.__index = mt -- we could have used a third table here, but mt has the y entry we want

-- we've changed the metatable handler, so now we'll get 777
print(o.y) --> 777

-- changes to the metatable are reflected in any object using it as metatable
mt.__index.y = 999
print(o.y) --> 999

-- now we give `o` it's OWN "y" entry, so the metatable handler will no longer be invoked
o.y = 2112

print(o.y) --> 2112
print(rawget(o, 'y')) --> o really owns this "y" entry
print(mt.__index.y) --> 999, the metatable was untouched by our write to o.y

关于variables - Lua 元表变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10668972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com