Lua:将值存储在字符串数组中

我想为 Lua 数组中的每个字符串元素存储一些值。

-- 模拟不同的浏览器
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"
}

-- 每个浏览器/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)

我注意到在一些例子中,如果我没有初始化字符串数组,那么它就会工作。 有没有人能提供任何更容易的解决方案来实现这一点或更正这个问题。

点赞
用户752976
用户752976

根据您发布的内容,您有一个字符串数组并希望对其元素进行索引;以下代码根本不起作用:

t = { "foo", "bar" }

--t[1]是 "foo"
--t[1].xyz等同于 t[1]["xyz"],它计算出 "foo"["xyz"],这可能不是您想要的

您需要的是一个“对象”的数组:

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

t[1].xyz = 5 -- 正常工作

但是,“foo”将在索引 1下,因此您可能希望为其分配一个名称

t = { {name="foo"}, {name="bar"} }
2013-07-08 11:22:55
用户1847592
用户1847592

在声明 user_agent 之后,但在为 max_conn_perhostmax_conn_total 赋值之前插入以下行:

for i, name in ipairs(user_agent) do
    user_agent[i] = {name = name}
end
2013-07-08 19:07:27