user2209266
user2209266

Reputation: 29

string to table

I know this is a really weird question, but say i have this type of strings

local string_1 = "{ [name] = "string_1", [color] = "red" }"
local string_2 = "{ [name] = "string_2", [color] = "blue" }"
local string_3 = "{ [name] = "string_3", [color] = "green" }"

can i use table.insert or something to turn them into this

local table_1 = {
    { [name] = "string_1", [color] = "red" };
    { [name] = "string_2", [color] = "blue" };
    { [name] = "string_3", [color] = "green" };
}

Upvotes: 2

Views: 397

Answers (3)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23727

This works in both Lua 5.1 & 5.2

local string_1 = '{ [name] = "string_1", [color] = "red" }'
local string_2 = '{ [name] = "string_2", [color] = "blue" }'
local string_3 = '{ [name] = "string_3", [color] = "green" }'

local function str2tbl(str)
   return assert((loadstring or load)('return '..str:gsub('%[(.-)]','["%1"]')))()
end

local table_1 = {}
table.insert(table_1, str2tbl(string_1))
table.insert(table_1, str2tbl(string_2))
table.insert(table_1, str2tbl(string_3))

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185653

Those strings appear to be Lua code. Assuming the format of these strings is fixed, i.e. you can't pick JSON or some other representation, then the right thing to do is probably to simply load them as Lua code and execute them. You'll probably want to sandbox the code though, depending on where these strings come from.

The way to do this differs between Lua 5.1 and Lua 5.2. Which version are you using?


Here's an example of doing it in Lua 5.1. I'm assuming here that your sample input is actually not what you intended, and that name and color were meant to be string keys, not references to variables. If they are variables, you'll need to muck with the environment.

local strings = {
    "{ name = \"string_1\", color = \"red\" }",
    "{ name = \"string_1\", color = \"red\" }",
    "{ name = \"string_3\", color = \"green\" }"
}

-- parses a string that represents a Lua table and returns the table
local function parseString(str)
    local chunk = loadstring("return " .. str)
    -- Sandbox the function. Does it need any environment at all?
    -- Sample input doesn't need an environment. Let's make it {} for now.
    setfenv(chunk, {})
    return chunk()
end

local tables = {}
for _, str in ipairs(strings) do
    table.insert(tables, parseString(str))
end

Upvotes: 2

darwin
darwin

Reputation: 240

It seems to me that you have some JSON strings that you need to parse. This can be done by using LuaJSON or other...

Upvotes: 0

Related Questions