Reputation: 723
I have a library in Lua that creates and parses data packets for a protocol. When I send a packet out, I'm expecting a reply back from the destination that is then parsed into a table. I'm trying to write a wrapper around this library so that I can make a function call like the following: result = SendUnicast(dest,packetData)
and have the parsed response table returned to result.
My problem is two fold: 1) The incoming message comes in asynchronously and on a different thread than the executing script and 2) the next packet I receive isn't necessarily the response for my request, I have to parse the incoming packet and match a sequence id.
The program flow currently looks something like:
[C# UI Thread]
[C# Data Thread]
[C# UI Thread]
I can't seem to find a good method for blocking the currently executing script (in the UIThread). Creating a coroutine to be called when the message is parsed and then while coroutine.status(co) ~= "dead"
seems to kill my lua interpreter.
EDIT
I'm marking BMitch's answer as accepted because it is the correct way to handle this issue. I will warn you, however, that LuaInterface does not support coroutines and I had to add support for them to the C# code myself.
Upvotes: 1
Views: 3427
Reputation: 264591
In the UI thread, run:
while ((status=lua_resume(L_coroutine, 0)) == LUA_YIELD) {
semaphore_wait(); /* whatever the appropriate C# call is */
}
"Wait for response" should look something like:
while not results[my_result] do
coroutine.yield()
end
The "incoming message" function should look like the following in Lua:
results[cur_result]=parsed_message
And finally back in C#
for the "incoming message", call the appropriate semaphore_post()
function.
Sorry if my C#
looks terrible, I'm a C
programmer on Linux, so I tried to keep that side generic.
Upvotes: 2