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
  • Lua has no regex support. Commented Mar 3, 2022 at 9:34

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

Sign up to request clarification or add additional context in comments.

3 Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.