How would I pass a table from server script to server script?

Hi everyone, so today I was wondering if you can pass a table from a server script to a server script and how would you do that?

Module script?

Events?

I have no idea :sweat_smile:

1 Like

Using Module Scripts or remote functions

Modules, bindables. Modules would be better though. With bindables tables get deep-copied so if reference matters then moudles would be better, even if it didn’t matter modules are still better.

So use modules

1 Like

i’d use a module

local module = {}

module.SomeTable = {
    Message = "Hello World"
}

return module

then do

local myModule = require(script.Parent)

print(myModule.SomeTable.Message)

OOORRR you can use the module itself as the whole table

local module = {
    Message = "Hello World"
}

return module

then do

local myModule = require(script.Parent)

print(myModule.Message)
2 Likes

Modules are probably the best way here. It’s essentially a global table, that can be accessed from any of your server scripts.

ModuleScript code example:

local tab = {}
tab.x = 45

function tab:Increment()
tab.x += 1
end

return tab

From any server script:

local server_table = require(PathToTheModule)
server_table:Increment()
print(server_table.x)

But what if I have to store the table, like example, I have a round generating system each round generates a new color table and I want to store that table for later use in another server script?

You could write to a field in a module script, too.

Example:

local myModule = require(PathToModule) --//Obviously would have to return a table

myModule.Color_Table = {} --//assign a new field to the module
1 Like

Never knew you could’ve make a new table in a module, so that can work even if each round you assign a different table how would that work.

like example:

-- new round generates every 1 minute
local ModuleScript = require(game.ReplicatedStorage.ExampleModule)

local newGeneratedColours = {-- random}

ModuleScript.Color_Table =  newGeneratedColours 

Would that work or do I have to approach this another way?

That’s totally fine. If you use the same key, it’ll just overwrite the old table with the new table you’re assigning it to.

e.g:

local tab = {}

tab.x = {1, 2, 3}
tab.x = {1}

