需要解释为什么我的 lua oop 返回错误的值/数据
我已经在互联网上浏览了3天来找到这个问题的解释,但我没有得到解决这个问题的解释。无论如何,我无法解决为什么“gaming.child.p”返回0而不是11。我将非常感谢您的解释。
这是代码:
local X = {
p = 1,
diffElementPls = "man"
};
local Y = {__index = X};
function interface()
local o = {};
return setmetatable(o, Y);
end
local w = {
something = "u found me",
child = interface()
};
local noob = {__index = w};
function new()
local o = {};
return setmetatable(o, noob);
end
local gaming = new();
local wd = new()
gaming.something = "noob"
gaming.child.p += 10
wd.child.p = 0
print(gaming.something, wd.something, gaming.child.p, wd.child.p) -- print noob u found me 0 0 instead of noob u found me 11 0
I Have been browsed on the internet to find an explanation for this problem for 3 days, But I didn't get an explanation to solve this problem. Anyways, I can't solve why "gaming.child.p" return 0 instead of 11. I will be very grateful for your explanation.
Here's the code :
local X = {
p = 1,
diffElementPls = "man"
};
local Y = {__index = X};
function interface()
local o = {};
return setmetatable(o, Y);
end
local w = {
something = "u found me",
child = interface()
};
local noob = {__index = w};
function new()
local o = {};
return setmetatable(o, noob);
end
local gaming = new();
local wd = new()
gaming.something = "noob"
gaming.child.p += 10
wd.child.p = 0
print(gaming.something, wd.something, gaming.child.p, wd.child.p) -- print noob u found me 0 0 instead of noob u found me 11 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
gaming.child
和wd.child
引用同一个表。因此,修改
wd.child.p
也会更改gaming.child.p
的值,因为它是同一个变量。wd
和gaming
都没有字段child
。因此,当你索引它时,Lua 将引用它们的元表w
。因此,在这两种情况下,您实际上都是在修改w.child.p
gaming.child
andwd.child
refer to the same table.hence modifying
wd.child.p
also changes the value ofgaming.child.p
as it is the same variable.Both
wd
andgaming
don't have a fieldchild
. Hence when you index it Lua will refer to their metatablew
. So in both cases you're actually modifingw.child.p