Storing table in another variable, values missing in another iteration

Hey all!

I’m trying to create like a randomization of 3 out of a table every round, but the problem is that when the function ran again, the cloned table actually has less value than original, isn’t the variable supposed to get assigned newly again? This is what I had.

--// In server script
-- [[ Variables ]]
local valueTable = {1, 2, 3, 4, 5}

-- [[ Functions ]]
local function ChooseValue()
	local valuesClone = valueTable
	local chosenValues = {} --// To have 3 random values
	print(valuesClone)
	
	--// Pick random index out of values, select it and remove from table for non-repeats
	repeat
		local selectedIndex = math.random(1, #valuesClone)
		table.insert(chosenValues, valueTable[selectedIndex])
		table.remove(valuesClone, selectedIndex)
	until #chosenValues >= 3
	
	print(chosenValues)
	return chosenValues
end

The output managed to print 3 random values from the table, but the next iteration failed because there is only 2 left from the table. Not sure if I’m understanding this correctly.

This doesn’t actually clone the table because of how tables pass by reference. It will be the same table as valueTable hence the error with missing values.

To solve it use a function to copy the table like the ones in that article.

1 Like

Ahh, I see, that explains it. Thanks a lot!

Marked as solution.