Lua中Button:new无法调用self.load()?需在实例化时执行该方法
问题分析与修正
你的代码无法正常运行,核心问题有3处:
- 属性赋值错误:构造函数里把
x、text赋值给了self(也就是Button类本身),而不是新创建的实例o。这会导致所有Button实例共享同一组属性,且实例自身没有独立的x和text值。 - 方法调用方式错误:
load方法里用.调用renderText,没有自动传递当前实例作为self,应该用:调用。 - 调用load的对象错误:构造函数里调用
self:load()时,self指向的是Button类,不是刚创建的实例,应该调用实例o的load方法。
修正后的代码
Button = {} Button.__index = Button -- 提前设置元表的__index指向自身,无需在构造函数重复设置 function Button:renderText() print(self.text) end function Button:load() if self.text ~= nil then self:renderText() -- 改用冒号调用,自动传入当前实例作为self end end function Button:new(x, y, text) -- 补回原代码中的y参数,按需保留 local o = {} setmetatable(o, self) -- 将属性赋值给新创建的实例o,而非Button类本身 o.x = x o.y = y o.text = text o:load() -- 调用新实例的load方法 return o end
验证调用示例
local btn = Button:new(10, 20, "Hello Button") -- 实例创建时会直接打印"Hello Button"
内容的提问来源于stack exchange,提问作者Marci
相关产品推荐
相关产品推荐

