需要解释为什么我的 lua oop 返回错误的值/数据

发布于 2025-01-15 20:13:29 字数 740 浏览 2 评论 0原文

我已经在互联网上浏览了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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

π浅易 2025-01-22 20:13:29

gaming.childwd.child 引用同一个表。

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文