Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to modify built-ins like table, string, math, etc from a module into requiring script?

Asked by 4 years ago
Edited 4 years ago

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.


PLEASE: Only answer if you know what you are talking about. If you think you know, you probably don't.

1 answer

Log in to vote
1
Answered by 4 years ago

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
0
thx bro it worked here's ur 20 points congrats on master programmerHere 371 — 4y
Ad

Answer this question