lua - how to represent nil in a table -
let's suppose want store list of element. including nil values. position of values significant, , need represent absence of value in list @ given position.
here problem:
a = {1,2,3,nil,4} k,v in ipairs(a) print(k,v) end print(a[4]) print(a[5])
the loop print elements 1,2 , 3. stops @ nil. first print statement prints nil, i'm not sure if stored in table or not. (who knows?) second print statement prints 4 - expected.
so here question: how represent list of elements in table, , iterate through them efficiently? given conditions above, e.g. position significant, , of positions "empty". in other words: have no value, absence of value @ position has meaning.
this module "null.lua"
local function null(...) local t, n = {...}, select('#', ...) k = 1, n local v = t[k] if v == null t[k] = nil elseif v == nil t[k] = null end end return (table.unpack or unpack)(t, 1, n) end _g.null = null
use null()
encoder , decoder
require("null") = {null(1,2,3,nil,4)} -- same done element-by-element -- = {null(1),null(2),null(3),null(nil),null(4)} k,v in ipairs(a) v = null(v) print(k,v) end print(null(a[4])) print(null(a[5]))
Comments
Post a Comment