0

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Leo_xfh
  • 23
  • 4

2 Answers2

1

since the string is actually valid lua syntax you can simply execute it using load()

for example

local txt = "{ {Group = 123, Pos = 200}, {Group = 124, Pos = 205} }"
local Array = load("return " .. txt)()
print(Array[1].Group) --prints 123

Note: for lua version 5.1 or lower it is the function loadstring()

Ivo
  • 18,659
  • 2
  • 23
  • 35
  • Thanks, but I have got an error : Bad argument #1 to 'load' (function expected, got string) on the line : local Array = ... – Leo_xfh Mar 03 '22 at 12:37
  • @Leo_xfh can you try `loadstring` instead? depending on which lua version it is called like that – Ivo Mar 03 '22 at 12:49
  • This lacks sandboxing and is thus insecure for user-provided data. – Luatic Mar 03 '22 at 13:54
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
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15