Search code examples
luaenum-flagsbitflags

Gmod Lua - 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().

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?


Solution

  • Lua 5.3 supports bit operators.

    Lua 5.2 and LuaJIT support bit operations as a library (each has their own, they're only partially compatible.)

    Lua 5.1 and older do not have bit operations. If that's what you're using, you can emulate the bit operation by arithmetic. E.g. (in your specific case): (flags/IN_FORWARD)%2 >= 1.

    While I could not find out what Lua version Garry's Mod is based on, it does have bit operations as a library, and you could use bit.band(flags, IN_FORWARD) == IN_FORWARD (or ~= 0, or != 0 with their syntax extensions) instead.