Created
November 5, 2016 22:51
-
-
Save Egor-Skriptunoff/2d47134d4ed9a432c4980b723a1242bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
------------------------------------------------------------------------------------ | |
-- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice approach