Module Scripts for Dummies


  • Module Scripts for Dummies
    Difficulty Level: 3/5 Stars

    Hey everyone, I decided to make a Module Scripts for Dummies tutorial. Basically, a module script is the script with the little grey brick. Module scripts can be compared to global variables/functions in the sense that they make it so you can access certain functions across any script. Let's go over how to use them.

    First off, when you first open a module script after creation it should look like this:

    local module = {}
    
    return module
    

    Now, let's say this module script is inside of the workspace. If we want to access it we can do:

    require(game.Workspace.ModuleScript)
    

    That will give us the table inside of the modulescript called module and everything inside of it.

    Now, let's edit this module script to print out 'Hello World!' when we require it.

    Here's the code:

    local module = {}
    
    module.PrintHello = function()
        print("Hello World!")
    end
    
    return module
    

    Inside of the other script:

    local functions = require(game.Workspace.ModuleScript)
    functions.PrintHello()
    

    In the output 'Hello World!' will appear.

    You can create more functions, and have them do stuff. This is even more helpful if you want to have a 'Settings' script. Here's an example of a module script that acts as a settings script:

    return {
        ["Admins"] = {"AstrealDev", "Player1"};
        ["Banned"] = {"SomeBannedGuy", "kingdom5"};
    }
    

    Inside of another script:

    local settings = require(game.Workspace.Settings)
    print(settings["Admins"][1])    -- Prints 'AstrealDev'
    print(settings["Banned"][2])    -- Prints 'kingdom5'
    

    As you can see, module scripts are extremely useful.

    You can also publish a module script to roblox (CALL THE MODULESCRIPT MainModule OTHERWISE THIS WON'T WORK!!) and get the asset id. Once you have the asset id you can do:

    require(ASSET_ID)
    

    and it will work the same as if the script is inside the game.

    Hope I explained this well! :)


  • Really all a module script does is return a single value.


  • why do i get banned :c


  • @mccrafter1212, your example snippet

    return settings = {
        ["Admins"] = {"AstrealDev", "Player1"};
        ["Banned"] = {"SomeBannedGuy", "kingdom5"};
    }
    

    would error due to settings =, would recommend editing to avoid confusion for any possible future readers:

    return {
        ["Admins"] = {"AstrealDev", "Player1"};
        ["Banned"] = {"SomeBannedGuy", "kingdom5"};
    }
    

    Also, it's worth mentioning that requiring a module using an asset id only works from the server.


  • Woops! You're right! I made a mistake there. Thanks for pointing that out @Pyrondon

Log in to reply
 

Looks like your connection to Scripting Helpers was lost, please wait while we try to reconnect.