-->

LUHN checksum algorithm Lua implementation

September 12, 2009  |  Jaime Blasco

I have wrote a LUA function that implements the LUHN checksum algorithm (requires bitlib), this algorithm checks that a sequence of digits is a valid credit card number. Here is the code:


local bit = require("bit")

local band, bor, bxor = bit.band, bit.bor, bit.bxor



function checksum(card)

	num = 0

	nDigits = card:len()

	odd = band(nDigits, 1)

	

	for count = 0,nDigits-1 do

		digit = tonumber(string.sub(card, count+1,count+1))

		if (bxor(band(count, 1),odd)) == 0 then

			digit = digit * 2

		end

		

		if digit > 9 then

			digit = digit - 9	

		end

		

		num = num + digit

		

	end

	return ((num % 10) == 0)

	

end

Share this with others

Featured resources

 

 

2024 Futures Report

Get price Free trial