Easy Tutorial
❮ Lua Basic Syntax Lua Environment ❯

Lua Data Types

Lua is a dynamically typed language; variables do not require type definitions, only assignment. Values can be stored in variables, passed as parameters, or returned as results.

Lua has 8 basic types: nil, boolean, number, string, userdata, function, thread, and table.

Data Type Description
nil The simplest type, with only the value nil belonging to it, representing an invalid value (equivalent to false in conditional expressions).
boolean Contains two values: false and true.
number Represents a double-precision real floating-point number.
string Strings are denoted by a pair of double or single quotes.
function Functions written in C or Lua.
userdata Represents arbitrary C data structures stored in variables.
thread Represents an independent execution thread, used for coroutines.
table Tables in Lua are "associative arrays," where indices can be numbers, strings, or table types. Tables are created using "constructor expressions"; the simplest is {}, which creates an empty table.

You can test the type of a given variable or value using the type function:

Example

print(type("Hello world"))      --> string
print(type(10.4*3))             --> number
print(type(print))              --> function
print(type(type))               --> function
print(type(true))               --> boolean
print(type(nil))                --> nil
print(type(type(X)))            --> string

nil (Empty)

The nil type represents a lack of valid value; it only has one value, nil. For example, printing an unassigned variable will output a nil value:

> print(type(a))
nil
>

For global variables and tables, nil also has a "delete" effect. Assigning a nil value to a global variable or a variable in a table is equivalent to deleting it. The following code demonstrates this:

tab1 = { key1 = "val1", key2 = "val2", "val3" }
for k, v in pairs(tab1) do
    print(k .. " - " .. v)
end

tab1.key1 = nil
for k, v in pairs(tab1) do
    print(k .. " - " .. v)
end

When comparing nil, it should be enclosed in double quotes ":

> type(X)
nil
> type(X)==nil
false
> type(X)=="nil"
true
>

The result of type(X)==nil being false is because type(X) actually returns the string "nil", which is of type string:

type(type(X))==string

boolean (Boolean)

The boolean type has two possible values: true (true) and false (false). Lua considers false and nil as false, and everything else as true, including the number 0:

Example

print(type(true))
print(type(false))
print(type(nil))

if false or nil then
    print("At least one is true")
else
    print("false and nil are both false")
end

if 0 then
    print("The number 0 is true")
else
    print("The number 0 is false")
end

The above code results in:

$ lua test.lua 
boolean
boolean
nil
false and nil are both false
The number 0 is true

number (Number)

Lua has only one number type by default—double (double-precision) type (the default type can be changed in luaconf.h). The following are all considered number types:

Example

print(type(2))
print(type(2.2))
print(type(0.2))
print(type(2e+1))
print(type(0.2e-1))
print(type(7.8263692594256e-06))

The above code results in:

number
number
number
number
number
number

string (String)

Strings are denoted by a pair of double or single quotes.

string1 = "this is string1"
string2 = 'this is string2'

You can also use two square brackets "[[]]" to denote a "block" of strings.

Example

html = [[
<html>
<head></head>
<body>
    <a href="http://www.tutorialpro.org/">tutorialpro.org</a>
</body>
</html>
]]
print(html)

The above code results in:

<html>
<head></head>
<body>
    <a href="http://www.tutorialpro.org/">tutorialpro.org</a>
</body>
</html>

When performing arithmetic operations on a numeric string, Lua tries to convert the string to a number:

> print("2" + 6)
8.0
> print("2" + "6")
8.0
> print("2 + 6")
2 + 6
> print("-2e2" * "6")
-1200.0
> print("error" + 1)
stdin:1: attempt to perform arithmetic on a string value
stack traceback:
        stdin:1: in main chunk
        [C]: in ?
>

In the above code, "error" + 1 causes an error. String concatenation uses .., as shown below:

> print("a" .. 'b')
ab
> print(157 .. 428)
157428
>

Use # to calculate the length of a string, placed before the string, as shown in the example:

Example

> len = "www.tutorialpro.org"
> print(#len)
14
> print(#"www.tutorialpro.org")
14
>

table (Table)

Tables in Lua are created using "constructor expressions." The simplest constructor is {}, which creates an empty table. You can also add data directly to initialize a table:

Example

-- Create an empty table
local tbl1 = {}

-- Directly initialize a table
local tbl2 = {"apple", "pear", "orange", "grape"}

Tables in Lua are "associative arrays," where indices can be numbers or strings.

Example

-- table_test.lua script file
a = {}
a["key"] = "value"
key = 10
a[key] = 22
a[key] = a[key] + 11
for k, v in pairs(a) do
    print(k .. " : " .. v)
end

The script results in:

$ lua table_test.lua 
key : value
10 : 33

Unlike arrays in other languages that start with index 0, Lua tables default to starting with index 1.

Example

-- table_test2.lua script file
local tbl = {"apple", "pear", "orange", "grape"}
for key, val in pairs(tbl) do
    print("Key", key)
end

The script results in:

$ lua table_test2.lua 
Key    1
Key    2
Key    3
Key    4

Tables do not have a fixed length; they automatically grow when new data is added. Uninitialized table elements are nil.

Example

-- table_test3.lua script file
a3 = {}
for i = 1, 10 do
    a3[i] = i
end
a3["key"] = "val"
print(a3["key"])
print(a3["none"])

The script results in:

$ lua table_test3.lua 
val
nil

function (Function)

In Lua, functions are considered "first-class values." Functions can be stored in variables:

Example

-- function_test.lua script file
function factorial1(n)
    if n == 0 then
        return 1
    else
        return n * factorial1(n - 1)
    end
end
print(factorial1(5))
factorial2 = factorial1
print(factorial2(5))

The script results in:

$ lua function_test.lua 
120
120

Functions can be passed as parameters in the form of anonymous functions:

Example

-- function_test2.lua script file
function testFun(tab,fun)
        for k ,v in pairs(tab) do
                print(fun(k,v));
        end
end

tab={key1="val1",key2="val2"};
testFun(tab,
function(key,val)--anonymous function
        return key.."="..val;
end
);

The script results in:

$ lua function_test2.lua 
key1 = val1
key2 = val2

thread (Thread)

In Lua, the primary thread is the coroutine. It is similar to a thread, with its own stack, local variables, and instruction pointer, but it can share global variables and most other things with other coroutines.

The difference between threads and coroutines: threads can run multiple at once, while coroutines can only run one at a time. A coroutine only pauses when it is suspended.


userdata (Userdata)

Userdata is a user-defined data type used to represent types created by applications or C/C++ libraries. It allows storing arbitrary C/C++ data types (usually structs and pointers) in Lua variables.

❮ Lua Basic Syntax Lua Environment ❯