Search code examples
stringluasplit

Split a string and store in an array in lua


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.


Solution

  • 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).