I am (or was) working on a library extension module, which just adds a bunch of functions that don't exist already into the built-in table
, string
, math
and probably a few more.
Something like...
local _M = { math = setmetatable({ cbrt = function(n) return n^(1/3) end, secant = function(n) return 1/math.cos(n) end -- etc }, {__index = math}) } return _M
And in the requiring script...
local _M = require(module_script) local cube_root = math.cbrt(64) -- 4
Originally, I had tried:
return function() for lib_name, lib in pairs(_M) do getfenv()[lib_name] = lib end end
And the requiring script would import the new "namespaces" with require(module_script)()
. But I guess that only affects the namespace of the module itself, as it never affect the requiring script.
I mean they could just add _M.
as prefix but I really don't want that.
You were just missing the argument to getfenv
that says you want to modify the calling scope, rather than the current one. This works:
return function() for lib_name, lib in pairs(_M) do getfenv(2)[lib_name] = lib end end