Sinelabore Homepage

How to Generate Lua Code from State Diagrams#

Lua is a powerful, efficient, lightweight, embeddable scripting language (lua.org). To generate Lua code call the code generator with the command line flag -l lua.

The generator creates one Lua module that implements the complete state machine. Take this simple state machine as an example:

Example state machine used to generate Lua code

For a simple state machine with 4 states and 2 events, the generated module looks like this:

function testcase:new()
        local new_inst = {}
        setmetatable( new_inst, testcase)

        -- machine states
        new_inst.states = {
                S1="S1",
                S11="S11",
                S12="S12",
                S3="S3",
                __UNKNOWN_STATE__="__UNKNOWN_STATE__"
        }

        -- machine events
        new_inst.events = {
                evB="evB",
                evA="evA",
                TESTCASE_NO_MSG="TESTCASE_NO_MSG"
        }

        -- Set state vars to default states
        new_inst.stateVar = new_inst.states.S1
        new_inst.stateVarS1 = new_inst.states.S11 -- set init state of S1 

        new_inst.init=false
        return new_inst
end

function testcase:processEvent(Event)
...
return evConsumed;
end

return testcase

The state machine can be used as follows:

testcase = require "testcase"

local testcase1 = testcase:new()
Event = {event = testcase1.events.TESTCASE_NO_MSG, condition=false};
testcase1:processEvent(Event)

Event.event=testcase1.events.evA;
testcase1:processEvent(Event)

The following state machine features are supported:

  • States and sub-states
  • Deep and flat hierarchy
  • Entry, exit, and action code of states
  • Regions (implemented as sub-functions called from the main state machine handler)
  • Choice pseudo-states

The complete example is available in the examples/microwave_handbook_lua folder.

Any feedback is highly welcome!