Split string and save in array in lua

I need to split a string and store it in an array. here i used the string.gmatch method and its character separation exactly, but my problem is how to store in an array? here is my script. my sample string format is: touchedSpriteName = Sprite, 10, rose

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

if I print (objProp) its exact values.

+6
source share
2 answers

Your expression returns only one value. Your words will be included in the keys, and the values ​​will remain empty. You must rewrite the loop to iterate over one element, for example:

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

Submits Sprite (demo link for ideone).

+4
source

Here's a nice function that explodes a string into an array. (Arguments divider and string )

 -- 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 
+4
source

Source: https://habr.com/ru/post/926843/


All Articles