表不作为我班上的属性

发布于 2025-02-11 07:14:26 字数 573 浏览 1 评论 0原文

我有这样的情况:

TestClass = { param = { n = 5 } }
function TestClass:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end
function TestClass:update(n)
    n = n or 1
    self.param.n = self.param.n + n
end

问题是,当我实例化一个像:obj = testClass:new()的对象时,更新方法未更新存储在obj 表,但它更改了默认表中的值:testClass

有没有办法解决此问题?我已经查找了 tutorial> tutorial lua的创建者,但他们对桌子没有说什么属性。

I have a situation like this:

TestClass = { param = { n = 5 } }
function TestClass:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end
function TestClass:update(n)
    n = n or 1
    self.param.n = self.param.n + n
end

The issue is that when I instantiate an object like: obj = TestClass:new() the update method doesn't update the value stored in the obj table but instead it changes the value inside the default table: TestClass

Is there a way to fix this? I already looked up the tutorial by the creators of lua but they say nothing about tables as attributes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

埖埖迣鎅 2025-02-18 07:14:26

我认为您应该这样做:

function TestClass:new(o)
    o = o or { param = { n = 5 } }
    setmetatable(o, self)
    self.__index = self
    return o
end

I think you should do it like this then:

function TestClass:new(o)
    o = o or { param = { n = 5 } }
    setmetatable(o, self)
    self.__index = self
    return o
end
半山落雨半山空 2025-02-18 07:14:26

我解决了这个问题,问题是表是通过参考存储的,而不是值,因此解决方案是在实例时在o对象内创建表(testClass:new()方法)。

要自动执行此操作,并且仅用于未传递的参数,我写了这个小功能:

function setDefaults(o, def)
    for k,v in pairs(def) do
        o[k] = o[k] or v
    end
end

简单地使用它:

function TestClass:new(o)
    o = o or {}
    setDefaults(o, {
        param = { n = 5 }
    })
    setmetatable(o, self)
    self.__index = self
    return o
end

我也想非常感谢 u/jackmacwindowslinux 和ivo Beckers帮助我找到了这个解决方案。

I solved this and the problem was that tables are stored by reference, not value so the solution was to create the table inside the o object at the time of instancing (the TestClass:new() method).

To do this automatically and only for params that are not passed in I wrote this little function:

function setDefaults(o, def)
    for k,v in pairs(def) do
        o[k] = o[k] or v
    end
end

And it is simply used like this:

function TestClass:new(o)
    o = o or {}
    setDefaults(o, {
        param = { n = 5 }
    })
    setmetatable(o, self)
    self.__index = self
    return o
end

I also wanted to thank a lot u/JackMacWindowsLinux and Ivo Beckers for helping me find this solution.

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