Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does tilde by itself mean in Lua?

Tags:

lua

For the code example:

num_1 = 12 ~ 36

What is the tilde doing in this example? Is it just a shortened way to represent ~= ?

like image 678
tronjo Avatar asked Oct 26 '25 03:10

tronjo


2 Answers

What does tilde by itself mean in Lua?

Operators on their own have no meaning. Only in combination with their operands they make sense.

There are three use-cases for ~ in Lua.

Relational operator ~= unequal: a ~= b is true if a is unequal b

Bitwise operators

  1. binary ~ bitwise XOR: a ~ b resolves to a number where every bit is the XORed value of a's and b's respective bit
  2. unary ~ bitwise NOT: ~a resolves to a number where every bit is inverted. So zeros become ones and ones become zeros.

In your case num_1 = 12 ~ 36 where ~ is used as a binary operator it is the bitwise XOR.

100100  36
001100  12
------ 
101000  40  

So num_1 = 12 ~ 36 assigns 40 to num_1.

like image 66
Piglet Avatar answered Oct 29 '25 07:10

Piglet


˜ is bitwise exclusive OR. See Bitwise Operators in the Reference Manual.

like image 36
lhf Avatar answered Oct 29 '25 05:10

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!