Why does this function work

I came across this block of code that takes a large number and returns the number with commas. I have no idea why this works, so if anyone could explain it that would be great.

function comma_value(amount)
  local formatted = amount
  while true do  
    formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
    if (k==0) then
      break
    end
  end
  return formatted
end
1 Like

Where did you found this code?

I found it from this post:

These are just simple string patterns.

2 Likes

Oh thanks, I’ll take a look at this.

If you want more info essentially it is continuously searching for a number with three digits at the end, then adding the comma to the beginning of those three digits. ^ matches only at the beginning of the string, groups are denoted by parenthesis (Which is what the %1 and %2 reference, the first and second group), and digits are represented by %d. The “+” operator signifies one or more. “-?” means that it will match 1 or 0 “-”, essentially saying that the number can be negative or positive. If you removed that then it would only work with positive numbers.

So in English, it would go something like, match any number of digits starting at the beginning of a string, then exactly after that match three digits, and put a comma in between those two groups. Then iterate until you can’t find any amount of digits followed by three digits, or in other words until it has been fully formatted. You can see this more clearly by just seeing how the first iteration would affect a number. It would go from something like “15000250” to “15000,250” then in the second iteration “15,000,250”. You can see from the original text to the first iteration that you have 1 or more digits (“15000”) followed by three digits (“250”), then it simply places a comma in between the groups.

2 Likes

Thank you so much for that detailed explanation, that helps a lot :slight_smile: !