You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 07:10:22