Bitwise

From GMod Wiki

Jump to: navigation, search
Icon-info.png Go to:
Useful Information
Warning 64.pngThis 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.
Lua: Bitwise
Page white text.png 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.
link=User:Butt Face Original Author:Butt Face
Calendar.png Created:22th April 2008

Contents

What is a bitwise?

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
 

Real world example

 
// 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

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox