需要解释为什么我的 lua oop return 不正确 value/data

Need Explenation why my lua oop return incorrect value/data

我在网上找了3天这个问题的解释,但是没有找到解决这个问题的解释。无论如何,我无法解决为什么“gaming.child.p”return 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

gaming.childwd.child 指的是同一个 table.

因此修改 wd.child.p 也会更改 gaming.child.p 的值,因为它是同一个变量。

wdgaming 都没有字段 child。因此,当你索引它时,Lua 将引用它们的元table w。所以在这两种情况下你实际上是在修改 w.child.p