How can i set the name of a dictionary to an existing value?

Hello! I am working on improving my datastore system by cleaning up the code. When it comes to create a table to save, I want to make a dictionary for each value in the stats folder. The dictionary’s name must match the name of the stat. Here is how i would like to see it work.

local statname = "coins"

local dict = {statname = player.stats[statname].Value}
table.insert(data, dict)
-- where 'statname' is the value of the variable

How on earth could i do this?

You can do a for loop to go through every object in your folder, get the name, then add its value to the dictionary.

local dict = {} -- create an empty dictionary, you would save this once you're done
local stats = player.stats:GetChildren() -- list of stat objects
for index, statObject in stats do
	-- this code is purposely longer as a demo
	local key = statObject.Name
	local value = statObject.Value
	dict[key] = value
	
	-- you can do all 3 operations by writing
	-- dict[statObject.Name] = statObject.Value
end

-- once you're done, you can save dict to datastore
saveData(datastoreKey, dict)

Holy cow, thank you so much! I never knew you could use tables in such a way :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.