Lua

Lua: Types

Being dynamically typed, there are no type definitions in Lua. Each value knows its own type.

Lua types:

The type function will return the type of the value passed in.

type(true)       -- boolean
type(nil)        -- nil
type("Gidday")   -- string
type(678.67)     -- number
type(type)       -- function
type({})         -- table

Nil

The nil type has a single value nil. This indicates the absence of a useful value.

Variables have the nil value by default and you can assign nil to a variable to remove it (it will get garbage collected eventually).

Booleans

The boolean type has two values: true and false.

Conditional tests consider the boolean false and the value nil as false and any other value as true.

The and, or, and not logical operators are supported.

The and and or operators evaluate their second operand only when necessary (short-circuit evaluation).

and operator

If the first operand is false, the value of the first operand is returned. Otherwise the value of the second operand is returned.

The thing to remember is that the boolean value false and the value nil are considered the false value and any other value is considered true. This can yield come surprising values if you are used to working with only the pure boolean values true and false in conditional expressions.

> 13 and 56     -- returns 56 because 13 is considered true
> false and 56  -- returns false
> nil and 56    -- returns nil

or operator

The or operator returns the first operand if it is not false. If it is false, the second operand is returned.

> 0 or 24           -- returns 0 because 0 is not false
> false or "hello"  -- returns "hello"
> nil of false      -- returns false

not operator

The not operator always returns true or false.

not nil      -- true
not false    -- true
not 0        -- false
not "apple"  -- false

Idioms when working with boolean values

You will often see the following to set default values.

x = x or v

The variable x will only receive the value v if it is not already set (i.e. has the value nil).

Tools

Web

Languages

Data