質問

I am writing a program in Lua using the Love2D game engine. I am trying to use a class within a class, which I understand Lua does not directly support classes (an oversight in my opinion if wanting to compete with major languages). If I use just one of my classes then everything works just fine, but when I start to nest classes I run into issues. I have 3 files containing my code and the error I receive all detailed below.

I receive the following:

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'

Code in "main.lua"

require "menu"
require "box"

function love.load()

    newMenu = Menu:create()

end

function love.update(delta)



end

function love.draw()

    newMenu:draw()

end

Code in "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

Code in "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
役に立ちましたか?

解決

You don't assign anything to newBox field, hence the error about trying to index it while it's nil.

Probably replace menu.newBox:create(100, 100, 100, 50) with menu.newBox = Box:create(100, 100, 100, 50)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top