Boolean

From GMod Wiki

Jump to: navigation, search

Boolean.png

Booleans are simple types of data, they can either be true or false.

If you know something is a boolean, you can check if it's true / false like so:

 
if myBool then
    --This code will run if myBool is true
else
    --This code will run if myBool is false
end
 

When a variable is given by itself in an if statement, or is used with a logical operator like !, and, or, etc, or is otherwise used in a situation where it only makes sense to use true / false values, Lua evaluates the variable to (looks at it's value, then returns) true or false. If a variable is equal to nil or false, Lua evaluates it to false. Otherwise, Lua evaluates it to true.

 
local hello = "hi";
local num = 0;
local haveWeapon = false;
 
--evals to true
if hello then
    Msg( "hello evaluated to true\n" );
end
 
--evals to true
if num then
    Msg( "num evaluated to true\n" );
end
 
--evals to false
if haveWeapon then
    Msg( "haveWeapon evaluated to true" );
end
 
--doesNotExist is nil, will eval to false
if doesNotExist then
    Msg( "doesNotExist evaluated to ture" )
end
 

A quick way of setting a variable depending on a boolean is to use and/or.

 
str = godmode and "Godmode on" or "Godmode off"
 

str will be "Godmode on" if godmode is true, otherwise "Godmode off"

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox