Coroutine.pkg 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. $[
  2. local totalTime_ = 0
  3. local sleepedCoroutines_ = {}
  4. local waitEventCoroutines_ = {}
  5. function coroutine.start(func)
  6. if func == nil then
  7. return nil
  8. end
  9. local co = coroutine.create(func)
  10. return coroutine.resume(co)
  11. end
  12. function coroutine.sleep(time)
  13. local co = coroutine.running()
  14. if co == nil then
  15. return
  16. end
  17. sleepedCoroutines_[co] = totalTime_ + time
  18. return coroutine.yield(co)
  19. end
  20. function coroutine.update(steptime)
  21. totalTime_ = totalTime_ + steptime
  22. local coroutines = {}
  23. for co, wakeupTime in pairs(sleepedCoroutines_) do
  24. if wakeupTime < totalTime_ then
  25. table.insert(coroutines, co)
  26. end
  27. end
  28. for _, co in ipairs(coroutines) do
  29. sleepedCoroutines_[co] = nil
  30. coroutine.resume(co)
  31. end
  32. end
  33. function coroutine.waitevent(event)
  34. local co = coroutine.running()
  35. if co == nil then
  36. return
  37. end
  38. if waitEventCoroutines_[event] == nil then
  39. waitEventCoroutines_[event] = { co }
  40. else
  41. table.insert(waitEventCoroutines_[event], co)
  42. end
  43. return coroutine.yield(co)
  44. end
  45. function coroutine.sendevent(event)
  46. local coroutines = waitEventCoroutines_[event]
  47. if coroutines == nil then
  48. return
  49. end
  50. waitEventCoroutines_[event] = nil
  51. for _, co in ipairs(coroutines) do
  52. coroutine.resume(co)
  53. end
  54. end
  55. $]