Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- State API, Created by Detective_Smith, This API is under the Creative Commons Attribution-NonCommercial 4.0 International Public License
- -- Forum topic: http://www.computercraft.info/forums2/index.php?/topic/25128-states/page__pid__237930#entry237930
- local create, yield, resume, status = coroutine.create, coroutine.yield, coroutine.resume, coroutine.status
- local tStates, lstring, pc, senv, pairs, ty = 0, loadstring, pcall, setfenv, pairs, type
- local function copyTable(table)
- local newTable = {}
- for k, v in pairs(table) do
- newTable[k] = ty(v) == "table" and copyTable(v) or v
- end
- return newTable
- end
- local createFunction = load and
- function(code, env, debugName)
- return ty(code) == "string" and load(code, debugName, "t", env) or senv(code, env)
- end
- or
- function(code, env, debugName)
- local func, err = ty(code) == "string" and lstring(code, debugName) or code
- if not func then return _, err end; return senv(func, env)
- end
- local State = {
- new = function(code, env, useCoroutine, debugName, copy)
- local env = copyTable and ty(env) == "table" and ((env.type == "state" and env.env) or env) or _G; tStates = tStates + 1
- env = copy == "copy" and copyTable(env) or copy == "meta" and setmetatable({}, {__index = env}) or env
- local state, err = createFunction(code or function() end, env, debugName or "state"..tStates)
- if not state then return _, err end; local c = useCoroutine and create(function() repeat until pc(state, yield()) end); resume(c)
- return useCoroutine and
- {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,
- resume = function(...) return resume(c, ...) end, status = function() return status(c) end, env = env, type = "cstate"}
- or
- {setCode = function(code) state, err = createFunction(code or "", env, debugName or "state"..tStates); return err end,
- run = function(...) return pc(state, ...) end, env = env, type = "state"}
- end,
- version = function() return "1.2" end
- }
Advertisement
Add Comment
Please, Sign In to add comment