Created
August 22, 2021 10:26
-
-
Save appgurueu/e0b37ef2659a58331c181587601b1d23 to your computer and use it in GitHub Desktop.
Trinary logic implemented in Lua using debug.setmetatable
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
-- 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