Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- help = [[
- Reference:
- Using is pretty easy:
- Foo = require 'auto'
- Creating the table with optional fields load/update/unload
- local t = {a = 10, b = 20}
- function t:load(x, y)
- self.x, self.y = x, y
- end
- function t:unload()
- self.x, self.y = self.a, self.b
- end
- Creating another table
- local c = {}
- function c:load()
- Foo:set('t')
- end
- function c:unload()
- print('c exit')
- end
- Foo:new('t', t)
- Foo:new('c', c)
- Foo:set('t', 256, 128)
- -- t.x, t.y = 256, 128
- Foo:set('c')
- --> print 'c exit'
- -- t.x = t.a = 10, t.y = t.b = 20
- ]]
- local automato = {}
- local error = error
- local function err(v, s)
- if not v then error(s, 2) end
- end
- setmetatable(automato,
- {__call =
- function(self)
- self.__index = self
- return setmetatable({states = {current = {}}}, self)
- end
- }
- )
- -- creating new state, (string )name using for set/get,
- -- t contains any table with any parameters, but
- -- fields load, update and unload must be a functions
- --
- function automato:new(name, t)
- err(type(name) == 'string', 'arg #1: statename string expected, got '..type(name))
- if t.load then err(type(t.load) == 'function', 'arg #2: load function expected, got '..type(t.load)) end
- if t.update then err(type(t.update) == 'function', 'arg #3: update function expected, got '..type(t.update)) end
- if t.unload then err(type(t.unload) == 'function', 'arg #4: unload function expected, got '..type(t.unload)) end
- self.states[name] = t
- end
- -- set state with any args
- function automato:set(name, ...)
- err(self.states[name], 'State "'..name..'" does not exists', 3)
- if self.states.current.unload then self.states.current.unload(self.states.current) end
- self.states.current = self.states[name]
- if self.states.current.load then self.states.current.load(self.states.current, ...) end
- end
- -- return state with name or current [if nil]
- function automato:get(name)
- return self.states.current[name] and self.states.current.name or self.states.current
- end
- -- update state with any args
- function automato:update(...)
- if self.states.current.update then self.states.current.update(self.states.current, ...) end
- end
- return automato, help
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement