context.lua 885 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. Context = {
  2. list = {},
  3. started = false
  4. }
  5. function Context:add(obj, ...)
  6. local c = obj(...)
  7. table.insert(self.list, c)
  8. local tmp = ctx
  9. ctx = c
  10. f.exe(ctx.load, ctx, ...)
  11. ctx = tmp
  12. return c
  13. end
  14. function Context:run(key, ...)
  15. for i = #self.list, 1, -1 do
  16. ctx = self.list[i]
  17. if key == 'update' then
  18. ctx.tick = (ctx.tick or 0) + 1
  19. end
  20. tick = ctx.tick or 0
  21. if ctx[key] then ctx[key](ctx, ...) end
  22. ctx = nil
  23. tick = nil
  24. end
  25. end
  26. function Context:remove(ctx, ...)
  27. for i = 1, #self.list do
  28. if self.list[i] == ctx then
  29. f.exe(ctx.unload, ctx, ...)
  30. table.remove(self.list, i)
  31. collectgarbage()
  32. return
  33. end
  34. end
  35. end
  36. function Context:clear()
  37. table.each(self.list, f.cur(self.remove, self))
  38. end
  39. setmetatable(Context, {
  40. __index = function(t, k)
  41. return function(...) return t:run(k, ...) end
  42. end
  43. })