hunters2020

States API

Nov 11th, 2015
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. -- State API, Created by Detective_Smith, This API is under the Creative Commons Attribution-NonCommercial 4.0 International Public License
  2. -- Forum topic: http://www.computercraft.info/forums2/index.php?/topic/25128-states/page__pid__237930#entry237930
  3. local create, yield, resume, status = coroutine.create, coroutine.yield, coroutine.resume, coroutine.status
  4. local tStates, lstring, pc, senv, pairs, ty = 0, loadstring, pcall, setfenv, pairs, type
  5.  
  6. local function copyTable(table)
  7.     local newTable = {}
  8.     for k, v in pairs(table) do
  9.         newTable[k] = ty(v) == "table" and copyTable(v) or v
  10.     end
  11.     return newTable
  12. end
  13.  
  14. local createFunction = load and
  15. function(code, env, debugName)
  16.     return ty(code) == "string" and load(code, debugName, "t", env) or senv(code, env)
  17. end
  18. or
  19. function(code, env, debugName)
  20.     local func, err = ty(code) == "string" and lstring(code, debugName) or code
  21.     if not func then return _, err end; return senv(func, env)
  22. end
  23.  
  24. local State = {
  25.     new = function(code, env, useCoroutine, debugName, copy)
  26.         local env = copyTable and  ty(env) == "table" and ((env.type == "state" and env.env) or env) or _G; tStates = tStates + 1
  27.         env = copy == "copy" and copyTable(env) or copy == "meta" and setmetatable({}, {__index = env}) or env
  28.         local state, err = createFunction(code or function() end, env, debugName or "state"..tStates)
  29.         if not state then return _, err end; local c = useCoroutine and create(function() repeat until pc(state, yield()) end); resume(c)
  30.  
  31.         return useCoroutine and
  32.         {setCode = function(code) state, err = createFunction(code or "", env, debugName or "state"..tStates); c = create(function() repeat until pc(state, yield()) end); return err end,
  33.          resume = function(...) return resume(c, ...) end, status = function() return status(c) end, env = env, type = "cstate"}
  34.         or
  35.         {setCode = function(code) state, err = createFunction(code or "", env, debugName or "state"..tStates); return err end,
  36.          run = function(...) return pc(state, ...) end, env = env, type = "state"}
  37.     end,
  38.     version = function() return "1.2" end
  39. }
Advertisement
Add Comment
Please, Sign In to add comment