'how to write a Lua pattern to convert string (nested array) into a real array?
I would like to convert a string into an array (a small map in a game with coordinates, colors, etc.), the string represents a nested array, and I am not sure how to do it. I would like to open an array after the first { , then open an array after each { , and read the key/value until the } :
function stringToArray()
local Array = {}
local txt = "{ {Group = 123, Pos = 200}, {Group = 124, Pos = 205} }"
for str in string.gmatch(txt, .....
end
Solution 1:[1]
Without such functions that are possibly sandboxed like load() for example
you have to parse the string and construct (key/value pairs) what you want.
A good idea for further decisions/conditions and analyzing could be
to count what is not needed to construct...
local txt = "{ {Group = 123, Pos = 200}, {Group = 124, Pos = 205} }"
local _, lcurlies = txt:gsub('%{','')
local _, rcurlies = txt:gsub('%}','')
local _, commas = txt:gsub(',','')
local _, spaces = txt:gsub('%s','')
local _, equals = txt:gsub('=','')
print(lcurlies,rcurlies,commas,spaces,equals)
-- Puts out: 3 3 3 13 4
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | koyaanisqatsi |
