ngx lua: scope of local variable, init in init_by_lua_block ngx lua: scope of local variable, init in init_by_lua_block nginx nginx

ngx lua: scope of local variable, init in init_by_lua_block


Found this: https://github.com/openresty/lua-nginx-module#data-sharing-within-an-nginx-worker

To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua require builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.

Here is a complete small example:

-- mydata.lualocal _M = {}local data = {    dog = 3,    cat = 4,    pig = 5,}function _M.get_age(name)    return data[name]endreturn _M

and then accessing it from nginx.conf:

location /lua {    content_by_lua_block {        local mydata = require "mydata"        ngx.say(mydata.get_age("dog"))    }}


init_by_lua[_block] runs at nginx-loading-config phase, before forking worker process.

so the content variable is global, it's all the same in every request.

https://github.com/openresty/lua-nginx-module/#init_by_lua