indexof

function indexof( arr, val [, init] ) --> idx

Description

Gets the index at which the first occurrence of val is found in arr.

Parameters

arr

The array table to search.

val

The value to search for.

init

The start index to search from, the default value is 1.

Return Values

idx

The index of the matched value, else nil.

Code

--ZFUNC-indexof-v1
local function indexof( arr, val, init ) --> idx
   init = init or 1
   for idx = init, #arr do
      local v = arr[ idx ]
      if v == val then return idx end
   end
   return nil
end

return indexof

Examples

local t = require( "tapered" )
local indexof = require( "indexof" )

arr = { 1, 2, 1, 2 }
t.is( 2, indexof( arr, 2 ) )
t.is( 4, indexof( arr, 2, 3 ) )
t.is( nil, indexof( arr, 3 ) )

t.done()

Inspired by