Hello!
On Sun, Sep 13, 2015 at 10:53 AM, Robert Paprocki wrote:
> I have written a custom Lua module and have found that the single .lua file
> is getting a bit large; I'm looking at taking various helper functions and
> spreading them into several other files just for sanity. I'm wondering about
> the variances in performance between declaring the function globally like
> so, and not using the returned value in 'require':
>
Avoid global functions since they are also global variables per se.
Always declare functions either as local and/or export via the module
table (as returned by require()).
> lib.lua:
>
> local _M = {}
>
> function _foo ()
> -- function
> end
>
> return _M
>
This is bad since _foo is a global. The global namespace is
per-request while modules survive across requests. This mismatch can
cause subtle problems.
>
> main.lua:
>
> require "lib"
> _foo()
>
The global _foo might not exist in subsequent requests since the
global environment for the time "lib" is loaded would be different
from the one of subsequent requests!
> Versus defining the function as part of a separate module:
>
> lib.lua:
>
> local _M = {}
> function _M._foo ()
> --function
> end
> return _M
>
> main.lua
>
> local lib = require "lib"
> lib._foo()
This is recommended. And main.lua can be simplified further to
require("lib")._foo()
Or maybe you can just use the *_by_lua instead of *_by_lua_file
directive in nginx.conf directly for such one-liners.
>
> Documentation is very clear about avoiding polluting the global namespace
> with variables; does this warning apply to functions as well?
Yes, sure.
> Is there a
> more sane approach to defining functions that could be used in other Lua
> modules or *_by_lua contexts?
Yes, via and only via the calling module's table to reference (you can
also use "local" to save the table lookup overhead on hot code paths
anyway).
Best regards,
-agentzh