Split a string and store in an array in lua

17,291

Solution 1

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

Solution 2

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
Share:
17,291
ssss05
Author by

ssss05

silence.......

Updated on July 07, 2022

Comments

  • ssss05
    ssss05 over 1 year

    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.