0

I need separated string with limited string(for me comma) or char in array. How separated o split with comma in Lua.

I check these links, but I don't understand:

http://lua-users.org/wiki/SplitJoin

http://lua-users.org/wiki/PatternsTutorial

https://stackoverflow.com/questions/1426954/split-string-in-lua

objPropo = {}
str = "Maria Mercedez,,Jose,Sofia"
i = 1
for token in string.gmatch(str, ",") do
    objPropo[i] = token
    i = i + 1
end
native.showAlert("Names", objPropo[1], {"OK"})
native.showAlert("Names", objPropo[2], {"OK"})  <-- Is this error? Because is nil? or what happend?
native.showAlert("Names", objPropo[3], {"OK"})
native.showAlert("Names", objPropo[4], {"OK"})

It could show:

Maria Mercedez

How formatt send patterns?

[Other alternative]

if is possible this?

objPropo = {}
str = "Maria Mercedez,,Jose,Sofia"
i = 1
for token in string.gmatch(str, ",") do
    objPropo[token] = token           <-------- CHECK
    i = i + 1
end
native.showAlert("Names", objPropo["Maria Mercedez"], {"OK"})
native.showAlert("Names", objPropo["Jose"], {"OK"})

Is correct?

Community
  • 1
  • 1
rkv
  • 118
  • 2
  • 13

1 Answers1

5

To split a string with commas, you need to use a pattern that matches non-commas (followed by a comma):

for token in string.gmatch(str, "([^,]+),%s*") do
    objPropo[i] = token
    i = i + 1
end 
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Thanks, but I resolved this problem with: string.gmatch(event.result, "[^,]+") – rkv May 26 '14 at 04:48
  • @Ryuchan That would include whitespaces before the names, if that's what you want. – Yu Hao May 26 '14 at 04:53
  • No included whitespaces before the names. Now, I did edit. I want know what happen if between comma nothing character. – rkv May 26 '14 at 04:56