2013-03-25 50 views
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" }" 

我可以用table.insert什么使他们成为这个

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

我认为琴弦实际上是像' “{[名] = \” STRING_1 \ “[颜色] = \” 红\“}”'? – 2013-03-25 21:39:17

+1

另外,你的意思是让键是变量'name'和'color'的引用,而不是字符串'name'和'color'? – 2013-03-25 21:43:34

回答

0

在我看来,你有一些你需要解析的JSON字符串。这可以通过使用LuaJSONother ...

2

这些字符串看起来是Lua代码。假设这些字符串的格式是固定的,即您不能选择JSON或其他表示形式,那么正确的做法可能是简单地将它们加载为Lua代码并执行它们。您可能想要对代码进行沙盒处理,具体取决于这些字符串的来源。

在Lua 5.1和Lua 5.2中,做这件事的方法是不同的。你正在使用哪个版本?


下面是在Lua 5.1中做的一个例子。我假设您的示例输入实际上不是您想要的,并且namecolor应该是字符串键,而不是变量的引用。如果它们是变量,那么你需要考虑环境。

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 
0

这个工作在两个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)) 
+1

根据这些字符串的来源,这可能是相当危险的做,因为你不是沙盒。 – 2013-03-25 21:59:43

+0

此外,这不适用于Lua 5.1。 'load()'不能带一个字符串。 – 2013-03-25 22:00:03

+0

@KevinBallard - 谢谢。固定。 – 2013-03-25 22:04:59