Machine

From OpenEUO
Revision as of 17:37, 3 January 2011 by Ximan (Talk | contribs) (State Function Prototypes)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Calling Pattern

Call

local m = sl.machine(a[,b])

Args

a is a table of functions
b optional, is a table

Results

m is a machine closure

Closure Methods

Example Usage

local s = {
  initiate = function(h,...) local a = {...} print('initiating '..a[1]) return 'a' end,
  a        = function(h) print('a')       return 'b'    end,
  b        = function(h) print('b')       return 'c'    end,
  c        = function(h) print('c')       return 'exit' end,
  exit     = function(h) print('exiting') return 999    end,
  monitor  = function(s,h,n,g) if g=='exit' then h[1]=h[1]+1; if h[1]<3 then g='a' end end; return g end,
  }

local h = {0}
local m = sl.machine(s,h)
local n = m.init('live')
print(tostring(n))
--> initiating live
    a
    b
    c
    a
    b
    c
    a
    b
    c
    exiting
    999

Description

Calling machine returns a state machine closure with one defined method, machine.initiate. The first argument, a, is the table of state functions, and b is an optional table passed to each state function upon transition into its corresponding state. If b isn't provided, then b is set to a newly created empty table.

State Function Prototypes

The state table must provide function values for at least two keys: 'initiate' and 'exit'. The initiate function receives the optional argument b upon initialization (or a newly created empty table if it isn't) as well as any variadic arguments from the machine.initiate call, and should the key representing the next state to transition into.

-- initiate function
a.initiate = function(b, ...) return 'c' end

A typical state function receives b as its sole argument, and should return the key representing the next state to transition into.

-- a typical state function
a.c = function(b)  return 'c' end

The exit function receives b as its sole argument, and its return value will be echoed as the return value of machine.initiate if no errors occur during the execution of the state machine.

-- exit function
a.exit = function(b)  return r end

If the optional monitor function is provided, it receives as arguments a reference to the state function table, the b table, the last state key l, and the requested transition state key n. Monitor should return the key representing the next state to transition into, either echoing the requested key or overriding it.

-- optional monitor function
a.monitor = function(a,b,l,n)  return n end

Upon Error

If the described argument pattern isn't matched or the required state keys aren't available, an error is reported and handled according to the operant error redirection mode.

See Also