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
1

2 Answers 2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.