Next: 4 The Language Up: Reference Manual of the Previous: 2 Environment and Chunks

3 Types

Lua is a dynamically typed language. Variables do not have types; only values do. All values carry their own type. Therefore, there are no type definitions in the language.

There are seven basic types in Lua: nil, number, string, function, CFunction, userdata, and table. Nil is the type of the value nil, whose main property is to be different from any other value. Number represents real (floating point) numbers, while string has the usual meaning.

Functions are considered first-class values in Lua. This means that functions can be stored in variables, passed as arguments to other functions and returned as results. When a function is defined in Lua, its body is compiled and stored in a given variable. Lua can call (and manipulate) functions written in Lua and functions written in C; the latter have type CFunction.

The type userdata is provided to allow arbitrary C pointers to be stored in Lua variables. It corresponds to void* and has no pre-defined operations in Lua, besides assignment and equality test. However, by using fallbacks, the programmer may define operations for userdata values; see Section 4.7.

The type table implements associative arrays, that is, arrays which can be indexed not only with numbers, but with any value (except nil ). Therefore, this type may be used not only to represent ordinary arrays, but also symbol tables, sets, records, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing as syntactic sugar for a["name"] . Tables may also carry methods. Because functions are first class values, table fields may contain functions. The form t:f(x) is syntactic sugar for t.f(t,x) , which calls the method f from the table t passing itself as the first parameter.

It is important to notice that tables are objects, and not values. Variables cannot contain tables, only references to them. Assignment, parameter passing and returns always manipulate references to tables, and do not imply any kind of copy. Moreover, tables must be explicitly created before used; see Section 4.5.7.

Next: 4 The Language Up: Reference Manual of the Previous: 2 Environment and Chunks