Changes to environment handling, get_current_modname convenience

This commit is contained in:
Lars Mueller 2020-07-08 20:08:31 +02:00
parent 68b5c4013f
commit c7e165f170

57
mod.lua

@ -1,39 +1,58 @@
-- get modpath wrapper -- get modpath wrapper
function get_resource(modname, resource) function get_resource(modname, resource)
if not resource then
resource = modname
modname = minetest.get_current_modname()
end
return minetest.get_modpath(modname) .. "/" .. resource return minetest.get_modpath(modname) .. "/" .. resource
end end
-- get resource + dofile -- get resource + dofile
function include(modname, file) function include(modname, file)
if not file then
file = modname
modname = minetest.get_current_modname()
end
dofile(get_resource(modname, file)) dofile(get_resource(modname, file))
end end
-- loadfile with table env function include_env(file_or_string, env, is_string)
function include_namespace(classname, filename, parent_namespace) setfenv(assert((is_string and loadstring or loadfile)(file_or_string)), env)()
end
function create_namespace(namespace_name, parent_namespace)
namespace_name = namespace_name or minetest.get_current_modname()
parent_namespace = parent_namespace or _G parent_namespace = parent_namespace or _G
parent_namespace[classname] = setmetatable(parent_namespace[classname] or {}, {__index = parent_namespace, __call = parent_namespace}) local namespace = setmetatable({}, {__index = parent_namespace})
local class = assert(loadfile(filename)) parent_namespace[namespace_name] = namespace
setfenv(class, parent_namespace[classname]) -- prevent MT's warning
class() if parent_namespace == _G then
return parent_namespace[classname] rawset(parent_namespace, namespace_name, namespace)
end
return namespace
end
-- formerly extend_mod
function extend(modname, file)
if not file then
file = modname
modname = minetest.get_current_modname()
end
include_env(get_resource(modname, file .. ".lua"), _G[modname])
end end
-- runs main.lua in table env -- runs main.lua in table env
-- formerly include_mod -- formerly include_mod
function init(modname) function init(modname)
include_namespace(modname, get_resource(modname, "main.lua")) modname = modname or minetest.get_current_modname()
create_namespace(modname)
extend(modname, "main")
end end
-- formerly extend_mod
function extend(modname, filename)
include_namespace(modname, get_resource(modname, filename .. ".lua"))
end
-- formerly extend_mod_string
function extend_string(modname, string) function extend_string(modname, string)
_G[modname] = setmetatable(_G[modname] or {}, {__index = _G, __call = _G}) if not string then
local string = assert(loadstring(string)) string = modname
setfenv(string, _G[modname]) modname = minetest.get_current_modname()
string() end
return _G[modname] include_env(string, _G[modname], true)
end end