2013-03-25 54 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