No prefixing module when require()? Making them global

I’d like to globalize the contents of a module script.

local module = require(moduleScript)


Instead do:

??? require(moduleScript)


Kinda like import from python:

from moduleScript import *

It is possible to ‘inject’ variables into the global environment, although at the cost of quite significant performance penalty. getfenv(0) returns the script environment and we can attach variables to it. However, it’s a deprecated function, and it’s known to also disable some compiler optimisations.

Global access is slower than local, and the cost of indexing module variables is very minimial.

local module = {}
function module.fn() print("Called function 'fn'") end
function module.fn2() print("Called function 'fn2'") end

do local env = getfenv(0)
    for k, v in module do
        env[k] = v
fn(); fn2()

It’s not the best practice in Python either:

  • importing everything can be inefficient;
  • it’s normally useful to be able to clearly associate a variable with a module;
  • but most importantly, from module import * pollutes the namescape, so there’s a danger of namespace collisions if you have multiple modules and variables with the same name.

A standard in Luau is to just index functions of a module, but if you prefer to localize something from it, like using from module import someMethod, you can write:

local module = require(path)
local someMethod = module.someMethod

Thanks for the response, I’ll stick to prefixing module as the solution is seen as it is quite risky and “slower”.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.