Page 1 of 1

lua and lua 'class' - passing functions as variables

Posted: Wed Dec 23, 2020 9:11 pm
by tiss
I'm trying to make a level controller to be used as a framework for games I make; to help with transitions between levels and such.

I want to be able to make a lua module for each of my levels and have a controller that draws/updates/loads... the current level. Everything is working in the controller but my level is only being drawn once (I put a print in the draw method and it's only called once). Here is my level "class" and my main menu "level". I think my problem is something with how I am passing my functions into the level module.

level.lua

Code: Select all

Level = {}
Level.__index = Level

function Level:new(config)

	local l = {}
	setmetatable(l,Level)

	l.name = config.name
	l.load = config.load
	l.draw = config.draw
	l.update = config.update

	return l

end

function Level:load()

	-- Defined in :new


end

function Level:draw()

	-- Defined in :new

end

function Level:update(dt)

	-- Defined in :new

end

return Level
mainmenu.lua

Code: Select all

Level = require('level')

MainMenu = {}
MainMenu.__index = MainMenu

function MainMenu:load()

	love.window.setTitle("Main Menu")

end

function MainMenu:update(dt)

	

end

function MainMenu:draw()

	print("Drawing") -- THIS only happens once
	love.graphics.print("Level One", 100, 100)

end

---------------- I think, below is the issue -----------
MainMenu = Level:new({
	name = "Main Menu",
	load = MainMenu:load(),
	draw = MainMenu:draw(),
	update = MainMenu:update()
})

return MainMenu
What I want is to return MainMenu with as a level object/table with the functions passed into it.

This may seem more complicated than needed but I have some ideas on where I want to go with this. ALSO, I'm just learning lua so there may be some obvious or stupid things in this code :)

Re: lua and lua 'class' - passing functions as variables

Posted: Thu Dec 24, 2020 1:34 am
by pgimeno
tiss wrote: Wed Dec 23, 2020 9:11 pm
mainmenu.lua

Code: Select all

...
---------------- I think, below is the issue -----------
MainMenu = Level:new({
	name = "Main Menu",
	load = MainMenu:load(),
	draw = MainMenu:draw(),
	update = MainMenu:update()
})
If you add parentheses after a variable, that makes a call. You are passing the result of executing the function, but you want to pass the function itself, and that's a variable. Don't add parentheses. Also, you can't use colon with a variable; use a dot instead:

Code: Select all

	load = MainMenu.load,
	draw = MainMenu.draw,
	update = MainMenu.update

Re: lua and lua 'class' - passing functions as variables

Posted: Sat Dec 26, 2020 4:40 pm
by tiss
Oh, I see. Thanks! Works as expected now.