How to enforce the Lua runtime limit?

Running an almost trivial script in lua with dofile, 10,000 times, takes about 52 seconds on this computer, but if I run 10,000 times "lua52 script.lua", it takes 3 or 4 times more. I know there are more involved system calls and other overhead, but I'm trying to get the scripts to time out for, say, 3 seconds and print the output. My problem is scripts with infinite loops, intentional or not, like this:

while(true) do end 

Can I timeout for dofile from Lua? Is my only option to call the interpreter every time with a timeout (3)?

+2
source share
3 answers

It feels a little wrong if a newbie like me fixes LHF on Lua issues, but here it goes; passing "count" to debug.sethook is similar to passing "c" or "call", the correct mask to pass the associated function after n VM instructions "".

Thus, to limit the execution time 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) 
+4
source

No built-in tools, try using the lalarm library.

0
source

If you do not call C functions in your scripts, you can use a counter 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 before calling dofile.

A counting hook is called every n Lua VM instructions. However, there is no way to account for the time spent on C functions, so my warning is higher.

0
source

Source: https://habr.com/ru/post/1489983/


All Articles