context.lua 1.1 KB

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