Question: I use lua interfaces to get lua support in my C# program, the worker thread will freeze if the user submits code like this

```
while true do end

```

I have a way to detect if a infinite loop is running, but I need a nice way of exiting the DoString method from the Worker thread. Any ideas?

edit: @kikito, Yes Im deteting it something like that. The problem I have is that I cant find a clean way of killing the DoString method, it looks like the Lua interfaces main class (Lua) has some static dependencies, because if I do `lua.Close();` on my instance it will abort the DoString method, but the next time I instance an lua class `new Lua();` it will crash saying something about protective memory

edit: A feature branch showing my .Close code
<https://github.com/AndersMalmgren/FreePIE/tree/detect-and-recover-infite-lua-loop>

Answer: 
Put the Lua loop inside a coroutine and at the end of every loop, just use `Yield return null` to wait for a frame (Allowing the worker thread to be executed).
I suggest handling it just like any other Lua error. In other words, threat the code above as if the user had just written

```
error("Script execution has been cancelled after stalling for too long")

```

(I'm assuming that you detect infinite loops by assuming that no script should take more than a fixed amount of time to run. Change the message appropiatedly if this is not the case)

The way you will have to handle this will depend on how you deal with Lua errors - but you will have to do it anyway, so chances are that most of the code is there already.

EDIT: It seems that Martin James' suggestion is your best option. You can use the debug.setHook() to run some lua code every 100 Lua instructions or so, and if too much time has passed on the same client code, throw the error. Details about this can be found on [this mailing list](http://groups.google.com/group/lua-alchemy-dev/browse_thread/thread/ddb0cf936690f051?pli=1), and code sample on the [lua-project repo](https://github.com/gtimworks/lua-process/blob/master/src/kernel.lua).