Page 1 of 1

Separate State Machine per class instance?

Posted: Wed Sep 22, 2021 12:02 am
by lowercasename
I'm a novice at Lua, so forgive me if the answe to this is very obvious! I'm using the delightful lua-state-machine (https://github.com/kyleconroy/lua-state-machine) and the hump.class (https://github.com/vrld/hump) libraries, although I tried the same code with a different class library and it did the same thing so I suspect the issue is not necessarily down to a library, but to how I'm combining them.

I create a class:

Code: Select all

Actor = Class {
  x = 0,
  y = 0,
  state = machine.create( ... )
}

actors = {}
cow = Actor()
moon = Actor()
table.insert(actors, cow)
table.insert(actors, moon)
I then change the state of one of the instances in my love.mousepressed() function:

Code: Select all

for i,actor in ipairs(actors)
  if actor.x == mouseX and actorY == mouseY then
    actor.state:jump()
  end
then
At this point, both instances switch to the state 'jumping', even though only one of them was clicked. Is this due to some sort of interaction between the state machine and the class, or is it an issue in my for loop? Can I have a separate state machine per instance?

Re: Separate State Machine per class instance?

Posted: Wed Sep 22, 2021 4:42 am
by grump
That's because you create only one state machine and put it in the class. You need to create one per instance and put it in each instance instead. The constructor is a good place to do that.

Code: Select all

Actor = Class {
  init = function(self, x, y)
    self.x, self.y = x or 0, y or 0
    self.state = machine.create(...)
  end,
}

cow = Actor(1, 2)
moon = Actor(5, 6)

Re: Separate State Machine per class instance?

Posted: Wed Sep 22, 2021 8:42 am
by lowercasename
Ah thank you so much, it seems so obvious now it isn't 1 in the morning!