Hi need some help on my lua script. I have a script here that will run a server like application (infinite loop). Problem here is it doesn't execute the second coroutine.
Could you tell me whats wrong Thank you.
function startServer()
print( "...Running server" )
--run a server like application infinite loop
os.execute( "server.exe" )
end
function continue()
print("continue")
end
co = coroutine.create( startServer() )
co1 = coroutine.create( continue() )
Lua have cooperative multithreading. Threads are not swtiched automatically, but must yield
to others. When one thread is running, every other thread is waiting for it to finish or yield. Your first thread in this example seems to run server.exe
, which, I assume, never finishes until interrupted. Thus second thread never gets its turn to run.
You also run threads wrong. In your example you're not running any threads at all. You execute function and then would try to create coroutine with its output, which naturally would fail. But since you never get back from server.exe
you didn't notice this problem yet. Remove those brackets after startServer
and continue
to fix it.
As already noted, there are several issues with the script that prevent you from getting what you want:
os.execute("...")
is blocked until the command is completed and in your case it doesn't complete (as it runs an infinite loop). Solution: you need to detach that process from yours by using something like io.popen()
instead of os.execute()
co = coroutine.create( startServer() )
doesn't create a coroutine in your case. coroutine.create
call accepts a function reference and you pass it the result of startServer
call, which is nil
. Solution: use co = coroutine.create( startServer )
(note that parenthesis are dropped, so it's not a function call anymore).yield
command is for and that's why it's called non-preemptive multithreading. Solution: you need to use a combination of resume
and yield
calls after you create
your coroutine.startServer
doesn't need to be a coroutine as you are not giving control back to it; its only purpose is to start the server.In your case, the solution may not even need coroutines as all you need to do is: (1) start the server and let it detach from your process (for example, using popen
) and (2) work with your process using whatever communication protocol it requires (pipes, sockets, etc.).
There are more complex and complete solutions (like LuaLanes) and also several good descriptions on creating simple coroutine dispatchers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With