Issues with string.gsub

Hello! I have a problem where I have to find how many twos are in a string. By doing some research, I discovered that string.gsub would return this as its second value. The only problem is that I’m stumped on how to actually get this value.

I’ve tried doing several things, and here is one of my attempts:

local var1, var2 = string.gsub("24512", "2")

print (var1)
print (var2)

In the output it prints:
bad argument #1(string expected, got table)

How can I fix this and get the second value? Also, while I was doing my research I noticed that some people use string:gsub instead of string.gsub. What is the difference between the two?

3 Likes

You forgot the 3rd argument, the string that replaces the pattern string (2nd argument). Are you trying to find all occurrences of a character in a string? If so, you should be using the string.find function instead of string.gsub which is meant for substitution. Also, functions from the string library are methods to all string values just like how FindFirstChild is a method of game.

2 Likes

The first variable is a table because there are two “2” in the string you put
So you can iterate through it and print the values.

1 Like