Lets say I am running a script and the game client waits for the script to be finished before it updates. Can Lua do somthing of a 'timeout'? Like, can i set a priority on the update so it leaves the script to do the update and then after words could it go back to where it was in the script?
You can also set a count hook with a suitable count for timeout and abort execution of the script in the hook.
Lua uses collaborative multithreading, so the script must know how long it has taken before it passes control back to the caller. Its not hard to figure out how long it has run using os.time and getting the difference. In some cases this might be more difficult, but if the script is a loop it shouldn't be hard. Once you've figured out that you've run for too long, do a coroutine.yield() and when you want to resume the script, simply call lua_resume from your update loop.
You can run your whole lua_State and lua script in another thread. When the Lua script accesses functions you implemented which need to modify things in the main thread, use mutexes and other things to make that access thread-safe.
This way, you can easily have your Lua script hang or do whatever while your main thread can continue to operate normally, however, it also requires you to make all your implemented functions accessing anything the main thread probably takes care of normally (like graphics) to be threading-aware.
Related
I have written a code that runs multiple tasks one after the other in Lua. There is simply a loop that calls each function and then use the output for the next one and so on.
Usually there is no issue, but it happens that there is some error. In these situations the code would just stop working.
What I want is to monitor my code. In case there is an error at some point, I can call plan B and avoid that the program interrupts.
I've read about Lua coroutines, and it appears to be what i am looking for. If there is an error, the coroutine returns the error.
My question is whether I can stop coroutine that last too long. Lua offers asynchronous coroutines, so I thought that I cannot execute a function and simultaneously compute how long it has been busy doing the task. Am I getting this right, or is there a way to basically stop coroutines from the outside with some condition ?
Thank you
This is not possible using Lua coroutines. Lua coroutines are cooperative; they do not (inherently) support preemption, which is what you're looking for. For a coroutine to return execution to the caller of coroutine.resume, it has to "cooperate" by calling coroutine.yield or error.
As has been pointed out in the comments, it is possible to set a line hook - or even an "instruction hook" - to implement preemption of Lua-only code, by interrupting the code on every new line / every couple instructions executed and checking whether a timeout is met.
This stops working as soon as you call a (blocking) C function, including Lua standard library functions; it only works well for "pure Lua" code which only does constant-time API calls, since the API call is just a single line of code / instruction for Lua; Lua has no view "into" the function.
To solve this issue, you'll need actual multithreading e.g. using lualanes, multiprocessing (e.g. using luaposix's fork, or a nonblocking API and polling.
How to wait all coroutine finished in lua just like waitgroup in go? Waitgroup in go is completed with Semaphobe. But how to complete it in lua? Or any better scheme?
Lua is not a threaded scripting language. It has no concept of multiple things being able to happen at once (you can have multiple independent Lua states executing on distinct threads, but they're different Lua states. If you want them to be able to talk to each other, then you have to provide the means to do so manually).
As such, a Lua coroutine is simply a function which can choose to suspend its execution, returning some number of values to the function which invoked the coroutine. The user can then resume the coroutine, allowing it to further perform some task. This is cooperative multitasking; a task suspends execution only when it chooses to. This is in contrast to pre-emptive multitasking, where a task can just stop executing or execute in parallel with something else.
Given this, the idea of "waiting" for a coroutine or group of coroutines simply doesn't make sense. You resume a coroutine when you want it to execute further; it's not a passive action.
You could certainly create a list of coroutines and resume each one in turn repeatedly until all of them have terminated. But there's no Lua standard library function to do that, because it's generally not useful for the uses coroutines perform.
I have tried different wait/sleep commands which completely stops the code. In my code I have changed events, so if something was changed there is a wait/sleep command, but it will wait for that event to completely finish even if another event is called. How would I have it so there would still be a delay, but have it so the events called during the wait period will run, and not wait for the previous event.
There are two approaches:
1) "Fake" parallelism based on event loop:
Project "luvit" realizes this approach, trying to do for Lua those things that node.js doing for JavaScript. In my humble opinion, for such approach just use node.js, luvit is weird and is not very reliable.
2) Multi threading:
It is better for perfomance of application, but it is more complex way, it will take time to figure out how to work with it.
For this approach use Lua Lanes.
Also, if you need it inside OpenResty, it has tools for this.
If you need it in small script, though I love Lua with all my heart, you should consider switching to node.js
I am trying to understand how I shall port my Java chess engine to dart.
So I have understood that I should use Isolates and/or Futures to run my engine in parallell with the GUI but how can I force the engine to terminate the search.
In java I just set some boolean that where shared between the engine thread and the gui thread.
You should send a message to the isolate, telling it to stop. You can simply do something like:
port.send('STOP');
To be clear, isolates and futures are two different things, and you use them differently.
Use an isolate when you want some code to truly run concurrently, in a separate "isolated memory heap". An isolate is like a mini program, running separately from your main program. You send isolates messages, and you can receive messages from isolates.
Use a future when you want to be notified when a value is available later. "Later" is defined as "a future tick in the event loop". Each isolate has its own event loop. It's important to understand that just asking a Future to run a function doesn't make the function run in parallel. It just puts the function onto the event loop to be run "later".
Answering the implied question 'how can I get a long running task in an isolate to cease running?' rather than more explicitly asked 'how can I cause an isolate to terminate, release it's resources and generally cease to be?'
Break the long running task up into smaller, shorter running units.
Execute each unit with a Future. Chain futures as appropriate.
Provide a flag that each unit should check before executing its logic. If the flag is set, bail.
Listen for a 'stop' message and set the flag if/when received.
Splitting the main processing task up into Futures allows processing of the stop message to get onto the event queue ahead of units of processing of the main task.
There is now iso.Isolate.kill()
WARNING: This method is experimental and not handled on every platform yet.
Is there a way to run Lua code from a C/C++ program at a more fine-grained level than a standard "lua_pcall" function call? Ideally I'd like to be able to loop over a list of low-level bytecode instructions (assuming it has such things) and run them one by one, so that I could write my own scheduler which had more control of things than just running a complete Lua function from start to finish.
The reason I want to do this is because I wish to implement C functions which Lua code can call which would cause the program to wait until a certain (potentially long-winded) action had completed before continuing execution. There would be a high proportion of such function calls in a typical Lua script, so the idea of rewriting it to use callbacks once the action has completed isn't really practical.
Perhaps side-stepping the question, but you could use Lua coroutines rather than custom C stuff to wait until some event occurs.
For example, one coroutine could call a waitForEvent() function. In there, you can switch to another coro until that event occurs, then resume the first one. Take a look at the lua coro docs for more about that.
Jder's suggestion to use coroutines will work very well if you can write those long waiting C routines using Lua's cooperative threading (explicit yield) feature. You'll still use lua_pcall() to enter Lua, but the entry point will be your coroutine manager function.
This only works though if the C routines don't do anything while they wait. If they are long running because they calculate something for example, then you need to run multiple OS threads. Lua is threadsafe -- just create multiple threads and run lua_open() in each thread.
From http://www.lua.org/pil/24.1.html
The Lua library defines no global
variables at all. It keeps all its
state in the dynamic structure
lua_State and a pointer to this
structure is passed as an argument to
all functions inside Lua. This
implementation makes Lua reentrant and
ready to be used in multithreaded
code.
You can also combine the two approaches. If you have a wrapper Lua function to start an OS thread, you can yield after you start the thread. The coroutine manager will keep track of threads and continue a coroutine when the thread it started has finished. This lets you use a single Lua interpreter with multiple worker threads running pure C code.
If you go the OS threading way, please have a look at Lua Lanes. I would see it the perfect solution to what you're trying to achieve (= throw one addon module to the mix and you'll be making clear, understandable and simple code with multithreading seamlessly built in).
Please tell us how your issue got solved. :)
Does the debugging interface help?