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

9

我需要将一个字符串拆分并存储到数组中。在这里,我使用了string.gmatch方法,并且它确切地拆分了字符,但我的问题是如何存储到数组中?以下是我的脚本。 我的样本字符串格式:touchedSpriteName = Sprite,10,rose

```lua local str = "touchedSpriteName = Sprite,10,rose" local arr = {} for s in string.gmatch(str, "%w+") do table.insert(arr, s) end ```
以上代码将把拆分后的字符串存储在名为“arr”的数组中。
objProp = {}
for key, value in string.gmatch(touchedSpriteName,"%w+") do 
objProp[key] = value
print ( objProp[2] )
end

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

4个回答

7

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

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


嗨,dasblinkenlight,谢谢你。刚才我从这个链接中得到了相同的答案。https://dev59.com/6XM_5IYBdhLWcg3wUxZB?rq=1 - ssss05

5

这是一个很好的函数,可以将字符串分解成数组。(参数为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

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

而且您可以称之为:

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

0
重新编写的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接