Need help adapting a lua state machine to defold engine

currently I’m trying to adapt this finite state machine code for defold-use, however I’ve ran into an issue where in order for stateMachine.lua (a lua file containing the actual source code for the library) to work, it needs local event = self.events[e], this value is given by the events list in another general scripting file where the list of events is called self.events. I don’t know how to go about fixing this because the general script already requires the statemachine.lua

any way I can send over this array without using require?

1 Like

Can you show a bit more code? I’m not quite sure what the problem is at this point.

In the general script file the states are filled out like this, creating a machine object

local fsm = machine.create({
	initial = 'Idle',
	events = {
		{ name = 'InitRun',      from = { 'Run', 'Dash', 'Attack', 'Slide' },                 to = 'Run' },
		{ name = 'InitJump',     from = { 'Run', 'Idle' },                                    to = 'Jump' },
		{ name = 'InitSlide',    from = { 'Run', 'Idle' },                                    to = 'Slide' },
		{ name = 'InitDash',     from = { 'Run', 'Idle', 'Jump', 'Fall' },                    to = 'Dash' },
		{ name = 'InitAttack',   from = { 'Run', 'Jump', 'Idle', 'Fall' },                    to = 'Attack' },
		{ name = 'InitIdle',     from = { 'Run', 'Dash', 'Attack', 'Slide' },                 to = 'Idle' },
		{ name = 'InitFall',     from = { 'Run', 'Jump', 'Attack', 'Slide', 'Jump', 'Dash' }, to = 'Fall' },
		{ name = 'InitDeath',    from = '*',                                                  to = 'Death' },
		{ name = 'InitCutscene', from = '*',                                                  to = 'Cutscene' },
	}
})

the error I get is
attempt to index local 'event' (a nil value)
which seems to be because self.events[e] is recognised as nil for some reason (e being the current state call), for an example of when this is called if fsm:can('Run') then

function machine:can(e)
	local event = self.events[e]
	local to = event and event.map[self.current] or event.map['*']
	return to ~= nil, to
end

Ok, well, self, is a variable which is passed to the different lifecycle function. You need to make sure it is accessible from where you configure the state machine. Example:

function init(self)

	local fsm = machine.create({
		initial = 'Idle',
		events = {
			{ name = 'InitRun',      from = { 'Run', 'Dash', 'Attack', 'Slide' },                 to = 'Run' },
			... and so on
		}
	})

	-- self is available here as an upvalue provided from init()
	function fsm:can(e)
		local event = self.events[e]
		local to = event and event.map[self.current] or event.map['*']
		return to ~= nil, to
	end

end