asindex

function asindex( i, length [, fit] ) --> idx

Description

Allows to convert a negative index to a valid positive index. The optional fit parameter adds the following manipulation: * If, after the translation of a negative indix, idx is less than 1, it is corrected to 1. *If idx is greater than the string length, it is corrected to length.

Parameters

i

The index value that should be translated.

length

The length of the structure on which the index is used.

fit

Optional boolean parameter that activates with a true value additional manipulation. The default value is false.

Return Values

idx

The translated index value.

Code

--ZFUNC-asindex-v1
local function asindex( i, length, fit ) --> idx
   --ZFUNC-clamp-v1
   local function clamp( num, min, max )
      if num < min then return min
      elseif num > max then return max
      else return num
      end
   end

   if i < 0 then i = length + i + 1 end

   if fit then
      return clamp( i, 1, length )
   end

   return i
end

return asindex

Examples

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

length = 10

t.is( 7, asindex( 7, length ) )

t.is( 10, asindex( -1, length ) )
t.is( 1, asindex( -10, length ) )

t.is( 11, asindex( 11, length ) )
t.is( 0, asindex( 0, length ) )
t.is( 0, asindex( -11, length ) )

t.is( 10, asindex( 10, length, true ) )
t.is( 1, asindex( 0, length, true ) )
t.is( 1, asindex( -11, length, true ) )

t.done()