Guest User

emulator.lua v0.3

a guest
Jun 24th, 2012
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.81 KB | None | 0 0
  1. --[[
  2. kazagistars emulator
  3. Do whatever you want with it, no rights reserved, as per WTFPL
  4. (http://sam.zoy.org/wtfpl/COPYING)
  5.  
  6. Sometimes you just want to run something as if you didn't have a reactor
  7. churning away below doing cool things. So, you can use the emulator!
  8. Just call emulator:run(program) with a file name or function to run, and it
  9. will be run in parallel with everything else running in the reactor,
  10. including other emulated programs.
  11. --]]
  12. if not emulator then
  13. if not reactor then error 'emulator: missing dependancy "reactor"' end
  14.  
  15. emulator = {}
  16. emulator.threads = {} -- List of threads
  17. emulator.waiting = {} -- List of events they are waiting for
  18. emulator.nextid = 1
  19. emulator.count = 0
  20. emulator.run = function(e, program)
  21.     local func
  22.     if type(program) == "string" then
  23.         func = function() shell.run(program) end
  24.     elseif type(program) == "function" then
  25.         func = program
  26.     else
  27.         error("Emulator param must be a program")
  28.     end
  29.     local new = e.nextid
  30.     e.nextid = new + 1
  31.     e.count = e.count + 1
  32.     e.threads[new] = coroutine.create(func)
  33.     e.waiting[new] = "emulator.init"
  34.     reactor:register(nil, "emulator", emulator)
  35.     os.queueEvent("emulator.init")
  36. end
  37.  
  38. emulator.mt = {__call = function(e, event, name, ...)
  39.     local dead = {}
  40.     for id, thread in pairs(e.threads) do
  41.         if (not e.waiting[id]) or (e.waiting[id] == event) then
  42.             success, filter = coroutine.resume(thread, event, ...)
  43.             if not success then
  44.                 print("Emulated thread error: "..filter)
  45.             end
  46.             if coroutine.status(thread) == "dead" then
  47.                 dead[#dead+1] = id
  48.             end
  49.             e.waiting[id] = filter
  50.         end
  51.     end
  52.     for _,id in ipairs(dead) do
  53.         e.threads[id] = nil
  54.         e.waiting[id] = nil
  55.         e.count = e.count - 1
  56.     end
  57.     if e.count == 0 then reactor:unregister(nil, "emulator") end
  58. end}
  59. setmetatable(emulator, emulator.mt)
  60.  
  61. end
Advertisement
Add Comment
Please, Sign In to add comment