Mojimi
Mojimi

Reputation: 3161

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.

Upvotes: 1

Views: 638

Answers (1)

daurnimator
daurnimator

Reputation: 4311

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())

Upvotes: 3

Related Questions