context.lua 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. lume.call(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. lume.call(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. function Context:bind(initial, ...)
  40. love.update = Context.update
  41. love.draw = Context.draw
  42. love.quit = Context.quit
  43. love.handlers = setmetatable({}, {__index = Context})
  44. if initial then
  45. Context:add(initial, ...)
  46. end
  47. end
  48. setmetatable(Context, {
  49. __index = function(t, k)
  50. return function(...) return t:run(k, ...) end
  51. end
  52. })