user5052520
user5052520

Reputation:

Lua xor function code

Does this code work as a xor function in Lua?

function xor (a,b)
if a ~= b then return true else return false end
end

i = false
j = false
if xor(not i, not j) then 
  print("one exclusive") 
else 
  print("both or none") 
end

Upvotes: 2

Views: 4405

Answers (2)

G. Pendergrass
G. Pendergrass

Reputation: 101

My solution would be (looking at the logic gates behind it):

function xor(a,b)
    return (a or b) and (not(a and b))
end

Upvotes: 0

lhf
lhf

Reputation: 72402

Yes, your code works.

If a and b contain boolean values, then a XOR b is the same as not(a == b), which of course is the same as a ~= b.

Upvotes: 4

Related Questions