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:

local ArbitraryTable = {true,false,true,true,false}

local function GetTrueAttributes(Table)
    local TrueBools = 0
    for _,Boolean in pairs(Table) do
        if (Boolean == true) then
            TrueBools = (TrueBools + 1)
        end
    end
    return TrueBools
end

local TotalTrue = GetTrueAttributes(ArbitraryTable)
print(TotalTrue) --// 3

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

Ad

Answer this question