This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Son_Of_Diablo's profile picture

[SOLVED] How to split a string by comma?

Started by Son_Of_Diablo, 08 August 2014 - 02:43 PM
Son_Of_Diablo #1
Posted 08 August 2014 - 04:43 PM
Hello

I want to split a string like this: "1,1" by the comma so I get two variables like: var1 = 1 and var2 = 1


But I can't seem to figure out the string.gmatch function :/



Is there an easy way to do this?

my attempt at this was as following:


t = {}
test = "1,1"
if string.find(test,",") then
   for k, v in string.gmatch(test, "%p") do
		t[k] = v
	end
	print(t[1]..","..t[2])
end

and I will get this error message:


test:10: attempt to concatenate string and nil
Edited on 08 August 2014 - 03:16 PM
Lyqyd #2
Posted 08 August 2014 - 05:01 PM
There aren't ten lines in that script and you're using gmatch incorrectly.

Try something like this:


local results = {}
for match in string.gmatch(input, "[^,]+") do
  table.insert(results, match)
end
KingofGamesYami #3
Posted 08 August 2014 - 05:04 PM
string.gmatch is great. I suggest you read up on patterns.
However, what you are doing is actually much simpler.

local t = {}
local test = "10, 123; 1, 54"
for k, v in test:gmatch( "(%d+),%s?(%d+)" ) do
  t[k] = v
end
I suspect the reason for the error is, by default, string.gmatch returns a single value each iteration. Notice the parentheses I put around the values I wanted from the string.

NInja'd by Lyqyd

Edit: Thanks Lyqyd for pointing that out. I always forget %d *facepalm* (at least until I test it :P/> )
Edited on 08 August 2014 - 03:10 PM
Lyqyd #4
Posted 08 August 2014 - 05:07 PM
Your pattern isn't quite correct; numeric digits are %d, not %n. You're also missing the closing paren on the gmatch call.
Son_Of_Diablo #5
Posted 08 August 2014 - 05:16 PM
There aren't ten lines in that script and you're using gmatch incorrectly.

Try something like this:


local results = {}
for match in string.gmatch(input, "[^,]+") do
  table.insert(results, match)
end

Thanks works like a charm :D/>

also I had some blank lines I forgot to put in the code block here -.-''

string.gmatch is great. I suggest you read up on patterns.
However, what you are doing is actually much simpler.

local t = {}
local test = "10, 123; 1, 54"
for k, v in test:gmatch( "(%d+),%s?(%d+)" ) do
  t[k] = v
end
I suspect the reason for the error is, by default, string.gmatch returns a single value each iteration. Notice the parentheses I put around the values I wanted from the string.

NInja'd by Lyqyd

Edit: Thanks Lyqyd for pointing that out. I always forget %d *facepalm* (at least until I test it :P/> )

Thanks I will make sure to read up on the patterns :)/>