Checking if flag exists in bitflag (

I am trying to check if a key is being pressed at the current frame in Gmod Lua with [cmd:GetButtons()][1].

In other words, I am trying to see if a flag exists in a bitflag in Lua.

I am attempting the following code:


-- flags = 1024 (when holding forward)
-- IN_FORWARD = 1024
local flags = cmd:GetButtons()
if (flags & IN_FORWARD) == IN_FORWARD then
    print("You're walking forward.")
end

And receiving the following error in my console:


')' expected near '&'

Does lua not support the logical operator &?

Is there an alertnative way to check if a flag exists in a bitflag using Lua?

There are no bitwise operators in Lua 5.1/LuaJIT 2.0, they were in GMod 10 as garry’s custom bullshit but now you have to use bit.* functions:



if bit.band(flags, IN_FORWARD) ~= 0 then … end


Thank you! I couldn’t find a single answer out there.

You can use ‘&&’ or ‘and’ instead of ‘&’.

No you cannot, the and is a logical AND, not bitwise AND.

Any idea why my player still walks forward after running this?


if bit.band(cmd:GetButtons(), IN_FORWARD) ~= 0 then
    cmd:SetButtons(cmd:GetButtons() - IN_FORWARD)
end

The code below works but the code above doesn’t?


-- Replace jump to attack.
if bit.band(cmd:GetButtons(), IN_JUMP) ~= 0 then
	cmd:SetButtons(cmd:GetButtons() - IN_JUMP + IN_ATTACK)
end

EDIT

Don’t worry, I got it working with:


if bit.band(cmd:GetButtons(), IN_FORWARD) ~= 0 then
	cmd:SetForwardMove(0)
	cmd:SetButtons(cmd:GetButtons() - IN_FORWARD)
end

You will need to use these:

And to remove flags I suggest using bit.band(buttons, bit.bnot(IN_*))

To expand on this a bit for those who might come across it:



-- Set a flag:
var = bit.bor(var, FLAG)

-- Clear a flag:
var = bit.band(var, bit.bnot(FLAG))

-- Toggle a flag:
var = bit.bxor(var, FLAG)


Also do not use regular arithmetic + and - for this, as it will fuck up if you try to set/clear an already set/cleared flag that way.