Tables referencing other variables link the variables

So basically in my script I have a table that has a few references to another table variable. However, all of these tables link together and I can’t change them separately. I was wondering how I could fix this.

Here’s an example.

local exampleTableTemplate = {1,2,3}

local multipleTables = {
     exampleTableTemplate,
     exampleTableTemplate,
     exampleTableTemplate,
     exampleTableTemplate,
     exampleTableTemplate
}

If I did something like

multipleTables[3][1] = 5

Then it would change ALL of the tables’ slot 1 to 5, instead of just table 3’s slot 1 being changed to 5, which is what I want it to do.

Is there any way I could do this?

You must shallow clone the table using table.clone. You can also deep clone it which the code is provided here Tables | Documentation - Roblox Creator Hub

2 Likes

Its not working because:

How Looks Normal Table:

local myFavouriteTable = {}
table.insert(myFavouriteTable, "Murder Mystery 2")
table.insert(myFavouriteTable, "Jailbreak")
table.insert(myFavouriteTable, "Mad City")


Output:
{
--Its Key
  ---
  [1] = {"Murder Mystery 2", "Jailbreak", "Mad City"} -- Its Value
}


How can i get values?? is so easy
for i, v in pairs(myFavouriteTable) do
   print(i)
end

Ur Table:

2 Different Way
local mainTable = {}

mainTable["myFavouriteGames"] = {"Mad City", "Jailbreak", "Adopt Me"}
mainTable["myFavouriteFoods"] = {"Hamburger", "Pizza", "Donut"}

or

local mainTable = {
       --- Sets key to "myFavouriteGames"
  ["myFavouriteGames"] = {"Mad City", "Jailbreak", "Adopt Me"}
  ["myFavouriteFoods"] = {"Hamburger", "Pizza", "Donut"}
}


Output:
{
  ["myFavouriteGames"] = {"Mad City", "Jailbreak", "Adopt Me"}
  ["myFavouriteFoods"] = {"Hamburger", "Pizza", "Donut"}
}

how can i get value ? easy 
mainTable["myFavouriteGames"][1]


Whats ur problem?

wrong version:
mainTable = {
      --- its your key
  {"Jailbreak", "Madcity"}
}


true version:
mainTable = {
     --- its your key
  [1] = {"Jailbreak", "Madcity"}

 or
     --- its your key
  ["blabla"] = {"Jailbreak", "Madcity"}
}

I don’t think the style is the problem here. What is happening is that when @bigbfromcle is attaching the example table into the multiple table, what is happening is multipleTables[1], multipleTables[2], multipleTables[3], etc are all referring to the object table exampleTableTemplate and are simply just ways to call exampleTableTemplate in a different variable.

1 Like

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