print(#tab.x) --//Prints 1, because the old table was overwritten with a new table with 1 element

Hope this makes sense.

1 Like

All right, so the first round works, I was able to store the table in the module script and then retrieved it from another server script.

Main Script:

-- Main Stuff
local RemoteEvent = game.ReplicatedStorage.SideBar.GivePlayerToServer
local level = game.ReplicatedStorage:WaitForChild("GeneratedLevels"):GetChildren()
local studs = 0
local endLevel = game.ReplicatedStorage.End

-- Module
local TestModule2 = require(game.ServerScriptService.TestModule)

-- Table
local ColorTable = {}

while true do
	wait()
	local ColorTable = {}
	for count = 1, 6 do
		for i, placeHolder in pairs(game.Workspace.PlaceHolders:GetChildren()) do
			local chosenLevel = level[math.random(1, #level)]:Clone()
			print(chosenLevel.Name)
			-- Inserting Table Colours
			table.insert(ColorTable, Color3.new(chosenLevel.ColorBar.Value/250,chosenLevel.ColorBar2.Value/250,chosenLevel.ColorBar3.Value/250))
			chosenLevel.PrimaryPart = chosenLevel.Floor
			chosenLevel:SetPrimaryPartCFrame(CFrame.new(placeHolder.Position)+ Vector3.new(studs, 0, 0))
			studs = studs - chosenLevel.studs.Value

			chosenLevel.Parent = game.Workspace.currentLevels
		end
	end

	local endLevelClone = endLevel:Clone()
	endLevelClone.PrimaryPart = endLevelClone.Floor
	endLevelClone:SetPrimaryPartCFrame(CFrame.new(game.Workspace.PlaceHolders.Floor.Position)+ Vector3.new(studs, 0, 0))
	endLevelClone.Parent = game.Workspace.currentLevels	
	print("Be savage")
	-- Adding the Colour Table to the Module
	TestModule2.Color_Table = ColorTable
	
	
	
	-- Other stuff
	local minutes = 6
	local seconds = 0

	local minutesVal = game.ReplicatedStorage:WaitForChild("TimerVal"):WaitForChild("minutesVal")
	minutesVal.Value = minutes

	local secondsVal = game.ReplicatedStorage:WaitForChild("TimerVal"):WaitForChild("secondsVal")
	secondsVal.Value = seconds

	local timer = game.ReplicatedStorage.Timer


	repeat
		if seconds <= 0 and secondsVal.Value <= 0 then
			minutes = minutes - 1
			seconds = 59

			minutesVal.Value = minutesVal.Value - 1
			secondsVal.Value = 59
		else
			seconds = seconds - 1
			secondsVal.Value = secondsVal.Value - 1
		end

		if seconds <= 9 then

			timer.Value = tostring(minutes)..":0"..tostring(seconds) else

			timer.Value = tostring(minutes)..":"..tostring(seconds)
		end

		wait(game.Workspace.Values.WaitSpeed.Value)

	until minutes <= 0 and seconds <= 0

	if minutes <= 0 and seconds <= 0 then		
		-- Claimed Value
		for _, player in ipairs(game:GetService("Players"):GetPlayers()) do
			if (player) then
				player.ClaimedFolder.Claimed.Value = false
			end
		end
		-- Rep Values for local Buttons
		game.ReplicatedStorage.ShopEvents.LocalButtons.invisibilityButton.Value = false
		game.ReplicatedStorage.ShopEvents.LocalButtons.BunnyHopButton.Value = false
		game.ReplicatedStorage.ShopEvents.LocalButtons.FogButton.Value = false
		game.ReplicatedStorage.ShopEvents.LocalButtons.HighSpeedButton.Value = false
		game.ReplicatedStorage.ShopEvents.LocalButtons.LowGravityButton.Value = false
		game.ReplicatedStorage.ShopEvents.LocalButtons.invincibilityButton.Value = false

		-- Bought Values
		script.Parent.ShopItems.BunnyHopFolder.bought.Value = false
		script.Parent.ShopItems.invisivilityFolder.bought.Value = false
		script.Parent.ShopItems.FogFolder.bought.Value = false
		script.Parent.ShopItems.LowGravityFolder.bought.Value = false
		script.Parent.ShopItems.HighSpeedFolder.bought.Value = false
		script.Parent.ShopItems.invincibilityFolder.bought.Value = false
		-- Enabled Value example(BunnyHopEnabled)
		script.Parent.ShopItems.BunnyHopFolder.BunnyHopEnabled.Value = false
		script.Parent.ShopItems.invisivilityFolder.InvisibilityEnabled.Value = false
		script.Parent.ShopItems.FogFolder.FogEnabled.Value = false
		script.Parent.ShopItems.LowGravityFolder.LowGravityEnabled.Value = false
		script.Parent.ShopItems.HighSpeedFolder.HighSpeedEnabled.Value = false
		script.Parent.ShopItems.invincibilityFolder.invincibilityEnabled.Value = false
		-- Fog Back to normal ;)
		game.Lighting.FogEnd = 100000
		game.Lighting.FogStart = 0
		game.Lighting.OutdoorAmbient = Color3.fromRGB(128, 128, 128)
		-- Gravity Back to normal ;)
		game.Workspace.Gravity = 196.2
	end

	for i, player in pairs(game.Players:GetChildren())do
		player:LoadCharacter()
		wait(.1)
		player:LoadCharacter()
	end

	game.Workspace.Values.WaitSpeed.Value = 1
	game.Workspace.Values.SpeedMultiplier.Value = 1	


	game.Workspace.currentLevels:ClearAllChildren()
	studs = 0 
end

Using the Stored Table from the Module:

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
-- Module
local TestModule2 = require(game.ServerScriptService.TestModule)

local DataStore = DataStoreService:GetDataStore('Leaderstats1')

local function equipTrail(player, trail)
	
	local character = player.Character
	
	if trail ~= nil and character ~= nil and player.TrailInventory:FindFirstChild(trail.Name) then
		
		--if character:FindFirstChild(player.Name.."'s trail") then character[player.Name.."'s trail"]:Destroy() end
		
		--if character.HumanoidRootPart:FindFirstChild("attachmentCharacter") then 
		--character.HumanoidRootPart:FindFirstChild("attachmentCharacter"):Destroy() 
		--end
		
		local newTrail = trail:Clone()
		
		newTrail.Name = player.Name.."'s trail"
		
		newTrail.Parent = character.Torso
		
		
		newTrail.Attachment0 = character.Head.FaceFrontAttachment
		newTrail.Attachment1 = character.Torso.WaistBackAttachment
		
		--newTrail.Attachment0 = character.Head.FaceFrontAttachment
		--newTrail.Attachment1 = character.Torso.WaistBackAttachment
		
	end
	
end

--// Settings \\--
local StarterData = {
	Wins = 0;
	ParkourCoins = 0;
	Levels = 0;
	Exp = 0;
};
local playersavetable = {};
local AUTO_SAVE_INTERVAL = 90; -- time when the game auto saves

--// Functions \\--
local function loadStarterData(Player) -- loading the starter data
	local Stats = Instance.new("Folder")
	Stats.Name = 'leaderstats'
	Stats.Parent = Player
	for statname, statvalue in pairs(StarterData) do
		if type(statvalue) == "number" then
		    local numbervalue = Instance.new("NumberValue")
			numbervalue.Name = statname
			numbervalue.Value = statvalue
			numbervalue.Parent = Stats
			
		elseif type(statvalue) == 'boolean' then

		elseif type(statvalue) == 'string' then
			
		end
	end
	
end

local function loadData(Player)-- Loading saved data
	local Data
	local s, e = pcall(function()
	    Data = DataStore:GetAsync('-savinV2'..Player.UserId)
	end)
	
	if s then
		print('Getting '..Player.Name.."'s data was for the main leaderstats successful")
	else
		warn('something went wrong when loading'..Player.Name.."'s data")
	end
	
	if Data then
		for statname, statvalue in pairs(Data) do
			Player.leaderstats[statname].Value = statvalue
		end
		print(Player.Name.."'s main leaderstats data has been loaded!")
	else
		print(Player.Name..' has no main leaderstats data! Generating new data')
	end
end

local function saveData(Player)-- Saving data
	if RunService:IsStudio() then return end
	local Data = {}
	for _, stat in pairs(Player.leaderstats:GetChildren()) do
		Data[stat.Name] = stat.Value
	end
	local s, e = pcall(function()
		DataStore:SetAsync('-savinV2'..Player.UserId, Data)
	end)
	if s then
		print(Player.Name.."'s data has been successfuly saved")
	else
		warn('Something went wrong while saving '..Player.Name.." 's data")
	end
end

Players.PlayerAdded:Connect(function(player)-- loading the data when the player joins
	print("Player Loaded")
	game.ReplicatedStorage.SideBar.FaceSideBar:FireAllClients(player)
	playersavetable[player] = tick()
	loadStarterData(player)
	loadData(player)
	
	local Trailinventory = Instance.new("Folder")
	Trailinventory.Name = "TrailInventory"
	Trailinventory.Parent = player
	
	local equipedTrail = Instance.new("StringValue")
	equipedTrail.Name = "EquippedTrail"
	equipedTrail.Parent = player
	
	player.CharacterAdded:Connect(function(char)
		print("Character Loaded")
		game.ReplicatedStorage.SideBar.FaceSideBar:FireAllClients(player)
		-- Getting the table Stored from the Module and using it
		game.ReplicatedStorage.SideBar.GiveColoursToClient:FireAllClients(TestModule2.Color_Table)
		
		if game.ReplicatedStorage:WaitForChild("Trails"):FindFirstChild(equipedTrail.Value) then
			equipTrail(player, game.ReplicatedStorage:WaitForChild("Trails"):FindFirstChild(equipedTrail.Value):Clone())
		end
	end)
	
	equipedTrail.Changed:Connect(function()
		if equipedTrail.Value ~= nil then
			if game.ReplicatedStorage:WaitForChild("Trails"):FindFirstChild(equipedTrail.Value) then
				equipTrail(player, game.ReplicatedStorage:WaitForChild("Trails"):FindFirstChild(equipedTrail.Value):Clone())
			end
		end
	end)
	
	game.ReplicatedStorage.SystemText.PlayerJoinSystem:FireClient(player)

	while wait() do
		wait(1)
		game.ReplicatedStorage.ShopEvents.LocalButtons.LevelsLocal.Value = player.leaderstats.Levels.Value
	end
end)

Players.PlayerRemoving:Connect(function(player) -- saving the data when a player quits the game
	saveData(player)
end)

game.ReplicatedStorage.EquipTrail.OnServerEvent:Connect(function(player,trailName)
	local trail = game.ReplicatedStorage.Trails:FindFirstChild(trailName)
	
	if player.EquippedTrail.Value == "" then
		print("oki Doki")
		if trail and player.TrailInventory:FindFirstChild(trailName) then
			player.EquippedTrail.Value = trailName
		end
	end
	
end)

game.ReplicatedStorage.UnequipTrail.OnServerEvent:Connect(function(player)
	player.EquippedTrail.Value = ""
	if player.Character.Torso:FindFirstChild(player.Name.."'s trail") then
		player.Character.Torso[player.Name.."'s trail"]:Destroy()
	end
end)

--while true do
	--wait(1)
	--for _, player in pairs(Players:GetPlayers()) do
		--if tick() - playersavetable[player] >= AUTO_SAVE_INTERVAL then
			--saveData(player)
			--playersavetable[player] = tick()
		--end
	--end
--end

But then next round the table doesn’t fully overwrite?

Why are you using 2 local variables for ColorTable?

You have one in your while loop and another outside of the scope. Since they’re named exactly the same thing, when ever you index ColorTable you’ll index the one inside of the loop.

I would assume what you’re trying to do is set ColorTable to a blank table. If that’s the case, remove the local modifier in the while loop one.

1 Like

Use ModuleScripts and BindableFunctions.

1 Like