Dictionaries- can you make them VIA script?

Can you create a dictionary via script?

I am trying to do this.

local player_pet_data = {}

for i,v in pairs(player.Pets:GetChildren()) do

player_pet_data[v.Name]["Level"] = 12

end

But it keeps erroring. I also tried to do this.

local player_pet_data = {}

for i,v in pairs(player.Pets:GetChildren()) do

table.insert(player_pet_data, v.Name)

player_pet_data[v.Name]["Level"] = 12

end

Also an error. Am I missing something here?

You have to two-step it. Create the dictionary, then add a key to it.

player_pet_data[v.Name] = {};
player_pet_data[v.Name].Level = 12;

Awesome thanks.

How do I read from this now?

for i,v in pairs(game.Workspace.AllPets:GetChildren()) do
v.Level.Value = player_pet_data[v.Name].Level
end

Something like that?

Correct!

You can set a value in a dictionary using one of the following methods.

dictionary["Level"] = 12
dictionary.Level = 12

And you can get a value from one as follows.

local y = dictionary["Level"]
local x = dictionary.Level

The case with square brackets allows you to use non-string keys.


Bonus-round!

You can also initialize a dictionary like so.

local dictionary = {
    Level = 12
}

And then access them in the same was as you would above.

Thank you so much!

2 Likes

I have been trying to figure out how to do this for so long I am so glad I finally learned how, this will make coding so much easier. I used to just encrypt my datastores like this.

“pet093123Basic Red”

Glad you learned, because encrypting it is extremely inefficient

1 Like

It’s not only inefficient, but it’s messy once you start losing track of things. No kind of encryption is needed for a data store in the first place. Just save raw data.

4 Likes