Error with string.gsub

Hello!

I have a value that has a percentage (e.g. 25%).
I am trying to remove the percentage from my value so it gets converted to an int I can use for comparisons.

Here’s my code:

local percentage = string.gsub("Hello % World", "/[%]/", "")
print(percentage)

Regarding second argument, I’ve tried the following:

  • /[%]/
  • [%]
  • %
  • /%/

On the one in the code snippet above, it returns nil.
On the one with [%], it errors malformed pattern (missing ']')
On the one with %, it errors malformed pattern (ends with '%')

How to fix that?

Thanks in advance,
Mehdi

1 Like

You can identify percentage marks with the following pattern:

string.gsub("hello % world","%%","")

I believe this information used to be on the String Patterns reference page in the dev hub, but it’s not there anymore. Basically you use a double % to capture percentage marks.

1 Like

The escape character for string patterns is the percentage sign itself, so you have to do:

string.gsub("hello % world","%%","")
1 Like

Out of curiosity, how did you end up with a situation where you need to convert a percentage string into an integer? Isn’t this backwards in what usually occurs in a program where the percentage string is made from the integer or is passed around as needed, rather than getting it from the string?

A value in leaderstats that needed to be converted to check if the completion is superior to 75%.

There are 12 “magic characters” which are reserved for special purposes in patterns:
[....]
Instead of using their special meaning, you can precede them with a % symbol to search for them literally.

3 Likes