2013-07-08 41 views
2

我想爲Lua數組中的每個字符串元素存儲一些值。Lua:將值存儲在字符串數組中

-- Emulating different Browsers 
local user_agent = { 
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",   
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36",   
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36",     
"Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0",                     
"Mozilla/5.0 (X11; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0",                
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; FunWebProducts)",               
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; InfoPath.1; SV1; .NET CLR 3.8.36217; WOW64; en-US)",    
"Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25" 
} 

-- Number of connections per host and total connections for each browser/user_agent 
user_agent[1].max_conn_perhost , user_agent[1].max_conn_total = 6, 17 
user_agent[2].max_conn_perhost , user_agent[2].max_conn_total = 6, 10 
user_agent[3].max_conn_perhost , user_agent[3].max_conn_total = 6, 10 
user_agent[4].max_conn_perhost , user_agent[4].max_conn_total = 6, 16 
user_agent[5].max_conn_perhost , user_agent[5].max_conn_total = 6, 16 
user_agent[6].max_conn_perhost , user_agent[6].max_conn_total = 6, 35 
user_agent[7].max_conn_perhost , user_agent[7].max_conn_total = 6, 35 
user_agent[8].max_conn_perhost , user_agent[8].max_conn_total = 6, 16 

這是拋出錯誤:

attempt to index field '?' (a string value) 

我已經在一些例子中發現,如果我沒有初始化字符串數組,然後它會工作。 任何人都可以請建議任何更簡單的解決方案來實現這一目標或糾正問題。

回答

5

從你發佈的內容來看,你有一個字符串數組,並且想索引它的元素;該代碼有沒有任何工作機會:

t = { "foo", "bar" } 

-- t[1] is "foo" 
-- t[1].xyz is the same as t[1]["xyz"], which evaluates to "foo"["xyz"], which is probably not what you want 

你需要的是「物」的數組:

t = { {"foo"}, {"bar"} } 

t[1].xyz = 5 -- works 

然而,「富」將成爲下指數1,所以你可能會想爲它

t = { {name="foo"}, {name="bar"} } 
+0

非常感謝您解釋問題和解決方案! –

2

指定一個名稱插入聲明user_agent後這些線路,但分配給max_conn_perhostmax_conn_total前:

for i, name in ipairs(user_agent) do 
    user_agent[i] = {name = name} 
end 
+0

謝謝,這個簡單的解決方案!你能解釋一下第二行是如何實現的嗎?它是否將數組的元素類型化爲對象? –

+0

@KumarVikramjeet - 它用包含這些字符串的對象替換數組元素(字符串)。 –

相關問題