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

How do you make a count of the number of variables in a table that are true?

Asked by 4 years ago

So, I have a table full of variables that are defined by a datastore. I need to cycle through all the variables and check if they are true. Lets say that 4 of the variables are true, then the script would set the variable Count to 4, or if 7 of the variables are true Count would equal 7. How would I do this?

1 answer

Log in to vote
0
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

We can use a pairs iterator to enumerate through a table. Evaluate for a True attribute, and increment a count. If we embody this within a function, we can supply any array and retrieve a result:

01local ArbitraryTable = {true,false,true,true,false}
02 
03local function GetTrueAttributes(Table)
04    local TrueBools = 0
05    for _,Boolean in pairs(Table) do
06        if (Boolean == true) then
07            TrueBools = (TrueBools + 1)
08        end
09    end
10    return TrueBools
11end
12 
13local TotalTrue = GetTrueAttributes(ArbitraryTable)
14print(TotalTrue) --// 3

If this helped, don’t forget to accept this answer!

Ad

Answer this question