On Sat, 26 Apr 2008 12:46:00 +0200
Manlio Perillo <manlio_perillo at libero.it> wrote:
> Igor Sysoev ha scritto:
> > On Sat, Apr 26, 2008 at 11:59:38AM +0200, Manlio Perillo wrote:
> >
> >> Igor Sysoev ha scritto:
> >>> [...]
>> You can precompile all the Lua code at Nginx configuration time:
>http://www.lua.org/manual/5.1/manual.html#lua_load>>> The lua_load function reads and parses a Lua code chunk and return
> (in the Lua stack) the compiled code (or an error code).
Sure, and you can even byte-compile code into memory buffers by using
luaU_dump (along with a custom writer) and then loading them into the VM
by using lua_load (the luac compiler works by those functions, which
are present in the Lua library, its source code is in luac.c and can be
read easily.)
> So, if I'm not wrong, you need to:
> 1) Create a Lua state at the begin of the configuration phase
> 2) Use this Lua state for precompiling all the Lua code in Nginx
> 3) Finalize this Lua State at the end of configuration phase
> 4) For each request create a new Lua state
> 5) Use this Lua state for executing the precompiled script code
> 6) Finalize the Lua state at the end of the request
>> But, again, I have never used Lua, I'm just reading the reference
> manual and the source code, so better if a Lua developer can confirm
> this.
I am using Lua in a World Domination™ project I can't talk about (and
because it's fun! :-P)
That method will work, but I think it would be a bit faster not
creating an entire VM on each request. Using lua_newthread you can fork
off a new lua_State from an existing one, which will share the same
globals but will have its own execution stack. You could do:
1. Create a lua_State before configuring (call it "main" state)
2. Load all Lua code into the "main" state.
3. Fork off a new "thread" with lua_newthread using the "main"
lua_State as starting point when a request arrives.
4. Run code into the forked "thread"
5. Let Lua garbage-collect the finished threads (or force a collection
at the end of the request, or every n-th request, or whatever).
I wrote "thread" with quotes because they are coroutines, not operating
system "full-blown threads", they are very light and are implemented in
the VM.
One advantage of using coroutines is that they can yield and pass
control asynchronously to Nginx. Coroutines can be resumed from C by
using lua_resume. Also, you can set up a fake global environment on a
coroutine by using lua_setfenv (e.g. to only allow read access to
globals).
Lua is wonderful in many ways, but what I like most is that it gives
you a small set of features which can be used to achieve nearly
everything, hehe.
Just my two cents :D
Cheers,
-Adrian
--
Vim is like Emacs without all the typing. (John "Johann" Spetz)