Skip to content

Instantly share code, notes, and snippets.

@Mons
Created November 17, 2020 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mons/f26fb7857e9919ef20e8a6ae1e8f34e0 to your computer and use it in GitHub Desktop.
Save Mons/f26fb7857e9919ef20e8a6ae1e8f34e0 to your computer and use it in GitHub Desktop.
for _,expr in pairs({
"1",
"N",
"N/2+1",
"N/2+2",
"math.random()"
}) do
local fun,err = loadstring("return "..expr)
if not fun then error("Bad expression '"..expr.."'") end
local count = math.floor(math.random(7))
setfenv(fun, { N = count, math = math })
local ok, res = pcall(fun)
if not ok then error("Failed to execute expression '"..expr.."': "..res) end
res = math.floor(res)
print(("For N=%s and expr='%s' got result %s"):format(count, expr, res))
end
@Mons
Copy link
Author

Mons commented Nov 17, 2020

For N=6 and expr='1' got result 1
For N=5 and expr='N' got result 5
For N=5 and expr='N/2+1' got result 3
For N=6 and expr='N/2+2' got result 5
For N=1 and expr='math.random()' got result 0

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