How to resolve the algorithm Luhn test of credit card numbers step by step in the Lua programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Luhn test of credit card numbers step by step in the Lua programming language

Table of Contents

Problem Statement

The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:

For example, if the trial number is 49927398716:

Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Luhn test of credit card numbers step by step in the Lua programming language

Source code in the lua programming language

function luhn(n)
  n=string.reverse(n)
  print(n)
  local s1=0
  --sum odd digits
  for i=1,n:len(),2 do
    s1=s1+n:sub(i,i)
  end
  --evens
  local s2=0
  for i=2,n:len(),2 do
    local doubled=n:sub(i,i)*2
    doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end)
    s2=s2+doubled
  end
  print(s1)
  print(s2)
  local total=s1+s2
  if total%10==0 then
    return true
  end
  return false
end 

-- Note that this function takes strings, not numbers.
-- 16-digit numbers tend to be problematic
-- when looking at individual digits.
print(luhn'49927398716')
print(luhn'49927398717')
print(luhn'1234567812345678')
print(luhn'1234567812345670')


  

You may also check:How to resolve the algorithm Reverse a string step by step in the Insitux programming language
You may also check:How to resolve the algorithm Four is magic step by step in the Java programming language
You may also check:How to resolve the algorithm Fivenum step by step in the SAS programming language
You may also check:How to resolve the algorithm Read a file character by character/UTF8 step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm User input/Text step by step in the newLISP programming language