context.lua 871 B

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