why enable cache on nginx, will cache dofile() variables and local variables

288 views Asked by At

I got a nginx.conf like this:

local /api/{
    # lua_code_cache off;
    default_type application/json;
    content_by_lua_file webapi.lua;
    }

And in webapi.lua, I got code like this:

require("LuaXml")
local xml = xml

function foo1(args)
     dofile(file1)
     local var = var
     xml.load(file1)
end

function foo2(args)
     dofile(file2)
     local var = var
     xml.load(file2)
end

Output is:

The first time I request foo1, everything goes file, local var got value in file1, and xml works file. second time I request foo2, the local var was assigned to the value in file1 but not the value in file2, and xml was nil value for the log says "attempt to index a nil value".

Could anyone teach me ??

1

There are 1 answers

1
agentzh On

This is not ngx_lua caching your dofile call, but your own Lua code being loaded (and maybe including the 3rd-party Lua modules you're using as well) is polluting the Lua global namespace by creating new Lua global variables (like the global "xml" variable). See the following document for more details:

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