Strip or add leading zeros

Verified
Added by iNTERFACEWARE

Simple functions to strip or add leading zeros

Source Code
-- following best practice by putting local
-- functions first before main()

local function addZeros(Id, length)
   Id = string.rep('0', length-#Id)..Id
   return Id
end

local function removeZeros(Id)
   while true do 
      if Id:sub(1,1) == '0' then 
         Id = Id:sub(2)
      else
         break
      end
   end   
   return Id
end

function main()
   local Id1 = removeZeros('0004589787')
   local Id2 = addZeros('4589787', 10)
   trace(Id1)
   trace(Id2)
end
Description
Simple functions to strip or add leading zeros
Usage Details

This code uses two functions removeZeros() and addZeros() to strip or add leading zeros from a string.

How to use this code:

  • Simply paste the code into any Lua script component
  • Play around with it to see how it works, try changing the strings
  • See if you can modify it work with numbers
    Hint: Try using tonumber() and tostring() or :S()