Advertisement

Lua: Operator "or"

Started by June 23, 2011 09:03 AM
4 comments, last by Roots 13 years, 8 months ago
Hey!

I like to have a "Flags" variable in a function... but it don't work, because Lua "or" don't work as expected:

In C++ (or Calculator, works too)
int n = 1 | 2; //-> n = 3, can get them by->
if ((n&2) ) //do something


But in Lua:
n = 1 or 2
io.write(n) -- > says "1"


So, is this a bug? Or is there another operator for doing something like this?
Taken from here:

The disjunction operator or returns its first argument if this value is different from nil and false; otherwise, or returns its second argument.
[/quote]
Since the first argument (1) evaluates to true, it is returned, so the expression "1 or 2" evaluates to 1. or is not bitwise or, but logical or. A quick search suggests that there are no bitwise operators in standard Lua, but there are libraries for it.
Advertisement

Hey!

I like to have a "Flags" variable in a function... but it don't work, because Lua "or" don't work as expected:

In C++ (or Calculator, works too)
int n = 1 | 2; //-> n = 3, can get them by->
if ((n&2) ) //do something


But in Lua:
n = 1 or 2
io.write(n) -- > says "1"


So, is this a bug? Or is there another operator for doing something like this?


lua doesn't support bitwise operators, its or operator works like the c++ || operator and returns 1 or 0 (true or false)

check: http://lua-users.org...itwiseOperators
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!
Thank you both for the fast replys =)
Looks like i missed this one in the docs oO

Thx =D

A quick search suggests that there are no bitwise operators in standard Lua, but there are libraries for it.

Quite true for current Lua version yet the next version has bitops as does LuaJIT. There is a module which implements the same operators for 5.1 as 5.2 , 5.2 however uses a different syntax to LuaJIT but there is a module for 5.1 which is compatible with LuaJIT syntax.


Yes this has always annoyed me about Lua not having native bit-wise ops. It seems especially odd to me considering that Lua is a tiny language designed with embedded platforms in mind, which you think would be making more use of bit-wise operations than standard high-level application code would.

Hero of Allacrost - A free, open-source 2D RPG in development.
Latest release June, 2015 - GameDev annoucement

This topic is closed to new replies.

Advertisement