Simplify our overrides of load/loadstring

- Remove auto-prefixing of load/loadstring
 - Use Cobalt's normal load implementation, with a simple hook to
   set _ENV on the environment.
This commit is contained in:
Jonathan Coates 2021-05-04 18:30:08 +01:00
parent cf0f67265f
commit bc8e090873
2 changed files with 5 additions and 58 deletions

View File

@ -16,22 +16,7 @@ end
if _VERSION == "Lua 5.1" then
-- If we're on Lua 5.1, install parts of the Lua 5.2/5.3 API so that programs can be written against it
local type = type
local nativeload = load
local nativeloadstring = loadstring
local nativesetfenv = setfenv
-- Historically load/loadstring would handle the chunk name as if it has
-- been prefixed with "=". We emulate that behaviour here.
local function prefix(chunkname)
if type(chunkname) ~= "string" then return chunkname end
local head = chunkname:sub(1, 1)
if head == "=" or head == "@" then
return chunkname
else
return "=" .. chunkname
end
end
function load(x, name, mode, env)
expect(1, x, "function", "string")
@ -40,29 +25,11 @@ if _VERSION == "Lua 5.1" then
expect(4, env, "table", "nil")
local ok, p1, p2 = pcall(function()
if type(x) == "string" then
local result, err = nativeloadstring(x, name)
if result then
if env then
env._ENV = env
nativesetfenv(result, env)
end
return result
else
return nil, err
end
else
local result, err = nativeload(x, name)
if result then
if env then
env._ENV = env
nativesetfenv(result, env)
end
return result
else
return nil, err
end
local result, err = nativeload(x, name, mode, env)
if result and env then
env._ENV = env
end
return result, err
end)
if ok then
return p1, p2
@ -81,7 +48,7 @@ if _VERSION == "Lua 5.1" then
math.log10 = nil
table.maxn = nil
else
loadstring = function(string, chunkname) return nativeloadstring(string, prefix(chunkname)) end
loadstring = function(string, chunkname) return nativeload(string, chunkname) end
-- Inject a stub for the old bit library
_G.bit = {

View File

@ -76,26 +76,6 @@ describe("The Lua base library", function()
end)
end)
describe("loadstring", function()
it("prefixes the chunk name with '='", function()
local info = debug.getinfo(loadstring("return 1", "name"), "S")
expect(info):matches { short_src = "name", source = "=name" }
end)
it("does not prefix for unnamed chunks", function()
local info = debug.getinfo(loadstring("return 1"), "S")
expect(info):matches { short_src = '[string "return 1"]', source = "return 1" }
end)
it("does not prefix when already prefixed", function()
local info = debug.getinfo(loadstring("return 1", "@file.lua"), "S")
expect(info):matches { short_src = "file.lua", source = "@file.lua" }
info = debug.getinfo(loadstring("return 1", "=file.lua"), "S")
expect(info):matches { short_src = "file.lua", source = "=file.lua" }
end)
end)
describe("load", function()
it("validates arguments", function()
load("")