【问题标题】:Understanding how to access values in array of tables in lua了解如何在 lua 中访问表数组中的值
【发布时间】:2020-05-02 22:06:57
【问题描述】:

自学 lua 并尝试找出如何在嵌套表中访问键和值的数组。 如果我有例如下表:

local coupledNumbers = {}
local a = 10
for i = 1, 12 do
    for j = 1, 12 do
        table.insert(coupledNumbers, {ID = a, result = i*j})
        a = a + 10
    end
end

这个循环会给我钥匙(1 到 144)

for k, v in pairs (coupledNumbers) do
    print (k)
end

这个循环将为我提供值(类似于:table: 0xc475fce7d82c60ea)

for k, v in pairs (coupledNumbers) do
    print (v)
end

我的问题是如何进入表格中的值?

我如何获得 ID 和结果。我认为这样的事情会起作用:

print (coupledNumbers[1].["ID"])

print (coupledNumbers[1].["result"])

但它给出了一个错误。

【问题讨论】:

    标签: arrays lua nested key


    【解决方案1】:

    点符号和括号符号是不同的。您的错误是同时使用它们来索引一件事。 ([1].["ID"]) 问题是.[

    点符号:Table.a.b

    括号表示法:Table["a"]["b"]

    如果你想混合它们,你可以使用Table.a["b"]Table["a"].b

    所以你想做coupledNumbers[1].IDcoupledNumbers[1]["ID"]之类的事情

    据我所知,这实际上只是个人喜好edit: See Pedro's answer for information on the use of variables in dot notation.,尽管您无法使用点符号获得数组的第 nth 项,因此您将总是使用[n]索引一个数字

    【讨论】:

    • 谢谢大家的回答。这有帮助。如果我可以将两个答案标记为正确,我会
    【解决方案2】:

    正如 Allister 所说的那样,错误恰恰在于输入 .[。但我想补充一点:点表示法和方括号表示法 can 做同样的事情,但情况并非总是如此。

    我想补充的是,括号表示法允许您使用变量来引用字段。例如,如果您有以下部分:

    local function getComponent(color, component)
       return color[component]
    end
    
    local c = {
       cyan = 0,
       magenta = 11,
       yellow = 99,
       black = 0
    }
    
    print(getComponent(c, "yellow"))
    

    您根本无法使用点符号来执行此操作。以下将始终返回nil

    local function getComponent(color, component)
       return color.component
    end
    

    这是因为它会在 color 中搜索名为 component 的字段(在此模型中不存在)。

    所以,基本上,我想强调的是,如果您知道该字段,点表示法很好,但是,如果它可能不同,请使用括号。

    【讨论】:

      【解决方案3】:

      来自Lua 5.3 Reference Manual - 3.2 Variables

      方括号用于索引表格:

      var ::= prefixexp ‘[’ exp ‘]’

      语法var.Name 只是var["Name"] 的语法糖:

      var ::= prefixexp ‘.’ Name

      如果您的表键是文字字符串,您只能使用点表示法来索引表值。让 [ 跟在点运算符后面对 Lua 解释器来说没有意义,因为它需要一个文字字符串。

      coupledNumbers[1].["ID"] 替换为coupledNumbers[1].ID

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 2021-05-14
        • 2018-04-24
        • 2016-12-21
        • 2018-04-12
        • 2012-07-30
        • 2017-05-15
        • 1970-01-01
        • 2012-09-08
        相关资源
        最近更新 更多