Difference between revisions of "Bitwise Operators"

From GiderosMobile
m (Text replacement - "<source" to "<syntaxhighlight")
Line 15: Line 15:
 
=== Examples ===
 
=== Examples ===
 
'''Set joypad switches'''
 
'''Set joypad switches'''
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
if k==KeyCode.UP then joypad=joypad|0b001000
 
if k==KeyCode.UP then joypad=joypad|0b001000
 
elseif k==KeyCode.DOWN then joypad=joypad|0b000100
 
elseif k==KeyCode.DOWN then joypad=joypad|0b000100
Line 24: Line 24:
  
 
'''Clear joypad switches'''
 
'''Clear joypad switches'''
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
if k==KeyCode.UP then joypad=joypad&0b0111
 
if k==KeyCode.UP then joypad=joypad&0b0111
 
elseif k==KeyCode.DOWN then joypad=joypadRGUDLR&0b1011
 
elseif k==KeyCode.DOWN then joypad=joypadRGUDLR&0b1011
Line 33: Line 33:
  
 
'''Move in a direction based on joystick switches (using above examples)'''
 
'''Move in a direction based on joystick switches (using above examples)'''
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
local deltaX={0,-1,1,0,0,-1,1,0,0,-1,1,0,0,-1,1,0}
 
local deltaX={0,-1,1,0,0,-1,1,0,0,-1,1,0,0,-1,1,0}
 
local deltaY={0,0,0,0,1,1,1,1,-1,-1,-1,-1,0,0,0,0}
 
local deltaY={0,0,0,0,1,1,1,1,-1,-1,-1,-1,0,0,0,0}
Line 41: Line 41:
  
 
'''Debounce bits, eg joypad switches'''
 
'''Debounce bits, eg joypad switches'''
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
debouncedJoypad=(joypad~joypadOld)&joypad
 
debouncedJoypad=(joypad~joypadOld)&joypad
 
joypadOld=joypad
 
joypadOld=joypad

Revision as of 15:26, 13 July 2023

Supported platforms: Platform android.pngPlatform ios.pngPlatform mac.pngPlatform pc.png
Available since: Gideros 2017.10

Description

Bitwise operators to manipulate numbers.

a | b     Bitwise 'a OR b'.
a & b     Bitwise 'a AND b'.
a ~ b     Bitwise 'a XOR b'.
a << b   Bitwise shift 'a' by 'b' left.
a >> b   Bitwise shift 'a' by 'b' right.
~ a     Bitwise 'NOT a'.

Examples

Set joypad switches <syntaxhighlight lang="lua"> if k==KeyCode.UP then joypad=joypad|0b001000 elseif k==KeyCode.DOWN then joypad=joypad|0b000100 elseif k==KeyCode.LEFT then joypad=joypad|0b000010 elseif k==KeyCode.RIGHT then joypad=joypad|0b000001 end </source>

Clear joypad switches <syntaxhighlight lang="lua"> if k==KeyCode.UP then joypad=joypad&0b0111 elseif k==KeyCode.DOWN then joypad=joypadRGUDLR&0b1011 elseif k==KeyCode.LEFT then joypad=joypadRGUDLR&0b1101 elseif k==KeyCode.RIGHT then joypad=joypadRGUDLR&0b1110 end </source>

Move in a direction based on joystick switches (using above examples) <syntaxhighlight lang="lua"> local deltaX={0,-1,1,0,0,-1,1,0,0,-1,1,0,0,-1,1,0} local deltaY={0,0,0,0,1,1,1,1,-1,-1,-1,-1,0,0,0,0} x=x+deltaX[joypad+1] y=y+deltaY[joypad+1] </source>

Debounce bits, eg joypad switches <syntaxhighlight lang="lua"> debouncedJoypad=(joypad~joypadOld)&joypad joypadOld=joypad </source>

See also

https://www.lua.org/pil/3.3.html