Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 1 year ago
Edited 1 year ago

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

Log in to vote
2
Answered by
bbissell 346 Moderation Voter
1 year ago

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

0
Thank you, I forgot to put pass Table2 as a string iSilkye 7 — 1y
0
Sounds good! If this answered your question please sit it as the answer! bbissell 346 — 1y
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 iSilkye 7 — 1y
0
There should be a button next to the report button that says Set Post as Answer or something like that bbissell 346 — 1y
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"? iSilkye 7 — 1y
Ad
Log in to vote
0
Answered by
enes223 327 Moderation Voter
1 year ago

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

Answer this question