Advertisement
Snusmumriken

Lua-automato

Aug 19th, 2016
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.15 KB | None | 0 0
  1. help = [[
  2. Reference:
  3. Using is pretty easy:
  4.  Foo = require 'auto'
  5.  
  6. Creating the table with optional fields load/update/unload
  7.  local t = {a = 10, b = 20}
  8.  function t:load(x, y)
  9.   self.x, self.y = x, y
  10.  end
  11.  function t:unload()
  12.   self.x, self.y = self.a, self.b
  13.  end
  14.  
  15. Creating another table
  16.  local c = {}
  17.  function c:load()
  18.   Foo:set('t')
  19.  end
  20.  function c:unload()
  21.   print('c exit')
  22.  end
  23.  
  24.  Foo:new('t', t)
  25.  Foo:new('c', c)
  26.  Foo:set('t', 256, 128)
  27.  -- t.x, t.y = 256, 128
  28.  Foo:set('c')
  29.  --> print 'c exit'
  30.  -- t.x = t.a = 10, t.y = t.b = 20
  31. ]]
  32.  
  33. local automato = {}
  34.  
  35. local error = error
  36. local function err(v, s)
  37.     if not v then error(s, 2) end
  38. end
  39.  
  40. setmetatable(automato,
  41.     {__call =
  42.         function(self)
  43.             self.__index = self
  44.             return setmetatable({states = {current = {}}}, self)
  45.         end
  46.     }
  47. )
  48.  
  49. -- creating new state, (string )name using for set/get,
  50. -- t contains any table with any parameters, but
  51. -- fields load, update and unload must be a functions
  52. --
  53. function automato:new(name, t)
  54.     err(type(name) == 'string', 'arg #1: statename string expected, got '..type(name))
  55.     if t.load then err(type(t.load) == 'function', 'arg #2: load function expected, got '..type(t.load)) end
  56.     if t.update then err(type(t.update) == 'function', 'arg #3: update function expected, got '..type(t.update)) end
  57.     if t.unload then err(type(t.unload) == 'function', 'arg #4: unload function expected, got '..type(t.unload)) end
  58.     self.states[name] = t
  59. end
  60.  
  61. -- set state with any args
  62. function automato:set(name, ...)
  63.     err(self.states[name], 'State "'..name..'" does not exists', 3)
  64.     if self.states.current.unload then self.states.current.unload(self.states.current) end
  65.     self.states.current = self.states[name]
  66.     if self.states.current.load then self.states.current.load(self.states.current, ...) end
  67. end
  68.  
  69. -- return state with name or current [if nil]
  70. function automato:get(name)
  71.     return self.states.current[name] and self.states.current.name or self.states.current
  72. end
  73.  
  74. -- update state with any args
  75. function automato:update(...)
  76.     if self.states.current.update then self.states.current.update(self.states.current, ...) end
  77. end
  78.  
  79. return automato, help
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement