Roblox passed table being affected in parent function

Help I am passing a table of players to a function that makes a map for each player centred around a ‘main’ island, after each player’s island has been generated I remove them from the table of players which had been passed.

function MakeMap(players)
	local map = maps[math.random(1,#maps)]
	local central = map.CentralIsland:Clone()

	central.Parent = workspace.Game.Islands

	for ring, capacity in pairs(GameSettings.map.ring_caps) do
		local count = capacity
		local _cap = capacity
		local radius = GameSettings.map.ring_radi[ring]

		if #players < capacity then
			_cap = #players 
		end

		for i, player in pairs(players) do
			local island = map:FindFirstChild("PlayerIsland"):Clone()

			local angle = i * ((2 * math.pi) / _cap)
			local x, z = GetXYFromAngle(angle, radius)

			local position = (central.PrimaryPart.CFrame * CFrame.new(x, 0, z))
			local lookAt = central.PrimaryPart.Position

			island:PivotTo(position)

			island.Parent = workspace.Game.Islands
			island.Name = player.UserId

			count -= 1
			players[i] = nil

			if count == 0 then break end
		end

	end

	return map
end

The problem is this is being passed by a parent function that still needs to use the original and unaffected table of players. I thought when I passed a table to a function it was a mere copy. Thanks

function _Game.new(players)
	print(players) -- Prints | {player}
	local newGame = {}
	setmetatable(newGame, _Game)
	newGame.modifiers = {}
	newGame.stats = _Stats.new(players, newGame.modifiers)
	newGame.players = players-- use loaded players passed from loop script
	print(players) -- Prints | {player}
	newGame.map = MakeMap(players)
	print(players) -- Prints | {}
	newGame.connections = {}
	
	_Game.current = newGame
	
	return newGame
end

As the table is only 1 level deep, you should be able to make use of table.clone() to create a new table that won’t affect the values in the original.

One implementation of it could be replacing

newGame.map = MakeMap(players)

with

newGame.map = MakeMap(table.clone(players))

Thank you I was not aware of that function : )

np!

Just so you know, table.clone will not work the same way if you have tables with multiple layers (e.g. {"A", {"B", {"C"}}}, so if you encounter the original issue with that one then you will need to look into a deep-copy function!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.