Convo_bomber34

MultiAPI

Feb 16th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.86 KB | None | 0 0
  1. function multitasker(...)
  2.    local a = {...}
  3.    local m = {t = {}}
  4.    for k, v in pairs(a) do
  5.       m.t[k] = assert(coroutine.create(v))
  6.    end
  7.    m.status = "paused"
  8.    m.start = (function(mode)
  9.       local mode = mode or "all"
  10.       if (m.status == "done") then
  11.          error("Cannot start a completed multitasker",2)
  12.       end
  13.       m.status = "running"
  14.       while (m.status == "running") do
  15.          if (#m.t == 0) then
  16.             m.status = "done"
  17.          end
  18.          for i,t in pairs(m.t) do
  19.             if (coroutine.status(t) == "dead") then
  20.                table.remove(m.t,i)
  21.                if (string.lower(mode)=="any")then
  22.                   m.status = "done"
  23.                end
  24.                i = i-1
  25.             else
  26.                coroutine.resume(t)
  27.             end
  28.          end
  29.          sleep(0)
  30.       end
  31.       if (m.status ~= "paused") then m.status = "done"
  32.       end
  33.    end)
  34.    m.pause = (function()
  35.       if (m.status == "done") then
  36.          error("Cannot pause a completed multitasker",2)
  37.       end
  38.       m.status = "paused"
  39.    end)
  40.    return m
  41. end
  42.  
  43. --while solution
  44. function wh(bool,fn)
  45.    if (bool==true or bool()) then
  46.       fn()
  47.       coroutine.yield()
  48.       wh(bool,fn)
  49.       return
  50.    else
  51.       return
  52.    end
  53. end
  54. --sleep solution/"timer" like thing-- may or may not work in cclua as millisecond time isn't used often
  55. function sl(ms)
  56.    ms = ms/1000*.94
  57.    local start = os.clock()
  58.    local function wait()
  59.       if(os.clock()-start>ms) then
  60.          return
  61.       end
  62.       coroutine.yield()
  63.       wait()
  64.    end
  65.    wait()
  66. end
  67.  
  68. --[[
  69. --# Multitasking API
  70. --# Created by Convo_bomber34
  71. --# Example:
  72. function a()
  73.    wh(true,function()
  74.       print("a",(os.date("*t").sec))
  75.       sl(1000)
  76.    end)
  77. end
  78. function b()
  79.    local i = 1
  80.    wh(function()return i<=4 end,function()
  81.       sl(250)
  82.       print("b",i)
  83.       i = i+1
  84.    end)
  85. end
  86.  
  87. m = multitasker(a,b)
  88. m.start("any")
  89. --]]--
Advertisement
Add Comment
Please, Sign In to add comment