Skip to content

Instantly share code, notes, and snippets.

@appgurueu
Created June 11, 2021 14:06
Show Gist options
  • Save appgurueu/23ea49b9f216ff595f2c915660ee550f to your computer and use it in GitHub Desktop.
Save appgurueu/23ea49b9f216ff595f2c915660ee550f to your computer and use it in GitHub Desktop.
Trinary logic
-- Set boolean metatable
debug.setmetatable(false, {
__add = function(a, b)
if b == nil then
return b + a
end
return a or b
end,
__mul = function(a, b)
if b == nil then
return b * a
end
return a and b
end,
__unm = function(a)
return not a
end
})
-- Set nil metatable
debug.setmetatable(nil, {
__add = function(a, b)
if b == true then
return true
end
return nil
end,
__mul = function(a, b)
if b == false then
return false
end
return nil
end,
__unm = function()
return nil
end
})
local neg = {
{true, false},
{false, true},
{nil, nil}
}
for _, t in ipairs(neg) do
local a, e = unpack(t)
assert(-a == e)
end
local add = {
{true, true, true},
{true, false, true},
{true, nil, true},
{false, true, true},
{false, false, false},
{false, nil, nil},
{nil, true, true},
{nil, false, nil},
{nil, nil, nil},
}
local mul = {
{true, true, true},
{true, false, false},
{true, nil, nil},
{false, true, false},
{false, false, false},
{false, nil, false},
{nil, true, nil},
{nil, false, false},
{nil, nil, nil},
}
for i = 1, 9 do
do
local a, b, e = unpack(add[i])
assert(a + b == e)
end
do
local a, b, e = unpack(mul[i])
assert(a * b == e)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment