Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 了解如何在lua中访问表数组中的值_Arrays_Lua_Nested_Key - Fatal编程技术网

Arrays 了解如何在lua中访问表数组中的值

Arrays 了解如何在lua中访问表数组中的值,arrays,lua,nested,key,Arrays,Lua,Nested,Key,教我自己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) 这个循环将给我一些值(类似于:

教我自己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)

这个循环将给我一些值(类似于:table:0xc475fce7d82c60ea)

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

如何获取ID和结果。我认为这样做会奏效:

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


但它给出了一个错误。

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

点符号:
表a.b

括号符号:
表[“a”][“b”]

如果你想混合它们,你可以做
Table.a[“b”]
Table[“a”].b

因此,您需要执行类似于
coupledNumber[1].ID的操作
coupledNumber[1][“ID”]


据我所知,这实际上只是个人偏好编辑:请参阅Pedro的答案,了解点表示法中变量的使用信息。,尽管你不能用点表示法获得数组的第n项,所以你总是使用
[n]

索引一个数字,正如Allister正确地指出的,错误恰恰在于放置
。[
。但我想补充一点:点表示法和括号表示法可以做同样的事情,但情况并非总是如此

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

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
的字段(在这个模型中不存在)

所以,基本上,我想强调的是,如果你知道这个字段,点符号是可以的,但是,如果它可能会变化,请使用括号

方括号用于索引表格:

var::=prefixexp'['exp']'

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

var::=prefixexp.'Name

如果表键是文本字符串,则只能使用点表示法对表值进行索引。对于Lua解释器来说,在点运算符后面加上
[
没有意义,因为它需要文本字符串


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

谢谢大家的回答。这很有帮助。如果我能将两个答案标记为正确,我会的
print (coupledNumbers[1].["result"])
local function getComponent(color, component)
   return color[component]
end

local c = {
   cyan = 0,
   magenta = 11,
   yellow = 99,
   black = 0
}

print(getComponent(c, "yellow"))
local function getComponent(color, component)
   return color.component
end