Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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

1 comment

0

thx bro it worked here's ur 20 points congrats on master

This discussion is preserved as it was. New answers, comments, and votes are closed.