Search code examples
stringluasplitcoronasdklua-patterns

How to split string in Lua with comma


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?


Solution

  • 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