假设我有一个序列:
a = { 10, 12, 13 }
此序列的长度 (
#a
) 为 3。现在,假设我执行以下操作:
table.insert(a, nil)
(或
a[#a+1] = nil
。)这会以任何方式影响 table 吗?
这个问题的答案是决定性的,还是这种“未定义的行为”?
在我检查过的 Luas(Lua 5.1、Lua 5.3)上,这不会影响表格。但我想知道这是否是我不能依赖的“未定义行为”。
手册只讲添加
nil
到 中 序列,但它没有(根据我的解释)谈论将它添加到 结束 的序列。
最佳答案
添加值 nil
到一个序列,根本没有影响。事实上,一个表不能保存 nil
的值。 .来自 the manual :
Tables can be heterogeneous; that is, they can contain values of all types (except
nil
). Any key with valuenil
is not considered part of the table. Conversely, any key that is not part of a table has an associated valuenil
.
所以,一个表
{ 10, 12, 13, nil}
相当于 { 10, 12, 13 }
,两者都是序列。同样,一个非序列示例:一个表
{10, 20, nil, 40}
相当于 {[1] = 10, [2] = 20, [3] = nil, [4] = 40}
或 {[1] = 10, [2] = 20, [4] = 40}
关于lua - 将 nil 附加到 Lua 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730818/