diff --git a/sandbox.lua b/sandbox.lua index 72ce806..98fde7f 100644 --- a/sandbox.lua +++ b/sandbox.lua @@ -54,7 +54,11 @@ local function cleanup() end local function run(f, options) - if type(f) == 'string' then f = loadstring(f) end + if type(f) == 'string' then f = assert(loadstring(f)) end + + options = options or {} + + local limit = options.limit or 500000 setfenv(f, BASE_ENV) @@ -65,8 +69,8 @@ local function run(f, options) local step = 1 local count = 0 local timeout = function(str) - count = count + step - if count >= 500000 then + count = count + 1 + if count >= limit then cleanup() error('Timeout') end @@ -87,4 +91,4 @@ end local sandbox = { run = run } -return setmetatable(sandbox, {__call = function(_,f) return run(f) end}) +return setmetatable(sandbox, {__call = function(_,f,o) return run(f,o) end}) diff --git a/spec/sandbox_spec.lua b/spec/sandbox_spec.lua index c5c4963..911246b 100644 --- a/spec/sandbox_spec.lua +++ b/spec/sandbox_spec.lua @@ -38,10 +38,16 @@ describe('sandbox', function() assert.equal('hellohello', string.rep('hello', 2)) end) - it('#focus throws an error with infinite loops', function() - assert.has_error(function() sandbox("while true do end") end) + + describe('when handling infinite loops', function() + it('throws an error with infinite loops', function() + assert.has_error(function() sandbox("while true do end") end) + end) + + it('#focus accepts a limit param', function() + --assert.no_has_error(function() sandbox("for i=1,10000 do end") end) + assert.has_error(function() sandbox("for i=1,10000 do end", {limit = 50}) end) + end) end) - - end)