如何在表格中表示零 [英] how to represent nil in a table
问题描述
让我们假设要存储元素列表.包括一些零值.值的位置很重要,我需要表示列表中给定位置不存在值.
Let's suppose I want to store a list of element. Including some nil values. The position of the values is significant, and I need to represent the absence of a value in the list at a given position.
这是个问题:
a = {1,2,3,nil,4}
for k,v in ipairs(a) do
print(k,v)
end
print(a[4])
print(a[5])
for循环将仅打印元素1,2和3.它停止在nil位置.第一个print语句显示nil,但是我不确定它是否实际存储在表中. (谁知道?)第二个打印语句按预期打印4-.
The for loop will only print elements 1,2 and 3. It stops at nil. The first print statement prints nil, but I'm not sure if it is actually stored in the table or not. (Who knows?) The second print statement prints 4 - as expected.
所以这是一个问题:如何在表中表示元素列表,并高效地遍历它们?鉴于上述条件,例如该职位很重要,有些职位是空"的.换句话说:没有价值,但是在那个位置没有价值是有意义的.
So here is the question: how to represent a list of elements in a table, and iterate through them efficiently? Given the conditions above, e.g. the position is significant, and some of the positions are "empty". In other words: have no value, but the absence of that value at that position has a meaning.
推荐答案
这是模块"null.lua"
This is module "null.lua"
local function null(...)
local t, n = {...}, select('#', ...)
for k = 1, n do
local v = t[k]
if v == null then t[k] = nil
elseif v == nil then t[k] = null
end
end
return (table.unpack or unpack)(t, 1, n)
end
_G.null = null
使用null()
作为编码器和解码器
Use null()
as encoder and decoder
require("null")
a = {null(1,2,3,nil,4)}
-- the same could be done element-by-element
-- a = {null(1),null(2),null(3),null(nil),null(4)}
for k,v in ipairs(a) do
v = null(v)
print(k,v)
end
print(null(a[4]))
print(null(a[5]))
这篇关于如何在表格中表示零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!