Skip to content

Instantly share code, notes, and snippets.

@marcogravbrot
Created April 21, 2017 22:15
Show Gist options
  • Save marcogravbrot/9994f450b5aca67e492ef026f061132a to your computer and use it in GitHub Desktop.
Save marcogravbrot/9994f450b5aca67e492ef026f061132a to your computer and use it in GitHub Desktop.
function runCode(code)
local environment = {
--
-- global functions
--
print = print,
tostring = tostring,
tonumber = tonumber,
type = type,
pairs = pairs,
error = error,
ipairs = ipairs,
next = next,
unpack = unpack,
_VERSION = _VERSION,
select = select,
--
-- global libraries/tables
--
math = math,
string = string,
table = table,
--
-- global variables
--
ping = "pong!",
--message = message,
}
local func, err = loadstring("return ".. code, "eval", "t", environment)
if err and (not func) then -- return <code> doesn't work, let's try without return
func, err = loadstring(code, "eval", "t", environment)
if err and (not func) then
return false, err
end
local ret = {func()}
if ret and #ret > 0 then
return true, ret
end
return true
end
local ret = {func()}
if ret and #ret > 0 then
return true, ret
end
return true
end
--
-- Example code, showcases a use case with multiple returns
--
local ok, ret = runCode("return 1, 2, 3")
if ok and ret then
print(unpack(ret))
end
@thegalaxydev
Copy link

kek

@orjahren
Copy link

orjahren commented Jan 4, 2020

+1 nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment