Home > database >  how to write a Lua pattern to convert string (nested array) into a real array?
how to write a Lua pattern to convert string (nested array) into a real array?

Time:03-03

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

CodePudding user response:

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

  • Related