luhn

function luhn( numstr ) --> res

Description

Simple checksum formula to validate number strings, like credit card numbers.

Parameters

numstr

The number that should be checked as string.

Return Values

res

true if the number is valid, otherwise false.

Code

--ZFUNC-luhn-v1
local function luhn( numstr )
   local add = function( a, b )
      return tonumber( a ) + tonumber( b )
   end

   numstr = string.reverse( numstr )

   local sum = 0

   for i = 1, #numstr do
      if ( i % 2 == 0 ) then
         local doubled = numstr:sub( i, i ) * 2
         doubled = string.gsub( doubled, '(%d)(%d)', add )
         sum = sum + tonumber( doubled )
      else
         sum = sum + tonumber( numstr:sub( i, i ) )
      end
   end

   if ( sum % 10 ) == 0 then return true else return false end
end

return luhn

Examples

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

-- examples http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
t.ok( luhn( "49927398716" ) )
t.nok( luhn( "49927398717" ) )
t.nok( luhn( "1234567812345678" ) )
t.ok( luhn( "1234567812345670" ) )

t.done()