3

Running an almost trivial script in lua with dofile, 10000 times, takes about 52 seconds in this machine, but if i run 10000 times "lua52 script.lua", it takes 3 or 4 times more. I'm aware that there's more system calls involved and other overhead, but what i try to achieve is running scripts with a timeout of let's say 3 seconds, and print out the output. My problem is scripts with infinite loops, intentional or not, for example:

while(true) do
end

Can i make a timeout for a dofile from within Lua? Is my only option to call the interpreter each time with timeout(3)?

AlfredoVR
  • 4,069
  • 3
  • 25
  • 33

3 Answers3

4

It feels a bit wrong for a novice like me to be correcting lhf on Lua matters, but here goes; passing "count" to debug.sethook is the same as passing "c" or "call", the correct mask to pass to fire the associated function after n VM instructions is "".

As such, to restrict the runtime of code loaded from dofile(), use something like the following:

local f = function() error("timeout") end
local x,y = xpcall(function()
  debug.sethook(f, "", 1e8)
  local ret = dofile("script.lua")
  debug.sethook()
  return ret
end, debug.traceback)
furq
  • 5,648
  • 3
  • 16
  • 21
  • `count` works fine for me. The code I gave aborts with `stdin:1: timeout!`. – lhf Jul 17 '12 at 14:42
  • 1
    That's odd; passing `"count"` works as expected in the code you posted, but it aborts instantly in the code I posted (script.lua just contains `while true do end`). Passing `""` works as expected in both cases. – furq Jul 17 '12 at 19:57
2

If you don't call out to C functions in your scripts you can use the count hook with a large count value and raise an error inside the hook:

local function f() error"timeout!" end
debug.sethook(f,"count",1e6)
while true do end

In your application, set the count hook before calling dofile.

The count hook is called every n Lua VM instructions. However, there is not way to account for the time taken in C functions, hence my caveat above.

lhf
  • 70,581
  • 9
  • 108
  • 149
0

There's no built-in facilities, try using lalarm library.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68