NotMyName
NotMyName

Reputation: 21

LUA: How to Create 2-dimensional array/table from string

I see several posts about making a string in to a lua table, but my problem is a little different [I think] because there is an additional dimension to the table.

I have a table of tables saved as a file [i have no issue reading the file to a string].

let's say we start from this point: local tot = "{{1,2,3}, {4,5,6}}"

When I try the answers from other users I end up with: local OneDtable = {"{1,2,3}, {4,5,6}"}

This is not what i want.

how can i properly create a table, that contains those tables as entries? Desired result:

TwoDtable = {{1,2,3}, {4,5,6}}

Thanks in advance

Upvotes: 1

Views: 979

Answers (2)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7046

For a quick solution I suggest going with the load hack, but be aware that this only works if your code happens to be formatted as a Lua table already. Otherwise, you'd have to parse the string yourself.

For example, you could try using lpeg to build a recursive parser. I built something very similar a while ago:

local lpeg = require 'lpeg'

local name = lpeg.R('az')^1 / '\0'
local space = lpeg.S('\t ')^1

local function compile_tuple(...)
  return string.char(select('#', ...)) .. table.concat{...}
end

local expression = lpeg.P {
  'e';
  e = name + lpeg.V 't';
  t = '(' * ((lpeg.V 'e' * ',' * space)^0 * lpeg.V 'e') / compile_tuple * ')';
}

local compiled = expression:match '(foo, (a, b), bar)'

print(compiled:byte(1, -1))

Its purpose is to parse things in quotes like the example string (foo, (a, b), bar) and turn it into a binary string describing the structure; most of that happens in the compile_tuple function though, so it should be easy to modify it to do what you want.

What you'd have to adapt:

  • change name for number (and change the pattern accordingly to lpeg.R('09')^1, without the / '\0')
  • change the compile_tuple function to a build_table function (local function build_tanle(...) return {...} end should do the trick)
  • Try it out and see if something else needs to be changed; I might have missed something.

You can read the lpeg manual here if you're curious about how this stuff works.

Upvotes: 1

You can use the load function to read the content of your string as Lua code.

local myArray = "{{1,2,3}, {4,5,6}}"
local convert = "myTable = " .. myArray
local convertFunction = load(convert)
convertFunction()
print(myTable[1][1])

Now, myTable has the values in a 2-dimensional array.

Upvotes: 1

Related Questions