diff --git a/library/lua/dfhack.lua b/library/lua/dfhack.lua index 3cc98e882..ca9d43d1e 100644 --- a/library/lua/dfhack.lua +++ b/library/lua/dfhack.lua @@ -83,7 +83,27 @@ dfhack.exception.__index = dfhack.exception -- Module loading +local function find_required_module_arg() + -- require -> module code -> mkmodule -> find_... + if debug.getinfo(4,'f').func == require then + return debug.getlocal(4, 1) + end + -- reload -> dofile -> module code -> mkmodule -> find_... + if debug.getinfo(5,'f').func == reload then + return debug.getlocal(5, 1) + end +end + function mkmodule(module,env) + -- Verify that the module name is correct + local _, rq_modname = find_required_module_arg() + if not rq_modname then + error('The mkmodule function must be used at the start of a module') + end + if rq_modname ~= module then + error('Found module '..module..' during require '..rq_modname) + end + -- Reuse the already loaded module table local pkg = package.loaded[module] if pkg == nil then pkg = {} @@ -92,6 +112,7 @@ function mkmodule(module,env) error("Not a table in package.loaded["..module.."]") end end + -- Inject the plugin-exported functions when appropriate local plugname = string.match(module,'^plugins%.([%w%-]+)$') if plugname then dfhack.open_plugin(pkg,plugname)