From GMod Wiki
| This page needs to be edited as it contains information that is unclear or incorrect. Improvement can be discussed on the talk page. Find more pages that need work here. Details: None given. |
Description: | Most people don't see the potential of bitwise in Lua or even know it exists in Lua. This article aims to explain a bit about bitwise and how to use it. |
Original Author: | Butt Face |
Created: | 22th April 2008 |
What is a bitwise?
- Bitwise is a set of operators that act on the binary level of a number.
Available Operators
| OR
& AND
<< Bit shift left
>> Bit shift right
Example
local a, b, c, d, e = 1, 2, 4, 8, 16;
local sum = b | e; // 18
local value = e;
if( sum & value == value )then
// Our value is in the sum.
end
- This example may be very overwhelming for bitwise newcomers. But it is only meant to show a very basic use of bitwise operators.
Real world example
- You ask "When the hell would I ever use this in Lua?", well, you might use it to check if a player has access to do a certain thing.
// Each of these must be a power of 2
local kick = 1;
local ban = 2;
local pee = 4;
local weapons = 8;
local user_flags = kick | weapons; // 9
// Check if a user has access to kick
if( user_flags & kick == kick )then
// User has this flag.
end
How does it work?
Here's what happens when you use the OR operator in the previous example kick | weapons :
00000001 //This is 1 in binary
00001000 //And this is 8 in binary
-------- //Using the OR operator, if any of the bits are 1 they will be 1 in the result.
00001001 //This is 9 in binary.
And now for user_flags & kick :
00001001 //This is user_flags( 9 ) in binay
00000001 //And this is kick( 1 ) in binary
-------- //Using the AND operator, if both of the bits are 1 they will be in the result.
00000001 //This is the result of the operation (1) and it is equal to kick which was also 1.
Additional Notes
- Bitwise operators are only available in the Garry's Mod Lua environment, although there are modules that add bitwise functions.
- Hammer uses bitwise to store and retrieve spawnflags. To set them use ent:Fire( "spawnflags", "num" ) where "num" is the value of the flags you want.
- More information on bitwise operators can be found at http://en.wikipedia.org/wiki/Bitwise_operation
- A very helpful tutorial on bitwise (directed towards PHP, but can be easily applied to Lua as well) can be found at http://www.litfuel.net/tutorials/bitwise.htm
- The bitshift, << and >>, operators only seem to work with constants. To get around this, you can use the RunString function.
- This may not be true anymore, with the recent update(November 3rd), they now work with variables.