4

I'm new to nginx lua, and got a setup from previous developer. Trying to go through the docs to understand the scope but I'm pretty unsure.

It's like this right now

init_by_lua_block {
    my_module = require 'my_module'
    my_module.load_data()
}


location / {
    content_by_lua_block {
        my_module.use_data()
    }
}

And in my_module

local _M = {}
local content = {}

function _M.use_data()
    -- access content variable
end

function _M.load_data()
    -- code to load json data into content variable
end

return _M

So my understand is, content is a local variable, so its lifetime is within each request. However, it's being initialized in init_by_lua_block, and is being used by other local functions, which makes me confused. Is this a good practice? And what's the actual lifetime of this content variable?

Thanks a lot for reading.

Luan Nguyen
  • 134
  • 1
  • 7

2 Answers2

5

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.lua
local _M = {}

local data = {
    dog = 3,
    cat = 4,
    pig = 5,
}

function _M.get_age(name)
    return data[name]
end

return _M

and then accessing it from nginx.conf:

location /lua {
    content_by_lua_block {
        local mydata = require "mydata"
        ngx.say(mydata.get_age("dog"))
    }
}
Luan Nguyen
  • 134
  • 1
  • 7
  • Sweet! Where should I put mydata.lua what should i do for nginx to be able to see the mydata.lua module? – ntg Jan 14 '21 at 13:37
0

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

Larry.He
  • 604
  • 5
  • 16
  • Thanks for your answer. However, it doesn't seem to be global variable though. Just found this which answers my question directly https://github.com/openresty/lua-nginx-module#data-sharing-within-an-nginx-worker – Luan Nguyen Mar 16 '18 at 10:13