2012-10-03 61 views
6

我需要拆分一個字符串並將其存儲在一個數組中。在這裏我使用了string.gmatch方法,它精確地分割字符,但我的問題是如何存儲在數組中?這是我的腳本。 我的樣本字符串格式:touchedSpriteName =雪碧,10,玫瑰拆分一個字符串並存儲在lua的數組中

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

如果我打印(objProp)給予其準確值。

回答

4

您的表達式只返回一個值。你的話將以鍵結束,值將保持爲空。你應該重寫循環遍歷一個項目,像這樣:

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

這將打印Spritelink演示上ideone)。

+0

喜dasblinkenlight,謝謝你,剛纔從這個鏈接.. http://stackoverflow.com/questions/1426954/split-string-in-lua得到相同的答案? RQ = 1 – ssss05

4

這是一個很好的函數,它將字符串分解爲一個數組。 (參數是dividerstring

-- 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 
相關問題