Finite State Machines in Defold

As far as I know, Defold doesn’t have a built-in option for FSMs, and you would have to import a lua module like this one to get one working.

The problem is, I want to use some kind of manager object to manage game state for a turn based game, and allow other objects to get and set information on that object. My first thought was to use go.property() to set a property that held the state machine, but the modules I found create FSMs by returning a lua table, which cannot be passed into go.property().

Is there another way to do this? Or should I be using a different method for game state entirely?

1 Like

I can recommend you Oyster available here in Assets portal :wink: I’m using it in my project and every object that want to know anything about a game can require modules from Oyster and set/get state or any other data.

3 Likes

Also, I’d like to mention the simple yet powerful way of storing your global data in a global Lua table.

What do you mean by this exactly? From what I understand, you can only access properties from other scripts using go.property() and go.get(). The former doesn’t allow you to pass in a Lua table.

If the state machine is some global entity it could be created as a Lua module that you require in scripts that need to access it.

-- my_module.lua
local M = {
    some_data = 1
}

...

M.change_data = function(self, new_data)
    self.some_data = new_data
end

...

return M
--- my_script.script
local my_module = require("my_module")

function init(self)
    print(my_module.some_data) -- 1
    my_module:change_data(2)
    print(my_module.some_data) -- 2
end

You could probably create some kind of state machine module from this that can be updated and queried from different scripts.

4 Likes

That helped a ton sven, thanks. I originally thought that a module shared a different set of data to each script that required it.

1 Like

Great! (FWIW it’s possible to implement modules in that way as well, but in your case a single shared state makes more sense of course.)

Each script file can define local variables that are local to the script. Each script component sharing the same script file will share the local variable.

Global variables are shared between any script that are part of the same lua context. If you set the “Shared State” setting in “game.project” all scripts (gui, render and game object component scripts) will share the same context and thus share the same globals.

5 Likes