Modular Script

ModuleScript

A ModuleScript is a reusable piece of code that can be used by both server scripts and client scripts.

It helps organize code that is used in multiple places, making it easy to share functions and data between different scripts in your game.

Utility LibrariesCommon tasks like math operations, or data conversion
Game State ManagementManage the overall state of your game, such as tracking player scores, levels, or game phases.
Data ManagementStore and manage player data that needs to be accessed and modified by multiple scripts.
Shared ConfigurationsStore configuration settings or constants that need to be shared across different scripts
local UtilityModule = {} 

function UtilityModule.reverseString(str) 
   return str:reverse() 
end 

function UtilityModule.roundNumber(num) 
   return math.floor(num + 0.5) 
end 

return UtilityModule
local GameStateModule = {}
GameStateModule.scores = {}

function GameStateModule.addScore(player, score)
    if not GameStateModule.scores[player] then
        GameStateModule.scores[player] = 0
    end
    GameStateModule.scores[player] = GameStateModule.scores[player] + score
end

function GameStateModule.getScore(player)
    return GameStateModule.scores[player] or 0
end

return GameStateModule
local PlayerDataModule = {}
PlayerDataModule.data = {}

function PlayerDataModule.setData(player, key, value)
    if not PlayerDataModule.data[player.UserId] then
        PlayerDataModule.data[player.UserId] = {}
    end
    PlayerDataModule.data[player.UserId][key] = value
end

function PlayerDataModule.getData(player, key)
    return PlayerDataModule.data[player.UserId] and PlayerDataModule.data[player.UserId][key]
End

return PlayerDataModule
local ConfigModule = {}

ConfigModule.GRAVITY = 196.2
ConfigModule.MAX_PLAYERS = 10

return ConfigModule
local Utilities = require(game.ReplicatedStorage.UtilityModule)
print(Utilities.reverseString("Roblox"))
print(Utilities.roundNumber(3.6))

local GameState = require(game.ServerScriptService.GameStateModule)
game.Players.PlayerAdded:Connect(function(player)
    GameState.addScore(player, 10)
    print("Score for player " .. player.Name .. ": " .. GameState.getScore(player))
end)

If you found this tutorial helpful and would like to support my work, please consider buying me a coffee.

Thank you very much for your support!

Buy me a coffee