• Old table overwritten by newer table?
    5 replies, posted
I declared two tables, the 2nd one is for modification. But, when it's finished the new table overwrites the old table. I only want to modify the 2nd table. [CODE] // Weapon IDs with spaces between them. local str =[[m9k_acr m9k_ak47 m9k_ak74]] //tbl for names. local tbl = string.Explode( " ", str ) //tbl2 for IDs of weapons. local tbl2 = tbl // Change the values in tbl2 into names like Arc, Ak47 for a = 1, #tbl2 do // Remove "m9k_" tag. tbl2[a] = string.Replace( tbl2[a], "m9k_", "" ) // Capitalize first letter. local newString = string.gsub(tbl2[a], string.Left(tbl2[a], 1), string.upper(string.Left(tbl2[a], 1) ) ) tbl2[a] = newString --print(newString) end PrintTable(tbl) print() PrintTable(tbl2) [/CODE] The Result: [IMG]http://i.imgur.com/9aILNQo.png[/IMG]
Try: [CODE] local tbl2 = string.Explode( " ", str ) [/CODE] You maybe are writing to tbl through tbl2.
I fixed the problem, but i'm curious on how this happened. tbl2 seems to update tbl at the end of the code. I did a test and that doesn't seem like the issue. [IMG]http://i.imgur.com/53yKZzZ.png[/IMG] [IMG]http://i.imgur.com/rzKDDEy.png[/IMG] Anyway, maybe someone here would explain why.
When you set tbl2 to tbl they are pointing at the same object. When you change one, you change the other. Instead of doing PrintTable just do print and you'll see they both have the same address. [editline]21st October 2015[/editline] In your second code demonstrating the issue, change tbl2 = {"New", "Table" } to tbl2[1] = "New" and you'll see the issue
Is there any way to write a new address for the variable?
[QUOTE=Winter;48997841]Is there any way to write a new address for the variable?[/QUOTE] If you want to copy a table and then modify the copied table, you can use [URL="http://wiki.garrysmod.com/page/table/Copy"]table.Copy[/URL].
Sorry, you need to Log In to post a reply to this thread.