Confusion when using gsub()

Why this happens?
When running this code the output is: "Test A 1"

local String = "Test A    "
print(String:gsub("%s+$", ""))

And when running this one the output is the desired one: "Test A"

local String2 = "Test A    "
String2 = String2:gsub("%s+$", "")
print(String2)

I think its the way variables are stored, like youre editing a variable with itself if you know what I mean, try with another variable then cross compare

I see. Well, I wonder if the issue is related with print() itself?

local TestVar = false

local String = "Test A    "

TestVar = String:gsub("%s+$", "") -- Editing the string and storing it
print("'Live' editing:", String:gsub("%s+$", "")) -- Directly printing a "live" string edition
print("PreEdited:", TestVar) -- Printing the stored one

Output:

"'Live' editing: Test A	1"
"PreEdited: Test A"

Ohh, i think i get it, gsub returns a tuple, change line 5 to TestVar, TestVar2 = String:gsub(“%s+$”, “”)

Then change the last line to print TestVar2 as well.

1 Like

Also define TestVar2 in the first line

string | Roblox Creator Documentation

The first code prints the return values of String:gsub i.e. “Test A” and the number of substitutions made i.e. “1”.
The second code prints the value of String2, which you have just changed to be the amended string result of String:gsub(“%s+$”, “”)

1 Like
local TestVar, TestVar2 = false, false

local String = "Test A    "

TestVar, TestVar2 = String:gsub("%s+$", "")
print("'Live' editing:", String:gsub("%s+$", ""))
print("PreEdited:", TestVar, TestVar2)
print("alone", TestVar2)
1 Like

I totally forgot to check what gsub is returning… my mistake, yup its the number of substitutions… lol… Thank you @x1_EE and @Wigglyaa

I will check documentation more often… :v

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