squish: Optionally add in a 5.2-compatible module() function (5.2's own compat function is broken) lua5.2

Fri, 05 May 2017 09:47:52 +0100

author
Matthew Wild <mwild1@gmail.com>
date
Fri, 05 May 2017 09:47:52 +0100
branch
lua5.2
changeset 95
828e814152e0
parent 94
cf209451be5f
child 96
7d6070e5a096

squish: Optionally add in a 5.2-compatible module() function (5.2's own compat function is broken)

--module-compat or --no-module-compat, default is --module-compat if running under 5.2+ (detected at runtime).

When compiled with the appropriate flags, Lua 5.2 provides a module() function for backwards compatibility with
5.1. However 5.1's version of the function changed function environments, while 5.2's version changes the global
environment, which breaks through squish's per-module sandbox functions.

squish.lua file | annotate | diff | comparison | revisions
--- a/squish.lua	Fri May 05 09:44:43 2017 +0100
+++ b/squish.lua	Fri May 05 09:47:52 2017 +0100
@@ -4,7 +4,7 @@
 pcall(require, "luarocks.require");
 
 local short_opts = { v = "verbose", vv = "very_verbose", o = "output", q = "quiet", qq = "very_quiet", g = "debug" }
-local opts = { use_http = false };
+local opts = { use_http = false, module_compat = not not _ENV };
 
 for _, opt in ipairs(arg) do
 	if opt:match("^%-") then
@@ -268,6 +268,21 @@
 		data = data:gsub("^#[^\r\n]*\r?\n", ""); -- Remove shebang if any (or we can't concat)
 		if not opts.debug then
 			f:write("package.preload['", modulename, "'] = (function (...)\n");
+			if opts.module_compat then
+				f:write [[
+					local _ENV = _ENV;
+					local function module(name, ...)
+						local t = package.loaded[name] or _ENV[name] or { _NAME = name };
+						package.loaded[name] = t;
+						for i = 1, select("#", ...) do
+							(select(i, ...))(t);
+						end
+						_ENV = t;
+						_M = t;
+						return t;
+					end
+				]];
+			end
 			f:write(data);
 			f:write(" end)\n");
 		else

mercurial