I’m trying to get the number from a string, but it’s not working for some string
local ZoneNumber = tonumber(string.gsub(Player:GetAttribute("CurrentZone"), "%D", ""))
if not ZoneNumber then
warn("Could not get zone number", Player:GetAttribute("CurrentZone"), "defaulting to Zone1")
By string.gsub you’re literally removing all the digits from the string. tonumber() would return nil because the string is either empty or it only has letters.
That’s incorrect – by capitalizing %d (to %D) it captures every character that wasn’t a number. @NinjoOnline have you tried using Player:GetAttribute("CurrentZone"):match("^Zone(%d+)")?
string.gsub() returns how many replacements it made as its second argument; additionally, tonumber() accepts a second argument specifying the base. As such, your code is attempting to convert to Base4 and is having problems.
This will fix the problem:
local ZoneNumber = tonumber(select(1,string.gsub(Player:GetAttribute("CurrentZone"), "%D", "")))
Alternatively, you could just capture the number with this:
local ZoneNumber = tonumber(string.match(Player:GetAttribute("CurrentZone"),"%d+"))