2012-10-03 108 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 
相关问题