lua-nginx-module icon indicating copy to clipboard operation
lua-nginx-module copied to clipboard

global variables from includes

Open nvrmnd opened this issue 12 years ago • 5 comments

Hi. I'm using the following nginx config:

worker_processes 1; location = /lua { content_by_lua_file 'main.lua'; }

The content of 'main.lua' file is:

require("include")
ngx.say(variable)

File 'include.lua' is required here, it's content (one line, global variable):

variable = "Test"

When I query the location, i see that after second request global variable from included file is gone: $ curl "127.0.0.1/lua" Test $ curl "127.0.0.1/lua" nil

But everything is fine when I turn code cache off.

nginx 1.5.11 lua-nginx-module-0.9.5rc2 luajit 2.0.2

nvrmnd avatar Mar 13 '14 19:03 nvrmnd

@nvrmnd First of all, avoid using custom global Lua variables in the context of ngx_lua (and also for Lua in general) wherever possible. They are slow and might have bad side effects. Also, the global environment table in the context of content_by_lua has the same life time as the current request handler. See https://github.com/chaoslawful/lua-nginx-module#lua-variable-scope

agentzh avatar Mar 13 '14 19:03 agentzh

@nvrmnd Only use require() for proper Lua modules that return a thing. That is,

local mymod = require "mymod"
local myvalue = mymod.myfield

agentzh avatar Mar 13 '14 19:03 agentzh

Thank you very much for your quick answer! Loading includes this way works like a charm.

nvrmnd avatar Mar 13 '14 19:03 nvrmnd

Consider it resolved.

agentzh avatar May 04 '14 04:05 agentzh

Global variables are awesome and limitation on them is very sad, so:

require("include")
ngx.say(variable)

You can rewrite it to:

setfenv(loadfile('include.lua'), _G)()
ngx.say(variable)

Or even write helper:

include = function(path)
  return setfenv(loadfile(path .. '.lua'), _G)()
end

And then just use include instead of require

ghost avatar Nov 18 '16 01:11 ghost