Stoping the execution of lua script in LuaInterface

Started by
2 comments, last by Razov 11 years, 7 months ago
Hello,

lets say that i have got such code:


String script = @"
writeConsole("Starting.")
while true do
writeConsole("I am alive...")
sleep(1000)
end";
Lua lua = new Lua();
lua.DoString(script);


witch after executed in new thread keeps writing "I am alive..." evry second, like:



Starting.
I am alive...
I am alive...
I am alive...
.....


Is there any way to stop executing this loop (or any other lua script witch is in middle of execution at given point) from other thread ? And to reload execution of this script, so it will give output like this:


Starting.
I am alive...
I am alive...
I am alive...
Starting. // stop execution and start again in this place
I am alive...
I am alive...
Advertisement
I don't know which host language you're using (EDIT: ah C#, but which bindings library?), but the C API certainly gives you fine-grained control over how the Lua code is executed. So without using any additional threads, you call tell the interpreter to run a little bit of code at a time and check your restart/stopping condition in between.

From inside Lua itself, you can use coroutines.

However, if you were to explain the reasons for wanting to do this, I suspect that there might be a better approach to achieving your end goal.
You can use a state variable which can be either modified in your own lua script or in your C# engine, something like this:


MyStateVar = "stopped"
..
MyStateVar = "running"
while MyStateVar=="running" do
.. game logic ...
if ...escape key pressed... then
MyStateVar = "stopped"
end
end
..
Thats not the point.

I am using LuaInterface for C#.

I am creating an application, where user can write his own lua code and execute it (new thread). I want to have possiblity to stop (interput) the execution of this lua code from C#. Lets see an example:

Lets say there is such application:

gJQP6.png

When You change "Enabled" CheckBox Checked to [color=#008000]true, lua executes onEnabled function (this part is already done.), witch starts loop
When You change "Enabled" CheckBox Checked to [color=#b22222]false, execution of lua (there is loop running) is terminated/stoped, but lua variables stays untoutched (not cleaned)
When You press "RELOAD" button, execution of lua is stopped (if its running), then lua enverionment is cleared, and lua code from textbox is executed, so user can make changes to it and press reload.

Example output it would give:


["Enabled" Checked=true]
eC: 1 / wC: 1
eC: 1 / wC: 2
eC: 1 / wC: 3
["Enabled" Checked=false]
[time passes, nothing appears on log...]
["Enabled" Checked=true]
eC: 2 / wC: 4
eC: 2 / wC: 5
[RELOAD pressed]
eC: 1 / wC: 1
eC: 1 / wC: 2
...


The main problem i am facing right now is how i can stop execution of running lua code from c#?

This topic is closed to new replies.

Advertisement