Finite State Machine (FSM) in Defold?

Hi everyone,

I’m trying to get myself to build an FSM using the message passing structure.

I started doing something like:

go.property("state", hash("state1"))

function on_message(self, message_id, message, sender)
    if message_id == hash("state1") then
    	if message.done then
            -- do stuff to finish the state        		
            msg.post("#", hash("state2"))
    	else
	    self.state = hash("state1")
            -- do stuff to start the state
	    action(self, {param1 = 123})
        end
    elseif message_id == hash("state2") then
       -- and so on...
    end
end

function action(self, param)
    -- Do stuff during the state
    msg.post("#", self.state, { done = true })
end

Any thoughts?

Cheers,

K

1 Like

Yeah, I guess you could create a state machine using a message passing structure, but I’ve never tried it. I would probably have created one using pure Lua or used an existing Lua implementation (https://github.com/kyleconroy/lua-state-machine)