On Fri, May 18, 2012 at 4:26 PM, Sparsh Gupta <spars...@gmail.com> wrote:
> I am writing code for my other locations for nginx in lua. I will be
> using awesome content_by_lua_file for all the locations (total 6) but
> I realized that a lot of code will be duplicate. I can make different
> functions for it and have a common file which I can include in
> locations.lua file
>
> 1. Do you think this is a good idea?
This is exactly what Lua modules are for.
> 2. How exactly this can be done?
>
This should be done via Lua modules, and you're already using Lua
modules like resty.memcached and resty.mysql, right? ;)
Just check out how these modules are implemented and roll out your own
in a similar way.
> e.g. my nginx.conf says:
>
> location = /a.php {
> content_by_lua_file /usr/local/openresty/nginx/conf/a.lua;
> }
>
> in a.lua, i need to include common.lua which is in same folder
> shall I start my a.lua as:
>
> require "common.lua" ? Unable to find examples around
>
You can put common.lua into the same folder as a.lua here (or any
other place) but you need to tell ngx_lua where to look for it by
means of the lua_package_path directive:
lua_package_path "/usr/local/openesty/nginx/conf/?.lua;;";
Please note the ";;" sequence which is not a typo but indicates
inclusion of the default search paths.
And your common.lua should look like this:
module("common", package.seeall)
_VERSION = '0.01'
function trim(s) ... end
...
-- to prevent use of casual module global variables
getmetatable(common).__newindex = function (table, key, val)
error('attempt to write to undeclared variable "' .. key)
end
And finally just "require" it from your a.lua like this:
local common = require "common"
local trim = common.trim
-- use trim() as before...
See also the official documentation on Lua modules in the Lua 5.1
Reference Manual for further information:
http://www.lua.org/manual/5.1/manual.html#5.3
Regards,
-agentzh
P.S. I'm cc'ing the openresty mailing list because other users may
find this useful :)