I have a function that stores data in a table which players have loaded and as soon as there’s enough player’s the script stops checking how many players have loaded. Is there any way that I can continuously share the table between scripts, like make a different server script that has a while loop and is constantly returning the table? I have never done something like this and I’d like to try it, but I have no idea how to even begin.
Here’s the code that I want to run continuously:
local function hasPlayerLoaded(player: Player): bool --Checks if player loaded
if not player.Backpack then return false end --the value "loaded" is in player backpack
local val = player.Backpack:FindFirstChild("Loaded")
return val and val.Value --return the loaded value
end
local function getLoadedPlayers(): {Player} --Checks which players loaded
local players = {} --
for _, player in pairs(game.Players:GetPlayers()) do
if hasPlayerLoaded(player) then table.insert(players, player) end
end
return players
end
Hey there! I guess you haven’t come accross _G, in roblox lua _G s a predefined global table that contains all the global variables. You can use it to share data throughout scripts. Here is an example:
Lets say I define this in server script 1:
_G["Hello"] = "Hello there! I am Steve!"
And then in another server script (server script 2):
I can just do (make sure you define [“Hello”] in the global table first)
print(_G["Hello"])
And it will print out Hello there! I am Steve! for me.
you can use the global table to continuously share information within serverscripts or localscripts.
NOTE: though the global table is different across server and local scripts. That means, local scripts can’t access the global table of server scripts and server scripts cant access the global table of local scripts
Yes, so basically if you were to do this in script 1:
table.insert(_G["Players"],player)
and then you do this in script 2:
print(_G["Players"])
it would have the updated table with the player inserted in it as the players table is an element inside the global table that is shared across the scripts.
So, I need some help with the _G since I’m doing it for the first time.
Would this be the correct approach? It keeps printing out [0] = 0 and doesn’t change at all. If you find anything wrong in the way I used _G please tell me, if everything is correct then I’ll play around with the code until it works like yesterday
_G.players = {}
_G.players[0] = "0"
local function hasPlayerLoaded(player: Player): bool --Checks if player loaded
if not player.Backpack then return false end --the value "loaded" is in player backpack
local val = player.Backpack:FindFirstChild("Loaded")
return val and val.Value --return the loaded value
end
local function getLoadedPlayers(): {Player} --Checks which players loaded --
for _, player in pairs(game.Players:GetPlayers()) do
if hasPlayerLoaded(player) then table.insert(_G.players, player) end
end
end