Reimplement wesnoth.require function in Lua

This commit is contained in:
Celtic Minstrel 2017-05-03 01:42:01 -04:00
parent 37c0ccafa3
commit 072ddc4dc1
2 changed files with 24 additions and 0 deletions

14
data/lua/package.lua Normal file
View file

@ -0,0 +1,14 @@
local empty_pkg = {}
function wesnoth.require(pkg_name)
-- First, check if the package is already loaded
if wesnoth.package[pkg_name] then
return wesnoth.package[pkg_name]
end
-- Next, load the package with dofile
local pkg = wesnoth.dofile(pkg_name)
wesnoth.package[pkg_name] = pkg or empty_pkg
return pkg
end

View file

@ -395,9 +395,19 @@ lua_kernel_base::lua_kernel_base()
lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
lua_setglobal(L, "print");
cmd_log_ << "Initializing package repository...\n";
static const char* pkg_name = "lua/package.lua";
lua_settop(L, 0);
lua_pushstring(L, pkg_name);
int res = intf_dofile(L);
if(res != 1) {
cmd_log_ << "Error: Failed to initialize package repository. Falling back to less flexible C++ implementation.\n";
}
// Create the package table.
lua_getglobal(L, "wesnoth");
lua_newtable(L);
lua_pushvalue(L, -3);
lua_setfield(L, -2, pkg_name);
lua_setfield(L, -2, "package");
lua_pop(L, 1);