Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why my string.gsub returns a nonsense string?

Asked by
Tesouro 407 Moderation Voter
9 years ago

I have a part called "Checkpoint2", and inside it, there is a script with this function

print(string.gsub(script.Parent.Name, "Checkpoint", ""))

called when Touched.

It should print "2" , shouldn't it? too bad, cause it prints "2 1" and I have no idea why... I've tried to make a second string.gsub to remove the " 1" , but then it prints "2 0" ! Can someone see an error here? (the rest of the script is useless)

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

gsub actually returns two things. First the string, and then how many times it did the replace.

print prints all things returned, so you're seeing both, separated by a tab.

There isn't an error here at all! If you store it to a variable, you'll see that it works normally:

local str, matches = script.Parent.Name:gsub("Checkpoint","")
print(str)
-- 2
print(matches)
-- 1 (the other number you're seeing)
0
It's kinda weird, but it worked. Thanks. Tesouro 407 — 9y
0
If you added a comma to the str varialbe and added an matches variable after the comma, if you printed the matches variable, I assume it would print the number of matches it found, correct? Spongocardo 1991 — 9y
0
Correct BlueTaslem 18071 — 9y
Ad

Answer this question