Hello!
On Fri, May 30, 2014 at 12:39 AM, jacquesqiao wrote:
> 请问如果我在set_by_lua里面设置一下全局变量,比如_G["test"] = "123",那么当我require"a"的时候,a能拿到这个变量test么,或者有没有其他方法可以实现这个功能,谢谢~~~
>
_G 全局变量表是每请求的,引用一下 ngx_lua 官方文档的解释:
“...by design, the global environment has exactly the same lifetime as
the Nginx request handler associated with it. Each request handler has
its own set of Lua global variables and that is the idea of request
isolation.”
进一步地,使用 Lua 全局变量是强烈不推荐的做法,引用官方文档的解释:
“Generally, use of Lua global variables is a really really bad idea in
the context of ngx_lua because
1. misuse of Lua globals has very bad side effects for concurrent
requests when these variables are actually supposed to be local only,
2. Lua global variables require Lua table look-up in the global
environment (which is just a Lua table), which is kinda expensive, and
3. some Lua global variable references are just typos, which are hard to debug.
It's highly recommended to always declare them via "local" in the
scope that is reasonable.”
更多细节请参见 https://github.com/openresty/lua-nginx-module#lua-variable-scope
对于你的需求,你可以考虑使用 ngx.ctx API 同一请求的不同处理程序之间(比如在 set_by_lua 和
content_by_lua 之间)传递数据。见
https://github.com/openresty/lua-nginx-module#ngxctx
Regards,
-agentzh