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

length = 10

t( asindex( 7, length ), 7 )

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

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

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

t()