lua-users home
lua-l archive

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

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...

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);
lua_settable(L, LUA_REGISTRYINDEX); // pops the thread from the parent state

.. 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_settable(L2, LUA_REGISTRYINDEX);

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