Since I can’t explain the situation in 1 sentence, let me clarify:
When you create a variable with a table value, then create a second variable which is equal to the first variable and then modify the second variable, you will just change the first variable but with some extra steps.
How it looks like script wise:
local currentNames = {"Muhammad", "Jacob"}
local newNames = currentNames
newNames[3] = "Joseph"
print(currentNames, newNames)
-- What I expect it to print out: {"Muhammad", "Jacob"}, {"Muhammad", "Jacob", "Joseph"}
-- What it actually prints out: {"Muhammad", "Jacob", "Joseph"}, {"Muhammad", "Jacob", "Joseph"}
You’d expect that it would NOT print the same values, but no, it prints the same values. It’s like the second variable just references the path of the first variable, not actually cloning the value of the first variable.
So I tried to do this with numbers and strings and etc. to see what would happen:
local importantNumber = 25
local newNumber = importantNumbers
newNumber = 10
print(importantNumber, newNumber)
-- What I expect it to print out: 25, 10
-- What it actually prints out: 25, 10
And it doesn’t do the same shenanigans like the tables do.
So how do I work around this in the easiest way?
When trying to fix this problem I’ve found out that you can just create a loop and add the values from the table that you don’t want to modify (currentNames) to the new variable that you want to modify (newNames):
local currentNames = {"Muhammad", "Jacob"}
local newNames = {}
for i,v in currentNames do
newNames[i] = v
end
newNames[3] = "Joseph"
print(currentNames, newNames)
--prints out: {"Muhammad", "Jacob"}, {"Muhammad", "Jacob", "Joseph"}
But is there any easier way to do this?
I tried to search on the internet for this inconvenience but I can’t word my sentence in a way so that Google can understand.
I also do wanna blame this on lua lol