Unexcepted string.gsub result

I’m trying to extract the numbers from a string using this

print(tonumber(string.gsub("Stage1", "%D", "")))

and it works. It prints 1. But then when I tried using “Stage5” instead it prints nil, see screenshot below.

Is this a bug? I’m pretty sure this shouldn’t be happening. Is there any workarounds, or if I’m doing something wrong correct me.

string.gsub apparently returns 2 values, so doing

local result = string.gsub("Stage5", "%D", "")
print(tonumber(result))

will give 5 because tonumber() doesnt like the fact simply doing string.gsub doesnt return only 1 string

2 Likes

There is also this ugly way if you don’t care about table overheads

print(tonumber(({string.gsub("Stage5", "%D", "")})[1]))

Too bad you can’t select a specific value from a tuple so you have to do this

2 Likes

I managed doing this using string.match. Thanks anyway.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.