I have a script that pulls values from a DataStore and puts them in a table. These values can be any string. I need to count how many times a value shows up and grab the one that appears the most.
I Can't think of how to do this. The values are complete unknown beforehand.
ExampleTable = {"Hi", "Hi", "Hi", "Bye", "Bye"} -- It would be "Hi" ExampleTable = {"Funny", "Funny", "Not Funny", "Not Funny", "Not Funny"} -- It would be "Not Funny" ExampleTable = {"12", "12", "1", "12", "1"} -- It would be "12"
Make a dictionary. Dictionaries are tables with custom keys. You could make the keys the answer choices and the values the amount of times they're selected.
When you make a dictionary you'd make you custom key by surrounding what would be your key with square brackets []
. Your key itself can be any lua value. Such as a float, boolean or even an object. As long as it isn't nil. And since a string isn't nil we can use it!
local t = {["Key"]}
Now we need to set the key's value. We'll set it to 0 in this example.
local t = {["Key"] = 0}
Now whenever we check the value for Key
, we'll get 0.
print(t["Key"])
0
local exampledatastore = Datastore:GetDataStore(example) --[[ In this example you've saved all the tables in one datastore by saving multiple tables into one single table datastore = {{["Key"] = true},{["Key"] = false}} ^^Kind of like that ]] ExampleTable1 = {} --"Hi", "Hi", "Hi", "Bye", "Bye" ExampleTable2 = {} --"Funny", "Funny", "Not Funny", "Not Funny", "Not Funny" ExampleTable3 = {} --"12", "12", "1", "12", "1" for table,v in pairs(exampledatastore) do if table == 1 then for key,value in pairs(exampledatastore[v]) do ExampleTable1[key] = value end elseif table == 2 then for key,value in pairs(exampledatastore[v]) do ExampleTable2[key] = value end else for key,value in pairs(exampledatastore[v]) do ExampleTable3[key] = value end end end popularanswer = {} --Set the table to find all the most popular answer(Just incase multiple answers have the same amount of clicks.) --We'll use math.max to find out the highest value from each table. Probably a better way to do it than this. number = 0 for i,v in pairs(ExampleTable1) do number = math.max(number,v) table.insert(popularanswer,i) end number = 0 for _,v in pairs(ExampleTable2) do number = math.max(number,v) table.insert(popularanswer,i) end number = 0 for _,v in pairs(ExampleTable3) do number = math.max(number,v) table.insert(popularanswer,i) end print("The most popular answers were as follows: "..table.concat(popularanswer, ", ")..".")
Hope it helps!