Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need Explenation why my lua oop return incorrect value/data

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading