11 posts
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 = 1But 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
8543 posts
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
3057 posts
Location
United States of America
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
8543 posts
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.
11 posts
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 :)/>