Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I make a function that changes the value of a table based on another table?

local Table1 = { Table2 = { Lion = 1, Cat = 2, Dog = 3, }, }

for i,v in pairs(Table1.Table2) do print("Table Table2 "..i,v) end

local new_table = { Lion = 6, Cat = 4, Dog = 9, }

for i,v in pairs(new_table) do print("Table new_table "..i,v) end

function updateTable(my_table, game_table) for i,v in pairs(my_table) do Table1.game_table[i] = v end end

updateTable(new_table, Table2)

for i,v in pairs(Table1.Table2) do print("New Table Table2 "..i,v) end

Line 5 gives me this error : attempt to index a nil value (field 'game_table') How can I modify the code for it to work? I'm not sure if I even need to use Table1 in the function, but Table1 is needed in what I'm trying to do, Table 1 will store multiple elements that are related to it.

2 answers

✓ Accepted answer

You are calling Table2, but Table2 is nested inside of Table so try this:

local Table1 = { Table2 = { Lion = 1, Cat = 2, Dog = 3, }, }

for i,v in pairs(Table1.Table2) do print("Table Table2 "..i,v) end

local new_table = { Lion = 6, Cat = 4, Dog = 9, }

for i,v in pairs(new_table) do print("Table new_table "..i,v) end

function updateTable(my_table, game_table) for i,v in pairs(my_table) do Table1[game_table][i] = v end end

updateTable(new_table, "Table2")

for i,v in pairs(Table1.Table2) do print("New Table Table2 "..i,v) end

If you put game_table in brackets then it will use the value of game_table to find the key in Table1, now you can pass in "Table2" as a string

5 comments

0

Thank you, I forgot to put pass Table2 as a string

0

Sounds good! If this answered your question please sit it as the answer!

0

I do not see the option to do this, could it be because there's only one anwer? I tried to see if there was a report option to report this as the answer

0

There should be a button next to the report button that says Set Post as Answer or something like that

0

There's no button, I made sure my adblocker was off too just in case, should I report the answer as "other" and "This answered my question, I cannot find the button to set it as the answer"?

hey you! have you ever heard of enes? if you are in trouble, better call enes!

This discussion is preserved as it was. New answers, comments, and votes are closed.