Page 1 of 1

My implementation of game states library

Posted: Fri May 08, 2020 9:00 pm
by Spellweaver
Hello dear Love2d community. Some time ago I've created a small states.lua lib for personal use and used that in every single of my project afterwards. Thought I might as well publish it separately on github and share with people in case they find it useful.

Here's the github link: https://github.com/Spellsweaver/States

I would be really happy if it turns out useful for someone besides me, or if someone provides useful feedback on the code.

How to use

In main.lua
states = require("states")
in love.load() call states.setup()
From now on, states library will redirect love2d callbacks from your main.lua to state files
Each state file should be located in "states/" directory and return a table of callbacks that correspond to love2d callbacks
If you want your callbacks to be state-independant, keep them in your main.lua. This way states library will not redirect them to states.
If you want a callback to have both state-dependant and state-independant part,
keep it in main.lua and call states.(callback name) within love 2d callback
To switch states (you should probably do this immediately after initialising) use states.switch(filename,params)
Filename is a name of your state file, while params is a table that will be caught by .open callback within according state file
Through params you can transfer data to your state files conveniently

Re: My implementation of game states library

Posted: Tue Sep 15, 2020 5:13 pm
by JuanjoSalvador
Can you provide a code example?

Re: My implementation of game states library

Posted: Thu Sep 17, 2020 12:26 pm
by RNavega
The code looks interesting, thanks for sharing!

Re: My implementation of game states library

Posted: Tue Nov 10, 2020 12:48 am
by Spellweaver
JuanjoSalvador wrote: Tue Sep 15, 2020 5:13 pm Can you provide a code example?
Sure. Sorry for delayed reply.

main.lua

Code: Select all

local states = require("states")

function love.load()
	--some intialization happens
	states.setup()
	states.switch("ingame", {scale = 1})
end
ingame.lua

Code: Select all

local scale
local ingame = {}
function ingame.open(params)
	scale = params.scale
end

function ingame.draw()
	--same as what would be in love.draw when you're in this state
end

return ingame
Simple as that.

Re: My implementation of game states library

Posted: Mon Jan 11, 2021 6:09 pm
by dusoft