I needed some help with lua_resume / lua_yieldk usage with lua threads.
This is with lua-5.2.1.
I have simple tcp echo server application. It has a main lua state (L) and for each client session I associate a lua thread (T), i.e. created with lua_newthread(). And when the client session connects or sends data I pass it thru a function (say connect or data) in a lua script. This lua script has been loaded earlier during program init time.
I want each client session have its own environment - so that it can set some globals or state and not affect other client sessions.
So, far I am able to do this by setting the up value (1) of the function to be called with the client session specific environment before calling the lua function from the C code.
Now, I wanted to try to use the yield and resume functionality and implement a non-blocking API that can be called from lua script.
As a test, I tried add a "sleep(n)" function. Essentially, when the lua script calls "sleep(n)",
- the C code starts a timer for n seconds and returns with "lua_yieldk()".
- When the timer expires, I call lua_resume again
- in the continuation function, I just return 0 as I don't need to anything in this case (correct?)
- and then the script continues
This seems to work fine when there's only one session "sleeping" at time.
Now, while the first session is sleeping, a second session comes in, and the C code sets up the env corresponding to the second session and calls lua_resume to invoke the lua script function. And the script calls "sleep(n)", so the second session also goes to sleep.
But, now, when the first session wakes up, and the script continues, it's environment is now that of the second session. So, it gets the wrong information and that's a problem.
How can I ensure that that when the first session wakes up, it finds its own environment and not that of any other session that might have come (and gone) in between. (I am hoping I've described my problem clearly).
The other question I had is about the lua_resume API:
int lua_resume (lua_State *L, lua_State *from, int nargs);
In my case, I have the lua thread T (which is client session specific) and the global lua state L. For the "from" parameter, the manual says this : The parameter
from represents the coroutine that is resuming
L. If there is no such coroutine, this parameter can be
NULL . It was not clear to me whether I should be setting "from" to NULL or "L", my global lua state . I am thinking it should be NULL, in my case as, for the first call to lua_resume, there's no coroutine that's resuming it or when I call lua_resume after the timer expiry, it is the same. There's no co-routine which is actually resuming it.
-- It's not that I'm so smart, it's just that I stay with problems longer - Albert Einstein.