【问题标题】:Lua : Storing values in string arrayLua:将值存储在字符串数组中
【发布时间】:2013-07-09 03:07:27
【问题描述】:

我想为 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)

我在一些示例中注意到,如果我没有初始化字符串数组,那么它会起作用。 任何人都可以提出任何更简单的解决方案来实现这一目标或纠正问题。

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

    根据您发布的内容,您有一个字符串数组并且想要索引它的元素;此代码没有任何工作机会:

    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
    

    但是,“foo”将在索引 1 下,因此您可能需要为其指定一个名称

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

    【讨论】:

    • 非常感谢您解释问题和解决方案!
    【解决方案2】:

    在声明user_agent 之后,但在分配给max_conn_perhostmax_conn_total 之前插入这些行:

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

    【讨论】:

    • 感谢您提供这个简短的解决方案!你能解释一下第二行的目标是什么吗?是否将数组的元素类型转换为对象?
    • @KumarVikramjeet - 它正在用包含这些字符串的对象替换数组元素(字符串)。
    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多