lua - 将 nil 附加到 Lua 序列

标签 lua lua-table

假设我有一个序列:

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 value nil is not considered part of the table. Conversely, any key that is not part of a table has an associated value nil.



所以,一个表 { 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/

相关文章:

windows - lua的字符串模式匹配为什么要这样做呢?

lua - 在 Lua 中的单独函数调用之间缓存字符串上昂贵的表计算

animation - Love2D/Lua 动画系统和表格

lua - 如何在 Lua 中获取第一个表值

indexing - Lua中t.foo和t[foo]的区别

linux - 使用 Lua 检测字符串中是否存在字符

linux - 由于 librpmio.so 导致 Lua API 符号冲突

lua - Redis - Lua 表作为返回值 - 为什么这不起作用

class - 在Lua类中使用表变量

卢阿 |仅表参数的白名单