From 3d3a8c754932b2338995bf324e9d5d68597bd9ab Mon Sep 17 00:00:00 2001 From: eskerda Date: Fri, 11 Dec 2020 17:21:33 +0100 Subject: [PATCH] chore(*) lua > 5.1 compatibility * add a setfenv implementation --- README.md | 2 -- sandbox.lua | 21 +++++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 99d2df1..11a2eb7 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,6 @@ It's possible to provide extra functions via the `options.env` parameter. Infinite loops are prevented via the `debug` library. -For now, sandbox.lua only works with Lua 5.1.x. - Usage ===== diff --git a/sandbox.lua b/sandbox.lua index 69f50e7..be65e1c 100644 --- a/sandbox.lua +++ b/sandbox.lua @@ -28,6 +28,27 @@ local sandbox = { ]] } +-- Lua 5.2, 5.3 and above +-- https://leafo.net/guides/setfenv-in-lua52-and-above.html#setfenv-implementation +local setfenv = setfenv or function(fn, env) + local i = 1 + while true do + local name = debug.getupvalue(fn, i) + if name == "_ENV" then + debug.upvaluejoin(fn, i, (function() + return env + end), 1) + break + elseif not name then + break + end + + i = i + 1 + end + + return fn +end + -- The base environment is merged with the given env option (or an empty table, if no env provided) -- local BASE_ENV = {}