Problems with classes

Hi, think this is more a problem with my understanding of Lua but hoping someone can help.

I'm trying to make sure my game idea has nicely structured code but struggling with the concept of self.

I have my main.lua creating an instance of my mainmenu class, then mainmenu is creating an instance of submenu. Submenu update is failing, as self is null.

Example code (imports removed for readability) (Sorry the post formats weird, can't figure out how to format the code)

MAIN.LUA
local mainMenu = MainMenu()
function playdate.update()
mainMenu:update()
gfx.sprite.update()
playdate.timer.updateTimers()
playdate.drawFPS(2, 224)
end

mainMenu.lua

class('MainMenu').extends(playdate.graphics.sprite)

function MainMenu:init()
MainMenu.super.init(self)
local sprite1Image = gfx.image.new("images/mainMenu/sprite")
assert ( sprite1Image )

self.sprite1 = gfx.sprite.new (sprite1Image)
self.sprite1:moveTo (106,40)
self.sprite1:add()

    self.subMenu = SubMenu()

end

function MainMenu:update()
self.sprite1:moveTo (math.random(0,400), math.random(0,240))
self.subMenu.update()
end

Submenu.Lua
class('SubMenu').extends(playdate.graphics.sprite)

function SubMenu:init()
SubMenu.super.init(self)

local sprite1Image = gfx.image.new("images/mainMenu/sprite")
assert ( sprite1Image )

self.sprite1 = gfx.sprite.new (sprite1Image)
self.sprite1:moveTo (300,210)
self.sprite1:add()

end

function SubMenu:update()
if (self == nil) then
print ("SELF IS NIL")
else
self.sprite1:moveTo (math.random(0,400), math.random(0,240))
end
end

I'm no Lua expert, by any means, but as it's Sunday there might not be many folks about, so I'll hop in anyway. You might want to try:

self.submenu:update()

IIRC using the ':' invokes as a function w/'self' passed as opposed to accessing member data via its name (in this case, the address of 'self.subMenu.update').

Otherwise I'm sure someone who actually knows what they're doing can straighten things out. :slight_smile:

Tegu thank you, thank you! I need to read up more on : VS ., but that fixed me!

2 Likes