How to know if a value is a string without numerical elements?

Obviously, I know that I can do string:find(), but why repeat that 10 times? Is there an actual way numerical elements can be detected?

I’m not too sure what you specifically mean, but, my guess is that you’re asking to determine if a string has numbers in it.

You can totally take advantage of pattern matching in that case, particularly the character classes section.

string.find will do a pattern search by default, so you can just use the character class for numerical digits (%d):

local hasNumber = string.find(targetString, "%d") -- search for numerical digits (0123456789)
-- hasNumber will be nil if there are no digits (numbers) but will be the position of the first number if there is one
if not hasNumber then
	-- doesn't have a number in it
	print("There are no numerical digits in the string '" .. targetString .. "'")
else
	-- has a number in it at the index in hasNumber
	local digit = string.sub(hasNumber, hasNumber + 1)
	print("The first numerical digit in the string '" .. targetString .. "' is", digit)
end

Note
Passing a fourth argument of true to string.find disables pattern matching (this is a somewhat newer feature, there used to be no such thing as a plain find built in):

-- search for the text "%d" with pattern matching disabled
print(string.find("123 %d abc", "%d", nil, true)) -- 5 6
-- Note: nil is (sort of) the default for arguments you don't specify, it works on almost any Roblox function to just put "nil" wherever you don't want to pass an argument
-- this won't search for numbers, instead it just uses the plain text of the search argument, so it won't do any pattern matching, and just works like a plain find
2 Likes

Yeah, this is exactly what I was looking for! Sorry if I wasn’t specific.

Thanks a lot! I appreciate it.

1 Like