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.

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

hi dasblinkenlight, Thank you and just now get the same answer from this link.. stackoverflow.com/questions/1426954/split-string-in-lua?rq=1
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

Comments

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", ",")

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.