Last active
December 16, 2023 12:33
-
-
Save gilzoide/6d7c435e4585f8ba96592f89f2442845 to your computer and use it in GitHub Desktop.
Logical XOR in lua
This file contains hidden or 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
-- Returns false if value is falsey (`nil` or `false`), returns true if value is truthy (everything else) | |
function toboolean(v) | |
return v ~= nil and v ~= false | |
end | |
-- Returns true if one value is falsey and the other is truthy, returns false otherwise | |
function xor(a, b) | |
return toboolean(a) ~= toboolean(b) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's not failing, this is just how Lua behaves. I labeled this gist "logical xor" because it follows Lua's boolean logic, which is exactly what I needed at the time.
But it's easy enough to patch toboolean and have a version of xor that considers 0 as false, if anybody ever needs it:
It's also easy enough to inline the toboolean operation into xor as well, although I'd say that's a microoptimization and won't matter in most use cases.