Lua 表的函数效率

Efficiency of my function with Lua tables

我对这段 Lua 代码的组合方式有疑问。 比如说,有一个像下面这样的函数,包含 200 myTable tables,其中名称按字母顺序排列:

function loadTable(x)
    local myTable
    if x == "aaron" then myTable = {1,2,3,4,5,6,7,8,9,0}
    elseif x == "bobby" then myTable = {1,3,3,4,5,8,7,8,9,1}  
    elseif x == "cory" then myTable = {1,2,3,3,3,6,7,8,9,2}
    elseif x == "devin" then myTable = {1,2,3,4,5,2,3,4,9,0}          
    ...
    else 
        print("table not available") 
    end
    return myTable
end

现在我想找到 x == "zac" 对应的 table (恰好在最后的某个地方)。我使用这行代码:

local foundTable = loadTable("zac")

这样是不是一点效率都没有?如果它必须在函数的最后找到 table,它必须遍历所有前面的代码行。有什么方法可以在 lua 中更有效地编码并更快地找到正确的 table 吗? ?

这可以通过使用...a table!

变得更快

简单的做一个table,键是人名,值是你要加载的table,像这样:

local tables = {
   john = {1,2,3,4,5,6,7,8,9,0},
   peter = {1,3,3,4,5,8,7,8,9,1},
   william = {1,2,3,3,3,6,7,8,9,2},
   victoria = {1,2,3,4,5,2,3,4,9,0}
   --...
}

然后,如果密钥是有效的 identifier

,则只需使用 tables["richard"]tables.richard 而不是调用 loadTable("richard")