# HG changeset patch # User Matthew Wild # Date 1327260950 0 # Node ID d0a89c1c43fd0321ac778877605afcd4133aaa4b # Parent d8d257c13562365278b5c2c2a8c28f019ccb4c56 moduleapi: Add module:depends(), a way to safely depend upon another module at runtime diff -r d8d257c13562 -r d0a89c1c43fd core/moduleapi.lua --- a/core/moduleapi.lua Sun Jan 22 19:27:06 2012 +0000 +++ b/core/moduleapi.lua Sun Jan 22 19:35:50 2012 +0000 @@ -100,6 +100,35 @@ return f(); end +function api:depends(name) + if not self.dependencies then + self.dependencies = {}; + self:hook("module-reloaded", function (event) + if self.dependencies[event.module] then + self:log("info", "Auto-reloading due to reload of %s:%s", event.host, event.module); + modulemanager.reload(self.host, self.name); + return; + end + end); + self:hook("module-unloaded", function (event) + if self.dependencies[event.module] then + self:log("info", "Auto-unloading due to unload of %s:%s", event.host, event.module); + modulemanager.unload(self.host, self.name); + end + end); + end + local mod = modulemanager.get_module(self.host, name) or modulemanager.get_module("*", name); + if not mod then + local err; + mod, err = modulemanager.load(self.host, name); + if not mod then + return error(("Unable to load required module, mod_%s: %s"):format(name, ((err or "unknown error"):gsub("%-", " ")) )); + end + end + self.dependencies[name] = true; + return mod; +end + function api:get_option(name, default_value) local value = config.get(self.host, self.name, name); if value == nil then