findif
function findif( arr, fv [, init] ) --> v, i
Description
Looks through an array table and returning the first element that matches a truth function. The function returns as soon as it finds an acceptable element.
Parameters
- arr
-
The array table where you want to find the value.
- fv
-
Check function that checks the single value.
- init
-
Specifies where to start the search, the default value is 1.
Return Values
- v
-
The first value in the array table that matches the function condition. If no value matches with the function condition is it nil.
- i
-
The index of the first value in the array table that matches the function condition. If no value matches with the function condition is it nil.
Code
--ZFUNC-findif-v1 local function findif( arr, fv, init ) --> v, i init = init or 1 for i = init, #arr do local v = arr[ i ] if fv( v ) then return v, i end end return nil, nil end return findif
Examples
local t = require( "taptest" ) local findif = require( "findif" ) local iseven = require( "iseven" ) value, pos = findif( { 1, 3, 2, 4 }, iseven ) t( value, 2 ) t( pos, 3 ) value, pos = findif( { 1, 2, 3, 16 }, iseven, 3 ) t( value, 16 ) t( pos, 4 ) value, pos = findif( { 3, 5, 7, 11 }, iseven ) t( value, nil ) t( pos, nil ) t()