Zum Inhalt springen

Modul:CASRN

Faan Wikipedia

Die Dokumentation für dieses Modul kann unter Modul:CASRN/Doku erstellt werden

-- Export
-- a CAS Number have the format ZZZZZZ-ZZ-Z (example 7732-18-5) where at place 1 and 4 from the rigth is always a hyphen
-- therefore is in the script the magic number len-1, len-4 and i ~= 4
-- the latest number is a proof number

local p = {}

function checkCASInternal(CAS)
    local result = false
    if (CAS ~= nil) then
        local len = string.len(CAS)
        local numbercount = 1 
        local sum = 0
        if (len > 5) then
          local proof = string.byte(CAS,len,len)-48
          local hyphen1 = string.byte(CAS,len-1,len-1)
          local hyphen2 = string.byte(CAS,len-4,len-4)
          -- io.write('proof=', proof, ' ')
          if (proof >= 0 and proof <= 9 and hyphen1 == 45 and hyphen2 == 45) then
            -- io.write('ok ')
            for i = 2,len-1 do
              local pos = len - i
              local b = string.byte(CAS,pos,pos+1)-48
              if (b >= 0 and b <= 9) then
                sum = sum + b * numbercount
                -- io.write(b,'*',numbercount,'=',b*numbercount, '  ' )
                numbercount = numbercount + 1
              else
                if (i ~= 4) then 
                   -- io.write('break at ',i, ' ')
                   break
                end
              end
            end
            -- io.write(sum, ' ', sum % 10)
            result = proof == sum % 10
          end
        end
    end
    return result
end

-- if (checkCAS(CAS)) then
--      io.write("\nok")
-- else
--       io.write("\nnok")
-- end

function p.checkCAS( frame )
    return checkCASInternal( frame.args[1] )
end

return p