Why can't I reset a table by doing `table = otherTable`?

My script inn work, just experiment stuff:

local AllMaps = {"map1", "map2", "map3"}
local StoredMaps = AllMaps -- and this works btw
local CurrentMap

function SelectMap()
	if #StoredMaps <= 0 then
		StoredMaps = AllMaps -- does not work
	local SelectedNum = math.random(1,#StoredMaps)
	CurrentMap = StoredMaps[SelectedNum]
	table.remove(StoredMaps, SelectedNum)

for i = 0,9 do

In theory it should reset when the total values in the table are 0, which it doesn’t do:

   ▼  {
    [1] = "map1",
    [2] = "map2",
    [3] = "map3"
   ▼  {
    [1] = "map1",
    [2] = "map2"
   ▼  {
    [1] = "map2"
  {} -- returns empty table as if it skipped the "if"
  ServerScriptService.Script:12: invalid argument #2 to 'random' (interval is empty)

Put a print into the if statement to confirm it runs rq

A table value does not contain a table in it. It is a memory adress where the table is actually stored.

When you have Table1 with 1 Element and Table2 with 2, and you would do Table1 = Table2 - you wouldn’t change the data of the data. You are only saving a different memory adress. At this point, Table1 and Table2 have both the same memory adress which results in both tables beeing permanently equivalent.


This official Roblox page explains it a bit more and if you read it, you will find the solution by yourself!

1 Like

Pass by reference pass by value?

What do you exactly mean? Please explain further.

Pretty sure you’ve provided the solution but I can’t remember the name of this occurrence.
Pass by value refers to passing parameters creating a new variable whilst pass by reference creates a reference to the memory address which would change the original data recorded in said memory address when the reference is changed.

1 Like

sorry i didn’t respond, also I did check if it runs and it does run the if statement

Tables or similar constructs are pass by reference. Primitives are pass by value. You have to rebuild the whole table from scratch and populate the new table.

Just use “table.remove(tablename,anychild)”

Yeah, read what you sent about cloning the tables. {unpack(AllMaps)} seems to do the work for arrays. Thanks