Change table values using variables

Hi all,

This might be addressed in another topic, but I couldn’t find anything that directly answers this.

I’m trying to clean up my code, as I have a few table references that make my code hard to read. I can use variables to store the values from the table, but I can’t use that same variable to change the value in the original table.
Here’s an example:
Current Code:

local Table = {
   TableOne = {
      IndexOne = {1, 2, 3},
      IndexTwo = {1, 2, 3}
},
   TableTwo = {35, 30, 25},
}

if Table[TableOne[IndexOne[2]]] == Table[TableTwo[3]] then
   Table[TableOne[IndexOne[2]]] = Table[TableTwo[3]] - Table[TableOne[IndexOne[3]]]
else
   Table[TableTwo[3]] = 55
end

What I would like to do:

local Table = {
   TableOne = {
      IndexOne = {1, 2, 3},
      IndexTwo = {1, 2, 3}
},
   TableTwo = {35, 30, 25},
}

local Gold = Table[TableOne[IndexOne[2]]]
local Diamonds = Table[TableOne[IndexOne[3]]]
local Carrots = Table[TableTwo[3]]

if Gold == Carrots then
   Gold = Carrots - Diamonds
else
   Carrots = 55
end

If I try to do this the table values for Gold and Carrots won’t change. Only the variable values will. I could go set the table values to the variables afterwards, but that would defeat the purpose of cleaning up my code.

Is there any way to change the values using the variables? Thank you.

You can change variables directly if they hold tables (or instances like a Part), but not if they hold basic data like numbers or strings.

So you could do

local GoldTable = Table[TableOne[IndexOne]] -- it's a table reference to {1, 2, 3}
local DiamondsTable = Table[TableOne[IndexOne]]
local CarrotsTable = Table[TableTwo]

if GoldTable[2] == CarrotsTable[3] then
  GoldTable[2] = CarrotsTable[3] - DiamondsTable[3]
else
  CarrotsTable[3] = 55
end
2 Likes

Thank you for your response! I was hopping there could be a way to change basic data directly, but this will work fine. :slight_smile:

Gold, diamonds, and carrots are all tables, why? Wouldn’t it be easier to have one single value as gold and not a table for gold values.

This is just an example, my actual code is bit different and I would like to know for the future as well.