Home > Blockchain >  Need Explenation why my lua oop return incorrect value/data
Need Explenation why my lua oop return incorrect value/data

Time:03-19

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

CodePudding user response:

gaming.child and wd.child refer to the same table.

hence modifying wd.child.p also changes the value of gaming.child.p as it is the same variable.

Both wd and gaming don't have a field child. Hence when you index it Lua will refer to their metatable w. So in both cases you're actually modifing w.child.p

  • Related