Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Count unknown values in a table and list the one that appears the most?

Asked by 8 years ago

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.

1ExampleTable = {"Hi", "Hi", "Hi", "Bye", "Bye"}
2-- It would be "Hi"
3ExampleTable = {"Funny", "Funny", "Not Funny", "Not Funny", "Not Funny"}
4-- It would be "Not Funny"
5ExampleTable = {"12", "12", "1", "12", "1"}
6-- It would be "12"
0
for loop Async_io 908 — 8y
0
I understand that I need a for loop but I can't figure out how I would count the values individually and find the one that shows up the most. shadownetwork 233 — 8y
0
If I don't know anything about the values in the table beforehand expect the fact that they are strings. shadownetwork 233 — 8y

1 answer

Log in to vote
1
Answered by 8 years ago

What you could do

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.


Dictionaries

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!

1local t = {["Key"]}

Now we need to set the key's value. We'll set it to 0 in this example.

1local t = {["Key"] = 0}

Now whenever we check the value for Key, we'll get 0.

1print(t["Key"])

0


Final Product

01local exampledatastore = Datastore:GetDataStore(example)
02--[[
03In this example you've saved all the tables in one datastore
04by saving multiple tables into one single table
05datastore = {{["Key"] = true},{["Key"] = false}}
06^^Kind of like that
07]]
08 
09ExampleTable1 = {} --"Hi", "Hi", "Hi", "Bye", "Bye"
10ExampleTable2 = {} --"Funny", "Funny", "Not Funny", "Not Funny", "Not Funny"
11ExampleTable3 = {} --"12", "12", "1", "12", "1"
12 
13for table,v in pairs(exampledatastore) do
14    if table == 1 then
15        for key,value in pairs(exampledatastore[v]) do
View all 51 lines...


Hope it helps!

Ad

Answer this question