So I have a variable named “starterdata” that is a table that contains multiple tables
Then I add this line
local data = starterdata
table.insert(data,"hi")
How does “hi” get inserted to starterdata (I can check by having a loop that goes through starterdata every second and prints what is in it, yes I made sure I used the starterdata variable and not data)??? It should only be inserted into data
I am really confused and have been messing with this for the past hour so I decided to bring this to the devforum
Also this is not a ragebait post I literally do not know what is going on, I can send screenshots if needed
local starterdata =
{
["Currencies"] = {
["Tix"] = 0
},
["Inventory"] = {
["Troops"] = {
"Unit1"
},
["Equipped"] = {
"Unit1"
}
},
["Version"] = 3
}
task.spawn(function() --decoding
while task.wait(1) do
for i,v in starterdata.Inventory.Equipped do
print("starter",v)
end
end
end)
function module.SaveData(plr)
local data = starterdata
table.insert(data.Inventory.Equipped,"Unit2")
end)
So the decoder text will keep printing “Unit1” until the savedata function gets called then it prints “Unit1”, “Unit2” in output
I did clip off some of the stuff in my previous message so I did not have needless information everywhwere
This is called variable referencing. It’s a feature, but it can be confusing sometimes.
Suppose you wanted to make a camera script, but didn’t want to type workspace.Camera a bunch of times.
You’d create a variable that references workspace.Camera local c=workspace.Camera
Now, whenever you modify c, Roblox will modify workspace.Camera instead.
In order to fix this, you can do something like this.
local data={}
for i,v in starterdata do
data[i]=v
end
This is called cloning. It tells Roblox that you don’t want to reference starterdata.
Tell me if you have any problems with this.
The problem is, you are definingdata as a secondary variable for starterdata, so it is basically the same but with a diffrent name
To achieve what you’re trying to do, i’d do:
for i,v in pairs(starterdata) do
table.insert(data,v)
end
table.insert(data,"hi")
uh the code they used in the post crashed me somehow???
local function deepClone(original)
-- Define the new table for the copy
local clone = table.clone(original)
-- Loop through the original table to check for table values
-- If a table is found as a value, deep clone it to the key (index)
for key, value in original do
if type(value) == "table" then
clone[key] = deepClone(value)
end
end
-- Return the finalized copy of the deep cloned table
return clone
end