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( "taptest" )
local indexof = require( "indexof" )

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

t()

Inspired by