Module:Nullish

来自Arcaea中文维基
盐棋讨论 | 贡献2022年9月15日 (四) 17:00的版本 (空值合并)

可在Module:Nullish/doc创建此模块的帮助文档

local null, nullish
nullish = function(v) return v == null or v == nil end
local function crash(attr)
    return function(action)
        return function()
            error('attempt to ' .. action .. ' a ' .. attr .. ' value')
        end
    end
end
local nErr, nIll = crash 'null', crash 'illegal'
null = setmetatable({}, {
    __add = nErr "perform arithmetic on",
    __sub = nErr "perform arithmetic on",
    __mul = nErr "perform arithmetic on",
    __pow = nErr "perform arithmetic on",
    __unm = nErr "perform arithmetic on",
    __len = nErr "get length of",
    __lt = nErr "compare something with",
    __le = nErr "compare something with",
    __newindex = function() return end,
    __concat = function(a, b)
        return b == "" and tostring(a) or (a .. "") .. (b .. "")
    end,
    __tostring = function() return "null" end,
    __call = function() return nil end,
    __div = function(a, b)
        if nullish(a) then return b end
        return a
    end,
    __mod = function(a, _)
        if a == null then a = _ end
        return setmetatable({}, {
            __index = nIll 'get',
            __newindex = nIll 'set',
            __call = nIll 'call',
            __len = nIll "get length of",
            __mod = function(_, b)
                if nullish(a) then return b end
                return a
            end
        })
    end
})
return null, nullish