Untitled
unknown
lua
2 years ago
1.1 kB
23
Indexable
local function get_env()
local env = setmetatable({}, { __index = getfenv() })
local i = 1
while true do
local k, v = debug.getlocal(2, i)
if not k then
break
end
env[k] = v
i = i + 1
end
return env
end
local function pack(...)
return { n = select("#", ...), ... }
end
local function unpack(args, i)
i = i or 1
if i > args.n then return end
return args[i], unpack(args, i + 1)
end
local function foo(a, b, to_eval)
local some_local = 4
-- your function script ends here
local env = get_env()
local success, chunk_or_error = pcall(loadstring, to_eval)
if not success then
print("compilation_error: ", chunk_or_error)
return
end
local packed = pack(pcall(setfenv(chunk_or_error, env)))
local success = packed[1]
if not success then
local runtime_error = packed[2]
print("runtime_error: ", runtime_error)
return
end
return unpack(packed, 2)
end
local to_eval = [[
a = a + 1
print(a + b + some_local)
return 2, 4
]]
print(foo(2, 3, to_eval))
Editor is loading...
Leave a Comment