String 拆分字符串并存储在lua中的数组中

String 拆分字符串并存储在lua中的数组中,string,lua,split,String,Lua,Split,我需要拆分字符串并将其存储在数组中。这里我使用了string.gmatch方法,它精确地分割字符,但我的问题是如何存储在数组中?这是我的剧本。 我的示例字符串格式:touchedSpriteName=Sprite,10,rose objProp = {} for key, value in string.gmatch(touchedSpriteName,"%w+") do objProp[key] = value print ( objProp[2] ) end 如果我打印(objProp)

我需要拆分字符串并将其存储在数组中。这里我使用了string.gmatch方法,它精确地分割字符,但我的问题是如何存储在数组中?这是我的剧本。 我的示例字符串格式:touchedSpriteName=Sprite,10,rose

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

如果我打印(objProp)它的精确值。

表达式只返回一个值。您的单词将以键结束,值将保持为空。您应该重写循环以迭代一项,如下所示:

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

这将打印Sprite(在ideone上演示)。

这是一个很好的函数,可以将字符串分解为数组。(参数是
分隔符
字符串


这是我做的一个函数:

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
你可以称之为:

split("dog,cat,rat", ",")

嗨dasblinkenlight,谢谢你,刚才从这个链接得到了同样的答案。。
split("dog,cat,rat", ",")