ModuleManager.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. -- TODO: Implement lazy loading.
  2. local ModuleManager = {}
  3. local function IsFunction(x)
  4. return (type(x) == "function")
  5. end
  6. function ModuleManager.new(printDebug)
  7. local self = setmetatable({},{__index = ModuleManager})
  8. self.Debug = printDebug or false
  9. self.ModuleInstances = {}
  10. self.Modules = {} -- Loaded Modules.
  11. return self
  12. end
  13. function ModuleManager:AddModuleDirectory(moduleDirectory) -- not recursive.
  14. if self.Debug then
  15. print("Loading directory: ", moduleDirectory:GetFullName())
  16. end
  17. for _,moduleScript in pairs(moduleDirectory:GetChildren()) do
  18. if moduleScript:IsA("ModuleScript") then
  19. self:AddModule(moduleScript)
  20. end
  21. end
  22. end
  23. function ModuleManager:AddModule(moduleScript)
  24. assert(moduleScript:IsA("ModuleScript"), tostring(moduleScript).." is not a ModuleScript.")
  25. self.ModuleInstances[moduleScript.Name] = moduleScript
  26. end
  27. function ModuleManager:GetModule(moduleName)
  28. assert(self.Modules[moduleName], "No such module: "..moduleName)
  29. return self.Modules[moduleName]
  30. end
  31. function ModuleManager:GetModules()
  32. return self.Modules
  33. end
  34. function ModuleManager:LoadAllModules() -- Let's not be lazy now.
  35. for name,moduleScript in pairs(self.ModuleInstances) do
  36. local LoadedModule = require(moduleScript)
  37. -- Middleware?
  38. self.Modules[name] = LoadedModule
  39. end
  40. end
  41. function ModuleManager:InitAllModules()
  42. for name,module in pairs(self.Modules) do
  43. if IsFunction(module.Init) then
  44. if self.Debug then
  45. print("Initializing:",name)
  46. end
  47. module:Init(self)
  48. end
  49. end
  50. end
  51. function ModuleManager:StartAllModules()
  52. for name,module in pairs(self.Modules) do
  53. if IsFunction(module.Start) then
  54. if self.Debug then
  55. print("Starting:",name)
  56. end
  57. module:Start(self)
  58. end
  59. end
  60. end
  61. return ModuleManager