lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Mar 26, 2008, at 5:58 AM, Graham Wakefield wrote:


On Mar 25, 2008, at 6:23 PM, Eugen-Andrei Gavriloaie wrote:

2. I need a method of keeping some kind of "state" or "session" on each connection. This "session" is opaque from c++ point of view. Must be opaque because the user of the server must write his own Lua scripts and keep his own state particular for each application. For example, I have app1 and app2. App1 must keep an username and a passowrd in his "session" and app2 must keep a counter of some kind.

How about a coroutine per session: lua_newthread() & lua_resume()? Session storage would come for free in the form of any local variables.
One little issue... each lua_newthread() pushes a lua_State on the stack of the parent context. Right? And they need to stay there, otherwise will be garbage collected. On the other hand, stack space is precious and limited. And I will surly have hundreds of connections... So, I need to pop the lua_State from the stack and keep it somewhere and make Lua interpreter understand that is not allowed to garbage collect it.

Am I right? Any idea how can I keep this lua_State in the parent interpreter?

Thank you very much for your help!

Well, I wouldn't worry too much a few hundred stack slots... but...
Does the stack size increase by itself? If I do for example (I know this is a stupid example, but it works as an example):
L1=lua_newthread(L);
L2=lua_newthread(L);
...
L200=lua_newthread(L);
Will the stack be resized automatically? Or should I make something special?




Typically, to avoid collection, new threads can be placed into the registry, or a designated table in the registry.

E.g. to create:

L2 = lua_newthread(L);
lua_pushvalue(L, true);
Stack status:  elem1 elem2 ..... elemN thread true [top of the stack]

lua_settable(L, LUA_REGISTRYINDEX); // pops the thread from the parent state
This is translated into:
t[thread]=true. Is this correct?


.. now do things with L2, e.g. push a function and lua_resume() it.

When the session expires, you can let garbage collection occur again like this:

lua_pushthread(L2);
lua_pushnil(L2);
Stack status:  elem1 elem2 ..... elemN thread nil [top of the stack]

lua_settable(L2, LUA_REGISTRYINDEX);
t[thread]=nil. Is this correct? If it is that means that putting nil value into a table removes that pair? Or the pair [thread,nil] persists there... Because if it persists, I have a problem...


Also note that garbage collection and LUA_REGISTRYINDEX is shared between the parent and all child states.

If I understood all this correctly, it will be a huge step forward for me...

Thank you so much!