Allow shorter module name specification in wesnoth.require

Basically, you can now omit the "lua/" prefix and the ".lua" suffix.
If necessary, they will automatically be applied for you.
This commit is contained in:
Celtic Minstrel 2017-05-03 01:43:18 -04:00
parent 072ddc4dc1
commit 6b74f91b2f

View file

@ -1,14 +1,35 @@
local empty_pkg = {}
local function resolve_package(pkg_name)
if wesnoth.have_file(pkg_name) then return pkg_name end
if pkg_name:sub(-4) ~= ".lua" then
if wesnoth.have_file(pkg_name .. ".lua") then
return pkg_name .. ".lua"
end
if pkg_name:sub(1, 4) ~= "lua/" then
if wesnoth.have_file("lua/" .. pkg_name .. ".lua") then
return "lua/" .. pkg_name .. ".lua"
end
end
end
if pkg_name:sub(1, 4) ~= "lua/" then
if wesnoth.have_file("lua/" .. pkg_name) then
return "lua/" .. pkg_name
end
end
return nil
end
function wesnoth.require(pkg_name)
-- First, check if the package is already loaded
if wesnoth.package[pkg_name] then
return wesnoth.package[pkg_name]
local loaded_name = resolve_package(pkg_name)
if loaded_name and wesnoth.package[loaded_name] then
return wesnoth.package[loaded_name]
end
-- Next, load the package with dofile
local pkg = wesnoth.dofile(pkg_name)
wesnoth.package[pkg_name] = pkg or empty_pkg
local pkg = wesnoth.dofile(loaded_name)
wesnoth.package[loaded_name] = pkg or empty_pkg
return pkg
end