lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]




On 29/07/15 01:11 PM, Sean Conner wrote:
It was thus said that the Great Soni L. once stated:

On 29/07/15 11:18 AM, Dirk Laurie wrote:
2015-07-29 15:56 GMT+02:00 Soni L. <fakedme@gmail.com>:

Can we get true | false to be a thing?
debug.setmetatable(true,{
   __bor = function(x,y)
     assert (type(x)=='boolean' and type(y)=='boolean')
     return x or y
   end;
     __band = function(x,y)
     assert (type(x)=='boolean' and type(y)=='boolean')
     return x and y
   end;
})

I like that! But why do you call it a proposal?

It would be non-short-circuiting and/or.
   We already have those in the langauge, "and" and "or".  The operators "&",
"|" and "~" work bitwise, not logic wise.  There's a reason why C has both
"|" and "||" for "or".

   -spc


"and" and "or" are the short-circuiting ones. they also do branching.

lua code
-----------------------
function t() print("true") return true end
function f() print("false") return false end

print(t() or f()) -- prints "true" and "true"

print(f() and t()) -- prints "false" and "false"

local left, right = t(), f() -- evaluate both sides, prints "true" and "false"
print(left or right) -- prints "true", after some branching

local left, right = f(), t() -- evaluate both sides, "false" and "true" now
print(left and right) -- prints "false", after some branching

C code
-------------------------
int t() {
  printf("true\n");
  return 1;
}
int f() {
  printf("false\n");
  return 0;
}
int main() {
  printf("%d", t() || f());
  printf("%d", f() && t());

  printf("%d", t() | f());
  printf("%d", f() & t());

  return 0;
}


--
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.