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( "tapered" )
local findif = require( "findif" )

local iseven = require( "iseven" )

value, pos = findif( { 1, 3, 2, 4 }, iseven )
t.is( 2, value )
t.is( 3, pos )

value, pos = findif( { 1, 2, 3, 16 }, iseven, 3 )
t.is( 16, value )
t.is( 4, pos )

value, pos = findif( { 3, 5, 7, 11 }, iseven )
t.is( nil, value )
t.is( nil, pos )

t.done()

See also