9

I need to split a string and store it in an array. here i used string.gmatch method, and its splitting the characters exactly, but my problem is how to store in an array ? here is my script. my sample string format : touchedSpriteName = Sprite,10,rose

objProp = {}
for key, value in string.gmatch(touchedSpriteName,"%w+") do 
objProp[key] = value
print ( objProp[2] )
end

if i print(objProp) its giving exact values.

ssss05
  • 717
  • 7
  • 14
  • 26

4 Answers4

7

Your expression returns only one value. Your words will end up in keys, and values will remain empty. You should rewrite the loop to iterate over one item, like this:

objProp = { }
touchedSpriteName = "touchedSpriteName = Sprite,10,rose"
index = 1

for value in string.gmatch(touchedSpriteName, "%w+") do 
    objProp[index] = value
    index = index + 1
end

print(objProp[2])

This prints Sprite (link to demo on ideone).

R. Gadeev
  • 188
  • 3
  • 12
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • hi dasblinkenlight, Thank you and just now get the same answer from this link.. http://stackoverflow.com/questions/1426954/split-string-in-lua?rq=1 – ssss05 Oct 03 '12 at 13:27
5

Here's a nice function that explodes a string into an array. (Arguments are divider and string)

-- Source: http://lua-users.org/wiki/MakingLuaLikePhp
-- Credit: http://richard.warburton.it/
function explode(div,str)
    if (div=='') then return false end
    local pos,arr = 0,{}
    for st,sp in function() return string.find(str,div,pos,true) end do
        table.insert(arr,string.sub(str,pos,st-1))
        pos = sp + 1
    end
    table.insert(arr,string.sub(str,pos))
    return arr
end
Darkwater
  • 1,358
  • 2
  • 12
  • 25
1

Here is a function that i made:

function split(str, character)
  result = {}

  index = 1
  for s in string.gmatch(str, "[^"..character.."]+") do
    result[index] = s
    index = index + 1
  end

  return result
end

And you can call it :

split("dog,cat,rat", ",")
Ricardo
  • 1,308
  • 1
  • 10
  • 21
0

Reworked code of Ricardo:

local function  split (string, separator)
    local tabl = {}
    for str in string.gmatch(string, "[^"..separator.."]+") do
        table.insert (tabl, str)
    end
    return tabl
end

print (unpack(split ("1234#5678#9012", "#"))) 
-- returns  1234    5678    9012
darkfrei
  • 122
  • 5