[英]Need Explenation why my lua oop return incorrect value/data
I Have been browsed on the inte.net to find an explanation for this problem for 3 days, But I didn't get an explanation to solve this problem.我已经在 inte.net 上浏览了 3 天以找到对此问题的解释,但我没有得到解决此问题的解释。 Anyways, I can't solve why "gaming.child.p" return 0 instead of 11. I will be very grateful for your explanation.
无论如何,我无法解决为什么“gaming.child.p”返回 0 而不是 11。非常感谢您的解释。
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
gaming.child
and wd.child
refer to the same table. gaming.child
和wd.child
指的是同一张表。
hence modifying wd.child.p
also changes the value of gaming.child.p
as it is the same variable.因此修改
wd.child.p
也会改变gaming.child.p
的值,因为它是同一个变量。
Both wd
and gaming
don't have a field child
. wd
和gaming
都没有 field child
。 Hence when you index it Lua will refer to their metatable w
.因此,当你索引它时, Lua 将引用它们的元表
w
。 So in both cases you're actually modifing w.child.p
所以在这两种情况下你实际上是在修改
w.child.p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.