register.lua 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. local builtin_shared = ...
  2. do
  3. local default = {mod = "??", name = "??"}
  4. core.callback_origins = setmetatable({}, {
  5. __index = function()
  6. return default
  7. end
  8. })
  9. end
  10. function core.run_callbacks(callbacks, mode, ...)
  11. assert(type(callbacks) == "table")
  12. local cb_len = #callbacks
  13. if cb_len == 0 then
  14. if mode == 2 or mode == 3 then
  15. return true
  16. elseif mode == 4 or mode == 5 then
  17. return false
  18. end
  19. end
  20. local ret = nil
  21. for i = 1, cb_len do
  22. local origin = core.callback_origins[callbacks[i]]
  23. core.set_last_run_mod(origin.mod)
  24. local cb_ret = callbacks[i](...)
  25. if mode == 0 and i == 1 then
  26. ret = cb_ret
  27. elseif mode == 1 and i == cb_len then
  28. ret = cb_ret
  29. elseif mode == 2 then
  30. if not cb_ret or i == 1 then
  31. ret = cb_ret
  32. end
  33. elseif mode == 3 then
  34. if cb_ret then
  35. return cb_ret
  36. end
  37. ret = cb_ret
  38. elseif mode == 4 then
  39. if (cb_ret and not ret) or i == 1 then
  40. ret = cb_ret
  41. end
  42. elseif mode == 5 and cb_ret then
  43. return cb_ret
  44. end
  45. end
  46. return ret
  47. end
  48. function builtin_shared.make_registration()
  49. local t = {}
  50. local registerfunc = function(func)
  51. t[#t + 1] = func
  52. core.callback_origins[func] = {
  53. mod = core.get_current_modname() or "??",
  54. name = debug.getinfo(1, "n").name or "??"
  55. }
  56. end
  57. return t, registerfunc
  58. end
  59. function builtin_shared.make_registration_reverse()
  60. local t = {}
  61. local registerfunc = function(func)
  62. table.insert(t, 1, func)
  63. core.callback_origins[func] = {
  64. mod = core.get_current_modname() or "??",
  65. name = debug.getinfo(1, "n").name or "??"
  66. }
  67. end
  68. return t, registerfunc
  69. end