How to stop runaway scripts

Posted by Nick Gammon on Tue 09 May 2006 03:24 AM — 4 posts, 24,712 views.

Australia Forum Administrator #0
Sometimes when I am writing scripts I inadvertently send them into a loop, which is annoying because you have to force-quit MUSHclient to recover, possibly losing a heap of changes you have been making to worlds or other documents.

This simple timer shown below should fix this problem. It uses the Lua debug "sethook" facility to make a maximum instruction count (in this example 100,000 instructions). If this is reached an error is raised, breaking the loop and returning control to you.

It is done on a timer (I chose 5 seconds) because eventually normal scripting will consume that many instructions. The net effect should be to allow 100,000 instructions every 5 seconds (which should be plenty), but to raise an error if you do more - which is what a loop will tend to do.

An example of a loop which you could use to test it is:


repeat until false


Just copy this and paste into the timers window. This script is written in Lua, I'm not sure whether other languages support something similar.


<timers>
  <timer enabled="y" 
         second="5.00"    
         send_to="12"
>
  <send>

runaway_instruction_limit = 100000

function hook ()
  debug.sethook (hook, "", runaway_instruction_limit)
  error ("Runaway instruction limit reached")
end -- hook

debug.sethook (hook, "", runaway_instruction_limit)

</send>

  </timer>
</timers>


Template:pasting
For advice on how to copy the above, and paste it into MUSHclient, please see Pasting XML.
Amended on Thu 13 May 2021 07:46 PM by Nick Gammon
#1
Cannot use parentheses when calling a Sub
Line in error:
debug.sethook (hook, "", runaway_instruction_limit)



Any idea?
USA #2
That is an error message related to VB scripting, you will
need to set your world file to use LUA in order to use
this fix that Nick posted, which is something you ought
to do with your other scripts as well, as it is quickly
becoming the strongest language that MC supports.

Laterzzz,
Onoitsu2
Amended on Thu 18 Jan 2007 07:11 AM by Onoitsu2
USA #3
You are using Lua, right, not VBScript?


Edit:
D'oh, Onoitsu2 got there while I was writing mine up. :)
Anyhow, yes, what he said.