表不作为我班上的属性
我有这样的情况:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您应该这样做:
I think you should do it like this then:
我解决了这个问题,问题是表是通过参考存储的,而不是值,因此解决方案是在实例时在
o
对象内创建表(testClass:new()
方法)。要自动执行此操作,并且仅用于未传递的参数,我写了这个小功能:
简单地使用它:
我也想非常感谢 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 (theTestClass:new()
method).To do this automatically and only for params that are not passed in I wrote this little function:
And it is simply used like this:
I also wanted to thank a lot u/JackMacWindowsLinux and Ivo Beckers for helping me find this solution.