user3204845
user3204845

Reputation: 147

How to read a "texted table" into a table

My problem: I have a function that use a table as a variable, but the variables of the function are loaded from a parsed text file and, therefore, this table is read as a string. To be clearer, I have this:

"{x = 1, y = 2, z = 3}"

and I need to convert it into this:

{x = 1, y = 2, z = 3}

I tried string sub, without success. I may try to modify the text file to have 3 fields (each with one of the table variable) to get my results, but that mean a significant modification of the text file structure and of the functions that build that file... if I can use that "texted table" as a table, I'm done.

Upvotes: 3

Views: 40

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

You can load the string into a function and then run it like this:

local str = "{x = 1, y = 2, z = 3}"
local f = assert(load("return " .. str))
local t = f()

In Lua 5.1, use loadstring instead of load.

Upvotes: 2

Related Questions