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

拆分Lua Button类后遇‘attempt to index local Button(boolean)’错误求助

问题根源与解决办法

我一眼就看出问题出在哪了——你的button.lua模块没有正确导出Button类!

在Lua里,当你用require加载一个文件时,如果文件末尾没有显式返回某个值,Lua会默认返回true(仅仅表示模块加载成功)。你的button.lua只是定义了一个全局的Button表,但没有把它作为模块的返回值,所以local Button = require('button')这行代码实际上把Button变量赋值成了true——一个布尔值,自然没法调用Button:new方法,这就是你看到报错的原因。

一步解决:给button.lua添加返回语句

修改你的button.lua,在文件的最后加上一行,把Button类作为模块导出:

Button = {}

function Button:new(x, y, width, height, color, text, callback,arg1)
  local button = {
      x = x,
      y = y,
      width = width,
      height = height,
      color = color,
      text = text,
      callback = callback,
      arg1 = arg1,
      state = false,
  }
  setmetatable(button, self)
  self.__index = self
  return button
end

-- 以下draw、update方法保持不变...

-- 关键:添加这行导出Button类
return Button

更规范的写法(避免污染全局环境)

如果你不想让Button成为全局变量(推荐做法),可以把它定义成局部变量再返回:

-- 改成局部变量
local Button = {}

function Button:new(...)
  -- 方法内容不变
end

-- 其他方法不变...

return Button

额外的小优化

你的main.lua里,创建按钮的代码是放在全局作用域的,建议移到love.load函数里执行——因为此时窗口已经初始化完成,坐标计算会更准确:

buttons = {}

function love.load()
    love.window.setFullscreen(true)
    love.window.setTitle("Mon jeu")
    -- 把按钮创建移到这里
    table.insert(buttons, Button:new(200, 10, 200, 100, {0, 0, 1}, "Mon bouton", createTextbox, texts))
end

这样修改后,再运行代码应该就能正常创建按钮了!

内容的提问来源于stack exchange,提问作者Antowaan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:50:22