Attempting to use a class within a class

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
metzyn
Prole
Posts: 6
Joined: Wed Mar 27, 2013 10:51 pm
Location: TN, USA

Attempting to use a class within a class

Post by metzyn »

I am trying to use a class within a class, which I understand Lua does not directly support classes. 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:

Code: Select all

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"

Code: Select all

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"

Code: Select all

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"

Code: Select all

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
metzyn
Prole
Posts: 6
Joined: Wed Mar 27, 2013 10:51 pm
Location: TN, USA

Re: Attempting to use a class within a class

Post by metzyn »

Nevermind... I see my issue.

This line...

Code: Select all

menu.newBox:create(100, 100, 100, 50)
should read as...

Code: Select all

menu.newBox = Box:create(100, 100, 100, 50)
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 4 guests