在Lua中将字符串拆分并存储到数组中

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

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

如果我打印(objProp),它会给出精确的值。

点赞
用户335858
用户335858

你的表达式只返回一个值。你的单词将最终成为键,而值将保持为空。你应该重写循环以便迭代一个项目,像这样:

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上的演示).

2012-10-03 13:19:56
用户1576117
用户1576117

下面是将一个字符串拆分成数组的一个不错的函数。(参数为 dividerstring

-- 来源: http://lua-users.org/wiki/MakingLuaLikePhp
-- 作者: 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
2012-10-04 08:32:34
用户7347992
用户7347992

以下是我制作的函数:

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", ",")
2018-05-21 04:57:55
用户12968803
用户12968803

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", "#")))
-- 返回 1234    5678    9012
2022-11-22 13:52:51