Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I turn a string of a list of numbers into individual numbers?

So let's say I have this:

local String = "25,10"

How could I convert it so I can get access to individual numbers from this string? Surely the comma in between can be used?

2 answers

✓ Accepted answer

you can use the gmatch function of the strings library for this, and the "%d" or digits pattern to get only the numbers

local str = "25,10"

for i in string.gmatch(str,"%d+") do
   print(i)
end
--25
--10

for more information, you can check out the 20th chapter of the of lua pil, or Programming in Lua

1 comment

0

Lovely stuff, now that I have access to the number version of the string, how would I access them individually? using print(i[1]) doesn't work :( what if I have a variable called firstNumber and wish for the first number of the string to be allocate to it?

Although theking48989987's answer does solve your problem, I thought I'd chime in and provide an alternative approach. It's completely up to you what method you choose to use.

%d will indeed match numbers in a string. However, I find a different pattern to be much more handy. As you mentioned in your question...

Surely the comma in between can be used?

...you are surely right! And in my opinion, it should be. In this specific case, the comma character is behaving as a delimiter. A delimiter is nothing more than some character(s) that tell the program to separate, or end, some data. This is what the string pattern should be written in terms of. Therefore, my pattern solution would be [^,]+. For example...

local datum = "1,2,3"

for n in string.gmatch(datum, "[^,]+") do
	print(n)
end

####Output:

1 2 3

The [^,]+ pattern is very simple. It just tell the program to match all characters in between commas, or more specifically, all characters that are not commas (the carrot symbol in the pattern means do not match). Due to the nature of this solution, you may also use it for any list-like structure with a delimiter in a string. For example...

local datum = "name1,name2,name3"

for n in string.gmatch(datum, "[^,]+") do
	print(n)
end

####Output:

name1 name2 name3

I just thought you'd find this handy, and possibly a little more intuitive. Hope this helps.

3 comments

0

Definitely a clarification! Thank you! As much as I would also like to Accept Answer this but it has already been taken! I do apologise

0

i dont think you can use string.match like that in a for loop, did you mean to type "gmatch"?

0

I did -- thanks for catching that. I corrected it.

This discussion is preserved as it was. New answers, comments, and votes are closed.