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

-- examples http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
t( luhn( "49927398716" ), true )
t( luhn( "49927398717" ), false )
t( luhn( "1234567812345678" ), false )
t( luhn( "1234567812345670" ), true )

t()