stateful.lua

repository·master·Indexed 41 days ago

https://github.com/kikito/stateful.lua

A Lua module that extends the middleclass OOP library to allow classes to manage a stack of states. It enables dynamic method overriding and addition, state inheritance, and lifecycle callbacks for state transitions.

Tokens
829
Snippets
3
Records
3
Agent score
2%

What's inside stateful.lua

  1. How states work in stateful.lua

    master

    The 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, or instance: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
  2. Install stateful.lua

    master

    To use stateful.lua, you must first have middleclass installed.

    1. Copy the stateful.lua file to your project directory (e.g., a lib/ folder).
    2. Ensure your Lua package.path is configured so the directory containing stateful.lua is searchable.
    3. Require both middleclass and stateful in your Lua files.
    local class = require 'middleclass'
    local Stateful = require 'stateful'