How states work in stateful.lua
masterThe stateful module extends middleclass classes with state management capabilities.
Core Concepts:
- State Creation: Classes can define "states" using
Class:addState('StateName'). - Method Overriding: A state can override existing instance methods to change behavior.
- Method Addition: A state can add entirely new methods to an instance.
- Inheritance: States are inherited by subclasses of the original class.
- Stackable States: States are managed in a stack. The state at the top of the stack has the highest priority and its methods will be used.
- Lifecycle Callbacks: The library automatically invokes callback functions when a state is entered, exited, pushed, or popped.
- State Navigation: Use
instance:gotoState('StateName')to move to a specific state, orinstance:gotoState(nil)to clear the current state stack.
local class = require 'middleclass'
local Stateful = require 'stateful'
local Enemy = class('Enemy')
Enemy:include(Stateful)
function Enemy:initialize(health)
self.health = health
end
function Enemy:speak()
return 'My health is' .. tostring(self.health)
end
-- Create a state named 'Immortal'
local Immortal = Enemy:addState('Immortal')
-- Override an existing method
function Immortal:speak()
return 'I am UNBREAKABLE!!'
end
-- Add a new method
function Immortal:die()
return 'I can not die now!'
end
local peter = Enemy:new(10)
print(peter:speak()) -- Output: My health is 10
peter:gotoState('Immortal')
print(peter:speak()) -- Output: I am UNBREAKABLE!!
print(peter:die()) -- Output: I can not die now!
peter:gotoState(nil)
print(peter:speak()) -- Output: My health is 10