我正在使用 Love2D 游戏引擎用 Lua 编写一个程序。我正在尝试在类中使用类,据我所知,Lua 并不直接支持类(在我看来,如果想与主要语言竞争,这是一个疏忽)。如果我只使用我的一个类,那么一切都会正常工作,但是当我开始嵌套类时,我会遇到问题。我有 3 个文件,其中包含我的代码和我收到的错误,详细信息如下。
我收到以下信息:
Error
menu.lua:8: attempt to index field 'newBox' (a nil value)
Traceback
menu.lua:8: in function 'create'
main.lua:6: in function 'load'
[C]: in function 'xpcall'
Run Code Online (Sandbox Code Playgroud)
代码在“main.lua”中
require "menu"
require "box"
function love.load()
newMenu = Menu:create()
end
function love.update(delta)
end
function love.draw()
newMenu:draw()
end
Run Code Online (Sandbox Code Playgroud)
“menu.lua”中的代码
Menu = {}
Menu.__index = Menu
function Menu:create()
local menu = {}
setmetatable(menu, Menu)
menu.newBox:create(100, 100, 100, 50)
return menu
end
function Menu:draw()
self.newBox:draw()
end
Run Code Online (Sandbox Code Playgroud)
“box.lua”中的代码
Box = {}
Box.__index = Box
function Box:create(x, y, width, height)
local box = {}
setmetatable(box, Box)
box.x = x
box.y = y
box.width = width
box.height = height
return box
end
function Box:draw()
love.graphics.rectangle("fill", self.x, self.y, self.width, self.height)
end
function Box:getX()
return self.x
end
function Box:getY()
return self.y
end
function Box:setX(x)
self.x = x
end
function Box:setY(y)
self.y = y
end
Run Code Online (Sandbox Code Playgroud)
您没有向newBox
字段分配任何内容,因此在它处于nil
.
可能替换menu.newBox:create(100, 100, 100, 50)
为menu.newBox = Box:create(100, 100, 100, 50)