Search code examples
lualua-patterns

How to only keep the first two digits of a string?


I have been trying this but it's not working :

function twonumbers(num)
    num = tostring(num):gsub("%d%d(.*)","")
    return num
end

Basically it's for making a seconds counter using os.clock()

Also tried to make one that only keeps two digits after the dot :

function twodigits(num)
    num = tostring(num):gsub("%.%d%d(.-)","")
    return num
end

I feel like i'm using gsub wrong.


Solution

  • To answer your question directly: just use string.match

    function first_two_digits(str)
        return str:match("^%d%d")
    end
    

    But, you don't need to do this at all, just use math operations:

    math.floor(os.clock())