I have a table and I need to check whether all the booleans in that table are true - without checking every single variable myself. How can I do this?
Never mind, I solved it:
numTrue = 0 for i = 1, #t do if t[i] == true then numTrue = numTrue + 1 end end if numTrue == #t then print("all variables in t are true") end
fwiw: lends itself to a “fail-fast” tactic, might only matter if #t is large, fe:
local function areAllTrue(t) for i=1,#t do if (t[i]==false) then return false -- "fail-fast" end end return true -- "succeed slow" end print(tostring(areAllTrue(t)))
It really depends how many there are and how many of them are likely to be true and false, and do you know at the time. If you have thousands of the things, and they are mostly true, then Dave’s approach is going to struggle.
You could keep a parallel track of whether they are all true or false, for example, so something like, initially.
local t = {} local theyAreAllTrue = true
then when you put an entry in
t[someKey] = someValue if not someValue then theyAreAllTrue = false end
then the theyAreAllTrue variable will become false the moment you put a false in the table. This may not be practical to do, of course.
Different algorithms work differently in different contexts. Often it doesn’t matter - if it is a table of 10 you look at once a frame, anything will work. If it’s 1,000 and you call it 20 times it won’t.
One further comment ; do some work into boolean data types. You can scan your array like this -
local result = true for i = 1,#t do result = result and t[i] end
Never mind, I solved it:
numTrue = 0 for i = 1, #t do if t[i] == true then numTrue = numTrue + 1 end end if numTrue == #t then print("all variables in t are true") end
fwiw: lends itself to a “fail-fast” tactic, might only matter if #t is large, fe:
local function areAllTrue(t) for i=1,#t do if (t[i]==false) then return false -- "fail-fast" end end return true -- "succeed slow" end print(tostring(areAllTrue(t)))
It really depends how many there are and how many of them are likely to be true and false, and do you know at the time. If you have thousands of the things, and they are mostly true, then Dave’s approach is going to struggle.
You could keep a parallel track of whether they are all true or false, for example, so something like, initially.
local t = {} local theyAreAllTrue = true
then when you put an entry in
t[someKey] = someValue if not someValue then theyAreAllTrue = false end
then the theyAreAllTrue variable will become false the moment you put a false in the table. This may not be practical to do, of course.
Different algorithms work differently in different contexts. Often it doesn’t matter - if it is a table of 10 you look at once a frame, anything will work. If it’s 1,000 and you call it 20 times it won’t.
One further comment ; do some work into boolean data types. You can scan your array like this -
local result = true for i = 1,#t do result = result and t[i] end