Skip to content

Instantly share code, notes, and snippets.

@Egor-Skriptunoff
Created November 5, 2016 22:51
Show Gist options
  • Save Egor-Skriptunoff/2d47134d4ed9a432c4980b723a1242bf to your computer and use it in GitHub Desktop.
Save Egor-Skriptunoff/2d47134d4ed9a432c4980b723a1242bf to your computer and use it in GitHub Desktop.
------------------------------------------------------------------------------------
-- Module: null.lua
------------------------------------------------------------------------------------
-- How to insert nils in an array?
-- Traditional approach is to appoint some Lua value as nil-replacement.
-- A function null(...) that swaps nils with itself may be a perfect candidate:
-- 1) It represents nil values inside an array
-- 2) It serves as encoder (nil -> null)
-- 3) It serves as decoder (null -> nil)
-- Example:
-- Load the module: require("null")
-- Original data: a tuple of 3 values: 42, nil, nil
-- Encoding: null(42, nil, nil)
-- Encoded data: a tuple without nils: 42, null, null
-- Decoding: null(42, null, null)
-- Restored data: the original tuple: 42, nil, nil
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
return null
@denisdemaisbr
Copy link

nice approach

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment