SharedModule Proposal

[size=6]Hello there, fellow Developers![/size]

With the release of ModuleScripts, the ability to make modular dynamic code has become a lot easier. We no longer have to do as much sharing through _G, or build our own Module system (Which I have seen many implementations). However, I have discovered a slight small issue in regards to the current Module system. When requesting a Module, the Module is executed with it’s OWN environment, preventing us from being able to access variables from within the Main script. In a lot of cases, we would like to be able to access a variable or so from within the ModuleScript, without having to expose to _G.

[size=4]My Proposal:[/size]
Implement a new Module class called “SharedModule”, which will inherit the environment of the first script to require it. This allows us to access variables from within the Main script, while keep our code even cleaner.

EDIT: Guess I forgot to mention that I am asking for a separate class from ModuleScript, instead of replacing. I understand the use of ModuleScripts, but there are uses for such SharedModule also, which I think would be worth implementing.

Thoughts, suggestions, ideas? POST BELOW!

This is an extremely bad idea, you’re misunderstanding part of the contract of ModuleScripts.

The idea of a ModuleScript is that it represents some block of functionality that loaded and can now be included from any other place in your project. But you should not rely on any particular initialization order for your ModuleScripts, doing so is extremely unstable and error prone, as you can end up destroying your entire initialization order by accidentally requiring one module in the wrong place.

As a result, the main code in your ModuleScript should not be “[accessing] variables from within the Main script” like you want the feature to enable, since the ModuleScript has no idea whether the Main script variables in question have actually been initialized yet.

Ideally if you need your ModuleScript to be using information from your game-logic scripts you should have those scripts pass that information into the functions that they call on the ModuleScript, not the other way around having the ModuleScript go digging up information from the things that call it. EG:

-- Like this:
barSettings = ...
Mod = require(module)

-- NOT like this:
_G.barSettings = ...
Mod = require(module) --> reads _G.barSettings

I’d agree with Stravant. If you need code to interact with variables in your script, then write that code in your script. A ModuleScript is nice because it allows code-reuse in any way, which becomes highly restricted if it is assuming variables from its “main” script. ModuleScripts should usually work stand-alone (with some exceptions). For instance, writing API code.

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