Hello (I’m kind of a new scripter so please don’t judge me pls), I made a table which included all of the peoples’ UserId, and I want to share the variable along with different scripts so that they can also receive the variable’s information. But because of my tiny brain, I do not know how to do such a thing. I know I could’ve just used module scripts, but I do not know how to use module scripts as I never used it, and the tutorials are adding up my confusedness about it; I just think they can be a different solution such as Bindable Functions, just do not know how to put it. It will be greatly appreciated if you can help me!
Here’s the UserId Table Code if you want:
local userIds = {}
function PlayerAdded(plr)
table.insert(userIds, plr.UserId)
end
function PlayerRemoving(plr)
local Ind = table.find(userIds, plr.UserId)
if Ind then table.remove(userIds, Ind) end
end
wait()
game.Players.PlayerAdded:Connect(PlayerAdded)
game.Players.PlayerRemoving:Connect(PlayerRemoving)
for _, player in pairs(game.Players:GetPlayers()) do
PlayerAdded(player)
end
print(#userIds)
Module scripts are just having tables shared accross the game
You know how functions can return values
well module scripts return tables with functions that can your values or return your player list and you can get the module by requiring it
example
MODULE SCRIPT
local userid = {}
game.Players.PlayerAdded:Connect(function(plr)
table.insert(userid, plr.UserId)
end)
game.Players.PlayerRemoving:Connect(function(plr)
table.remove(userid, table.find(userid, plr.UserId))
end)
return userid
INSIDE A SCRIPT
require(PATH TO MODULE)
Agreed with @Carrotoplia that module scripts are the way to go to share data like this.
However I also might suggest that this particular table won’t end up beind extremely useful to you.
In situations where you want to do something whenever a new player joins, you’ll have to end up connecting to PlayerAdded anyways.
In situations where you want to do something for every player in the game, it’s just as easy to do for _, player in game.Players:GetPlayers() as it is to do for _, userId in userIds but in the former case you also get more information.
You can use a ModuleScript and store it in the ServerScriptService to share variables globally.
Here is an example ModuleScript called GLOBAL_CONFIG:
local GLOBAL_CONFIG = {}
EXITS_FOUND = 0
function GLOBAL_CONFIG.GetExitsFound()
return EXITS_FOUND
end
function GLOBAL_CONFIG.SetExitsFound(num)
EXITS_FOUND = num
return EXITS_FOUND
end
function GLOBAL_CONFIG.IncrementExitsFound()
EXITS_FOUND = EXITS_FOUND + 1
return EXITS_FOUND
end
return GLOBAL_CONFIG
In any other script, you can include this code to retrieve functions from the GLOBAL_CONFIG script:
local ServerScriptService = game:GetService("ServerScriptService")
local GLOBAL_CONFIG = require(ServerScriptService.GLOBAL_CONFIG)
-- use a function from GLOBAL_CONFIG
local exits = GLOBAL_CONFIG.GetExitsFound()