Luan

Luan Reference Manual

Original copyright © 2015 Lua.org, PUC-Rio. Freely available under the terms of the Lua license. Modified for Luan.


Contents

Introduction
Basic Concepts
The Language
Standard Libraries

Introduction

Luan is a high level programming language based on Lua. A great strength of Lua is its simplicity and Luan takes this even further, being even simpler than Lua. The goal is to provide a simple programming language for the casual programmer with as few concepts as possible so that one can quickly learn the language and then easily understand any code written in Luan.

Luan is implemented in Java and is tightly coupled with Java. So it makes a great scripting language for Java programmers.

Unlike Lua which is meant to be embedded, Luan is meant to be a full scripting language. This done not by adding feature to Luan, but rather by providing a complete set of libraries.

Basic Concepts

This section describes the basic concepts of the language.

Values and Types

Luan is a dynamically typed language. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type.

All values in Luan are first-class values. This means that all values can be stored in variables, passed as arguments to other functions, and returned as results.

There are eight basic types in Luan: nil, boolean, number, string, binary, function, java, and table. Nil is the type of the value nil, whose main property is to be different from any other value; it usually represents the absence of a useful value. Nil is implemented as the Java value null. Boolean is the type of the values false and true. Boolean is implemented as the Java class Boolean. Number represents both integer numbers and real (floating-point) numbers. Number is implemented as the Java class Number. Any Java subclass of Number is allowed and this is invisible to the Luan user. Operations on numbers follow the same rules of the underlying Java implementation. String is implemented as the Java class String. Binary is implemented as the Java type byte[].

Luan can call (and manipulate) functions written in Luan and functions written in Java (see Function Calls). Both are represented by the type function.

The type java is provided to allow arbitrary Java objects to be stored in Luan variables. A java value is a Java object that isn't one of the standard Luan types. Java values have no predefined operations in Luan, except assignment and identity test. Java values are useful when Java access is enabled in Luan

The type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any Luan value except nil. Tables can be heterogeneous; that is, they can contain values of all types (except nil). Any key with value nil is not considered part of the table. Conversely, any key that is not part of a table has an associated value nil.

Tables are the sole data-structuring mechanism in Luan; they can be used to represent ordinary arrays, sequences, symbol tables, sets, records, graphs, trees, etc. To represent records, Luan uses the field name as an index. The language supports this representation by providing a.name as syntactic sugar for a["name"]. There are several convenient ways to create tables in Luan (see Table Constructors).

We use the term sequence to denote a table where the set of all positive numeric keys is equal to {1..n} for some non-negative integer n, which is called the length of the sequence (see The Length Operator).

Like indices, the values of table fields can be of any type. In particular, because functions are first-class values, table fields can contain functions. Thus tables can also carry methods (see Function Definitions).

The indexing of tables follows the definition of raw equality in the language. The expressions a[i] and a[j] denote the same table element if and only if i and j are raw equal (that is, equal without metamethods). In particular, floats with integral values are equal to their respective integers (e.g., 1.0 == 1).

Luan values are objects: variables do not actually contain values, only references to them. Assignment, parameter passing, and function returns always manipulate references to values; these operations do not imply any kind of copy.

The library function Luan.type returns a string describing the type of a given value.

Environments

The environment of a chunk starts with only two local variables: require and java. These are functions are used to load and access libraries and other modules. All other variables must be added to the environment using local declarations.

As will be discussed in Variables and Assignment, any reference to a free name (that is, a name not bound to any declaration) var can be syntactically translated to _ENV.var if _ENV is defined.

Error Handling

Luan code can explicitly generate an error by calling the error function. If you need to catch errors in Luan, you can use pcall or try to call a given function in protected mode.

Whenever there is an error, an error table is propagated with information about the error. See Luan.new_error.

Metatables and Metamethods

Every table in Luan can have a metatable. This metatable is an ordinary Luan table that defines the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable. For instance, when a table is the operand of an addition, Luan checks for a function in the field "__add" of the table's metatable. If it finds one, Luan calls this function to perform the addition.

The keys in a metatable are derived from the event names; the corresponding values are called metamethods. In the previous example, the event is "add" and the metamethod is the function that performs the addition.

You can query the metatable of any table using the get_metatable function.

You can replace the metatable of tables using the set_metatable function.

A metatable controls how a table behaves in arithmetic operations, bitwise operations, order comparisons, concatenation, length operation, calls, and indexing.

A detailed list of events controlled by metatables is given next. Each operation is identified by its corresponding event name. The key for each event is a string with its name prefixed by two underscores, '__'; for instance, the key for operation "add" is the string "__add". Note that queries for metamethods are always raw; the access to a metamethod does not invoke other metamethods. You can emulate how Luan queries a metamethod for an object obj with the following code:

     raw_get(get_metatable(obj) or {}, "__" .. event_name)

Here are the events:

Garbage Collection

Luan uses Java's garbage collection.

The Language

This section describes the lexis, the syntax, and the semantics of Luan. In other words, this section describes which tokens are valid, how they can be combined, and what their combinations mean.

Language constructs will be explained using the usual extended BNF notation, in which {a} means 0 or more a's, and [a] means an optional a. Non-terminals are shown like non-terminal, keywords are shown like kword, and other terminal symbols are shown like ‘=’. The complete syntax of Luan can be found in §9 at the end of this manual.

Lexical Conventions

Luan ignores spaces and comments between lexical elements (tokens), except as delimiters between names and keywords. Luan considers the end of a line to be the end of a statement. This catches errors and encourages readability. If you want to continue a statement on another line, you can use a backslash followed by a newline which will be treated as white space.

Names (also called identifiers) in Luan can be any string of letters, digits, and underscores, not beginning with a digit. Identifiers are used to name variables, table fields, and labels.

The following keywords are reserved and cannot be used as names:

     and       break     do        else      elseif    end
     end_do    end_for   end_function        end_if    end_while
     false     for       function  goto      if        in
     local     nil       not       or        repeat    return
     then      true      until     while

Luan is a case-sensitive language: and is a reserved word, but And and AND are two different, valid names.

The following strings denote other tokens:

     +     -     *     /     %     ^     #
     &     ~     |     <<    >>    //
     ==    ~=    <=    >=    <     >     =
     (     )     {     }     [     ]     ::
     ;     :     ,     .     ..    ...

Literal strings can be delimited by matching single or double quotes, and can contain the following C-like escape sequences: '\a' (bell), '\b' (backspace), '\f' (form feed), '\n' (newline), '\r' (carriage return), '\t' (horizontal tab), '\v' (vertical tab), '\\' (backslash), '\"' (quotation mark [double quote]), and '\'' (apostrophe [single quote]). A backslash followed by a real newline results in a newline in the string. The escape sequence '\z' skips the following span of white-space characters, including line breaks; it is particularly useful to break and indent a long literal string into multiple lines without adding the newlines and spaces into the string contents.

Luan can specify any character in a literal string by its numerical value. This can be done with the escape sequence \xXX, where XX is a sequence of exactly two hexadecimal digits, or with the escape sequence \uXXXX, where XXXX is a sequence of exactly four hexadecimal digits, or with the escape sequence \ddd, where ddd is a sequence of up to three decimal digits. (Note that if a decimal escape sequence is to be followed by a digit, it must be expressed using exactly three digits.)

Literal strings can also be defined using a long format enclosed by long brackets. We define an opening long bracket of level n as an opening square bracket followed by n equal signs followed by another opening square bracket. So, an opening long bracket of level 0 is written as [[, an opening long bracket of level 1 is written as [=[, and so on. A closing long bracket is defined similarly; for instance, a closing long bracket of level 4 is written as ]====]. A long literal starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. It can contain any text except a closing bracket of the same level. Literals in this bracketed form can run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. Any kind of end-of-line sequence (carriage return, newline, carriage return followed by newline, or newline followed by carriage return) is converted to a simple newline.

Any character in a literal string not explicitly affected by the previous rules represents itself. However, Luan opens files for parsing in text mode, and the system file functions may have problems with some control characters. So, it is safer to represent non-text data as a quoted literal with explicit escape sequences for non-text characters.

For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string. As an example the five literal strings below denote the same string:

     a = 'alo\n123"'
     a = "alo\n123\""
     a = '\97lo\10\04923"'
     a = [[alo
     123"]]
     a = [==[
     alo
     123"]==]

A numerical constant (or numeral) can be written with an optional fractional part and an optional decimal exponent, marked by a letter 'e' or 'E'. Luan also accepts hexadecimal constants, which start with 0x or 0X. Hexadecimal constants also accept an optional fractional part plus an optional binary exponent, marked by a letter 'p' or 'P'. A numeric constant with a fractional dot or an exponent denotes a float; otherwise it denotes an integer. Examples of valid integer constants are

     3   345   0xff   0xBEBADA

Examples of valid float constants are

     3.0     3.1416     314.16e-2     0.31416E1     34e1
     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1

A comment starts with a double hyphen (--) anywhere outside a string. If the text immediately after -- is not an opening long bracket, the comment is a short comment, which runs until the end of the line. Otherwise, it is a long comment, which runs until the corresponding closing long bracket. Long comments are frequently used to disable code temporarily.

Variables

Variables are places that store values. There are three kinds of variables in Luan: global variables, local variables, and table fields.

A single name can denote a global variable or a local variable (or a function's formal parameter, which is a particular kind of local variable):

	var ::= Name

Name denotes identifiers, as defined in Lexical Conventions.

Local variables are lexically scoped: local variables can be freely accessed by functions defined inside their scope (see Visibility Rules).

Before the first assignment to a variable, its value is nil.

Square brackets are used to index a table:

	var ::= prefixexp ‘[’ exp ‘]

The meaning of accesses to table fields can be changed via metatables. An access to an indexed variable t[i] is equivalent to a call gettable_event(t,i). (See Metatables and Metamethods for a complete description of the gettable_event function. This function is not defined or callable in Luan. We use it here only for explanatory purposes.)

The syntax var.Name is just syntactic sugar for var["Name"]:

	var ::= prefixexp ‘.’ Name

Global variables are not available by default. To enable global variable, you must define _ENV as a local variable whose value is a table. If _ENV is not defined, then an unrecognized variable name will produce a compile error. If _ENV is defined then an access to an unrecognized variable name will be consider a global variable. So then an acces to global variable x is equivalent to _ENV.x. Due to the way that chunks are compiled, _ENV is never a global name (see Environments).

Statements

Luan supports an almost conventional set of statements, similar to those in Pascal or C. This set includes assignments, control structures, function calls, and variable declarations.

Blocks

A block is a list of statements, which are executed sequentially:

	block ::= {stat}

Luan has empty statements that allow you to separate statements with semicolons, start a block with a semicolon or write two semicolons in sequence:

	stat ::= ‘;

A block can be explicitly delimited to produce a single statement:

	stat ::= do block end_do
	end_do ::= end_do | end

Explicit blocks are useful to control the scope of variable declarations. Explicit blocks are also sometimes used to add a return statement in the middle of another block (see Control Structures).

Chunks

The unit of compilation of Luan is called a chunk. Syntactically, a chunk is simply a block:

	chunk ::= block

Luan handles a chunk as the body of an anonymous function with a variable number of arguments (see Function Definitions). As such, chunks can define local variables, receive arguments, and return values.

A chunk can be stored in a file or in a string inside the host program. To execute a chunk, Luan first loads it, compiling the chunk's code, and then Luan executes the compiled code.

Assignment

Luan allows multiple assignments. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. The elements in both lists are separated by commas:

	stat ::= varlist ‘=’ explist
	varlist ::= var {‘,’ var}
	explist ::= exp {‘,’ exp}

Expressions are discussed in Expressions.

Before the assignment, the list of values is adjusted to the length of the list of variables. If there are more values than needed, the excess values are thrown away. If there are fewer values than needed, the list is extended with as many nil's as needed. If the list of expressions ends with a function call, then all values returned by that call enter the list of values, before the adjustment (except when the call is enclosed in parentheses; see Expressions).

The assignment statement first evaluates all its expressions and only then the assignments are performed. Thus the code

     i = 3
     i, a[i] = i+1, 20

sets a[3] to 20, without affecting a[4] because the i in a[i] is evaluated (to 3) before it is assigned 4. Similarly, the line

     x, y = y, x

exchanges the values of x and y, and

     x, y, z = y, z, x

cyclically permutes the values of x, y, and z.

The meaning of assignments to global variables and table fields can be changed via metatables. An assignment to an indexed variable t[i] = val is equivalent to settable_event(t,i,val). (See Metatables and Metamethods for a complete description of the settable_event function. This function is not defined or callable in Luan. We use it here only for explanatory purposes.)

An assignment to a global name x = val is equivalent to the assignment _ENV.x = val (see Environments). Global names are only available when _ENV is defined.

Control Structures

The control structures if, while, and repeat have the usual meaning and familiar syntax:

	stat ::= while exp do block end_while
	stat ::= repeat block until exp
	stat ::= if exp then block {elseif exp then block} [else block] end_if
	end_while ::= end_while | end
	end_if ::= end_if | end

Luan also has a for statement (see For Statement).

The condition expression of a control structure must be a boolean. Any other value type will produce an error. This helps catch errors and makes code more readable.

In the repeatuntil loop, the inner block does not end at the until keyword, but only after the condition. So, the condition can refer to local variables declared inside the loop block.

The break statement terminates the execution of a while, repeat, or for loop, skipping to the next statement after the loop:

	stat ::= break

A break ends the innermost enclosing loop.

The return statement is used to return values from a function or a chunk (which is an anonymous function). Functions can return more than one value, so the syntax for the return statement is

	stat ::= return [explist] [‘;’]

For Statement

The for statement works over functions, called iterators. On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. The for loop has the following syntax:

	stat ::= for namelist in exp do block end_for
	namelist ::= Name {‘,’ Name}
	end_for ::= end_for | end

A for statement like

     for var_1, ···, var_n in exp do block end

is equivalent to the code:

     do
       local f = exp
       while true do
         local var_1, ···, var_n = f()
         if var_1 == nil then break end
         block
       end
     end

Note the following:

Function Calls as Statements

To allow possible side-effects, function calls can be executed as statements:

	stat ::= functioncall

In this case, all returned values are thrown away. Function calls are explained in Function Calls.

Local Declarations

Local variables can be declared anywhere inside a block. The declaration can include an initial assignment:

	stat ::= local namelist [‘=’ explist]

If present, an initial assignment has the same semantics of a multiple assignment (see Assignment). Otherwise, all variables are initialized with nil.

A chunk is also a block (see Chunks), and so local variables can be declared in a chunk outside any explicit block.

The visibility rules for local variables are explained in Visibility Rules.

Template Statements

Template statements are based on template exressions and provide the full equivalent of JSP but in a general way. Template statements write the equivalent template exression to standard output. For example:

	local name = "Bob"
	%>
	Hello <%= name %>!
	Bye <%= name %>.
	<%

is equivalent to the code:

	local name = "Bob"
	require("luan:Io.luan").stdout.write( %>
	Hello <%= name %>!
	Bye <%= name %>.
	<% )

Expressions

The basic expressions in Luan are the following:

	exp ::= prefixexp
	exp ::= nil | false | true
	exp ::= Numeral
	exp ::= LiteralString
	exp ::= functiondef
	exp ::= tableconstructor
	exp ::= ‘...’
	exp ::= exp binop exp
	exp ::= unop exp
	prefixexp ::= var | functioncall | ‘(’ exp ‘)

Numerals and literal strings are explained in Lexical Conventions; variables are explained in Variables; function definitions are explained in Function Definitions; function calls are explained in Function Calls; table constructors are explained in Table Constructors. Vararg expressions, denoted by three dots ('...'), can only be used when directly inside a vararg function; they are explained in Function Definitions.

Binary operators comprise arithmetic operators (see Arithmetic Operators), relational operators (see Relational Operators), logical operators (see Logical Operators), and the concatenation operator (see Concatenation). Unary operators comprise the unary minus (see Arithmetic Operators), the unary logical not (see Logical Operators), and the unary length operator (see The Length Operator).

Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see Function Calls as Statements), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the expression is enclosed in parentheses). In all other contexts, Luan adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values.

Here are some examples:

     f()                -- adjusted to 0 results
     g(f(), x)          -- f() is adjusted to 1 result
     g(x, f())          -- g gets x plus all results from f()
     a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
     a,b = ...          -- a gets the first vararg parameter, b gets
                        -- the second (both a and b can get nil if there
                        -- is no corresponding vararg parameter)
     
     a,b,c = x, f()     -- f() is adjusted to 2 results
     a,b,c = f()        -- f() is adjusted to 3 results
     return f()         -- returns all results from f()
     return ...         -- returns all received vararg parameters
     return x,y,f()     -- returns x, y, and all results from f()
     {f()}              -- creates a list with all results from f()
     {...}              -- creates a list with all vararg parameters
     {f(), nil}         -- f() is adjusted to 1 result

Any expression enclosed in parentheses always results in only one value. Thus, (f(x,y,z)) is always a single value, even if f returns several values. (The value of (f(x,y,z)) is the first value returned by f or nil if f does not return any values.)

Arithmetic Operators

Luan supports the following arithmetic operators:

Addition, subtraction, multiplication, division, and unary minus are the same as these operators in Java. Exponentiation uses Java's Math.pow function.

Modulo is defined as the remainder of a division that rounds the quotient towards minus infinite (floor division). (The Java modulo operator is not used.)

Coercions and Conversions

Luan generally avoids automatic conversions. String concatenation automatically converts all of its arguments to strings.

Luan provides library functions for explicit type conversions.

Relational Operators

Luan supports the following relational operators:

These operators always result in false or true.

Equality (==) first compares the type of its operands. If the types are different, then the result is false. Otherwise, the values of the operands are compared. Strings, numbers, and binary values are compared in the obvious way (by value).

Tables are compared by reference: two objects are considered equal only if they are the same object. Every time you create a new table, it is different from any previously existing table. Closures are also compared by reference.

You can change the way that Luan compares tables by using the "eq" metamethod (see Metatables and Metamethods).

Java values are compared for equality with the Java equals method.

Equality comparisons do not convert strings to numbers or vice versa. Thus, "0"==0 evaluates to false, and t[0] and t["0"] denote different entries in a table.

The operator ~= is exactly the negation of equality (==).

The order operators work as follows. If both arguments are numbers, then they are compared following the usual rule for binary operations. Otherwise, if both arguments are strings, then their values are compared according to the current locale. Otherwise, Luan tries to call the "lt" or the "le" metamethod (see Metatables and Metamethods). A comparison a > b is translated to b < a and a >= b is translated to b <= a.

Logical Operators

The logical operators in Luan are and, or, and not. The and and or operators consider both false and nil as false and anything else as true. Like the control structures (see Control Structures), the not operator requires a boolean value.

The negation operator not always returns false or true. The conjunction operator and returns its first argument if this value is false or nil; otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different from nil and false; otherwise, or returns its second argument. Both and and or use short-circuit evaluation; that is, the second operand is evaluated only if necessary. Here are some examples:

     10 or 20            --> 10
     10 or error()       --> 10
     nil or "a"          --> "a"
     nil and 10          --> nil
     false and error()   --> false
     false and nil       --> false
     false or nil        --> nil
     10 and 20           --> 20

(In this manual, --> indicates the result of the preceding expression.)

Concatenation

The string concatenation operator in Luan is denoted by two dots ('..'). All operands are converted to strings.

The Length Operator

The length operator is denoted by the unary prefix operator #. The length of a string is its number of characters. The length of a binary is its number of bytes.

A program can modify the behavior of the length operator for any table through the __len metamethod (see Metatables and Metamethods).

Unless a __len metamethod is given, the length of a table t is defined as the number of elements in sequence, that is, the size of the set of its positive numeric keys is equal to {1..n} for some non-negative integer n. In that case, n is its length. Note that a table like

     {10, 20, nil, 40}

has a length of 2, because that is the last key in sequence.

Precedence

Operator precedence in Luan follows the table below, from lower to higher priority:

     or
     and
     <     >     <=    >=    ~=    ==
     ..
     +     -
     *     /     %
     unary operators (not   #     -)
     ^

As usual, you can use parentheses to change the precedences of an expression. The concatenation ('..') and exponentiation ('^') operators are right associative. All other binary operators are left associative.

Table Constructors

Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is

	tableconstructor ::= ‘{’ fieldlist ‘}’
	fieldlist ::= [field] {fieldsep [field]}
	field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
	fieldsep ::= ‘,’ | ‘;’ | end_of_line

Each field of the form [exp1] = exp2 adds to the new table an entry with key exp1 and value exp2. A field of the form name = exp is equivalent to ["name"] = exp. Finally, fields of the form exp are equivalent to [i] = exp, where i are consecutive integers starting with 1. Fields in the other formats do not affect this counting. For example,

     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }

is equivalent to

     do
       local t = {}
       t[f(1)] = g
       t[1] = "x"         -- 1st exp
       t[2] = "y"         -- 2nd exp
       t.x = 1            -- t["x"] = 1
       t[3] = f(x)        -- 3rd exp
       t[30] = 23
       t[4] = 45          -- 4th exp
       a = t
     end

The order of the assignments in a constructor is undefined. (This order would be relevant only when there are repeated keys.)

If the last field in the list has the form exp and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see Function Calls).

The field list can have an optional trailing separator, as a convenience for machine-generated code.

Function Calls

A function call in Luan has the following syntax:

	functioncall ::= prefixexp args

In a function call, first prefixexp and args are evaluated. The value of prefixexp must have type function. This function is called with the given arguments.

Arguments have the following syntax:

	args ::= ‘(’ [explist] ‘)’
	args ::= tableconstructor
	args ::= LiteralString

All argument expressions are evaluated before the call. A call of the form f{fields} is syntactic sugar for f({fields}); that is, the argument list is a single new table. A call of the form f'string' (or f"string" or f[[string]]) is syntactic sugar for f('string'); that is, the argument list is a single literal string.

Function Definitions

The syntax for function definition is

	functiondef ::= function funcbody
	funcbody ::= ‘(’ [parlist] ‘)’ block end_function
	end_function ::= end_function | end

The following syntactic sugar simplifies function definitions:

	stat ::= function funcname funcbody
	stat ::= local function Name funcbody
	funcname ::= Name {‘.’ Name} [‘:’ Name]

The statement

     function f () body end

translates to

     f = function () body end

The statement

     function t.a.b.c.f () body end

translates to

     t.a.b.c.f = function () body end

The statement

     local function f () body end

translates to

     local f; f = function () body end

not to

     local f = function () body end

(This only makes a difference when the body of the function contains references to f.)

A function definition is an executable expression, whose value has type function. When Luan precompiles a chunk, all its function bodies are precompiled too. Then, whenever Luan executes the function definition, the function is instantiated (or closed). This function instance (or closure) is the final value of the expression.

Parameters act as local variables that are initialized with the argument values:

	parlist ::= namelist [‘,’ ‘...’] | ‘...

When a function is called, the list of arguments is adjusted to the length of the list of parameters if the list is too short, unless the function is a vararg function, which is indicated by three dots ('...') at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a vararg expression, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses).

As an example, consider the following definitions:

     function f(a, b) end
     function g(a, b, ...) end
     function r() return 1,2,3 end

Then, we have the following mapping from arguments to parameters and to the vararg expression:

     CALL            PARAMETERS
     
     f(3)             a=3, b=nil
     f(3, 4)          a=3, b=4
     f(3, 4, 5)       runtime error
     f(r(), 10)       runtime error
     f(r())           runtime error
     
     g(3)             a=3, b=nil, ... -->  (nothing)
     g(3, 4)          a=3, b=4,   ... -->  (nothing)
     g(3, 4, 5, 8)    a=3, b=4,   ... -->  5  8
     g(5, r())        a=5, b=1,   ... -->  2  3

Results are returned using the return statement (see Control Structures). If control reaches the end of a function without encountering a return statement, then the function returns with no results.

Template Expressions

Luan template expression are based on JSP. Template expressions return multiple values. Here is an example:

	local name = "Bob"
	write( %>Hello <%= name %>!<% )

This is equivalent to the code:

	local name = "Bob"
	write( "Hello ", name, "!" )

The strings in template expressions may be multiple lines.

Visibility Rules

Luan is a lexically scoped language. The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration. Consider the following example:

     x = 10                -- global variable
     do                    -- new block
       local x = x         -- new 'x', with value 10
       print(x)            --> 10
       x = x+1
       do                  -- another block
         local x = x+1     -- another 'x'
         print(x)          --> 12
       end
       print(x)            --> 11
     end
     print(x)              --> 10  (the global one)

Notice that, in a declaration like local x = x, the new x being declared is not in scope yet, and so the second x refers to the outside variable.

Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an upvalue, or external local variable, inside the inner function.

Notice that each execution of a local statement defines new local variables. Consider the following example:

     a = {}
     local x = 20
     for i=1,10 do
       local y = 0
       a[i] = function () y=y+1; return x+y end
     end

The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different y variable, while all of them share the same x.

Standard Libraries

The standard Luan libraries provide useful functions that are implemented both in Java and in Luan itself. How each function is implemented shouldn't matter to the user. Some of these functions provide essential services to the language (e.g., type and get_metatable); others provide access to "outside" services (e.g., I/O).

Default Environment

These are provided by default as local variables for any Luan code as described in Environments.

java ()

This function enables Java in the current chunk if that chunk has permission to use Java. If the chunk doesn't have permission to use Java, then an error is thrown.

require (mod_uri)

Example use:

	local Table = require "luan:Table.luan"

Could be defined as:

	local function require(mod_name)
		return Package.load(mod_name) or Luan.error("module '"..mod_name.."' not found")
	end

Basic Functions

Include this library by:

	local Luan = require "luan:Luan.luan"

The basic library provides basic functions to Luan that don't depend on other libaries.

Luan.do_file ([uri])

Could be defined as:

	function Luan.do_file(uri)
		return Luan.load_file(uri)()
	end

Luan.error (message)

Throws an error containing the message.

Could be defined as:

	function Luan.error(message)
		Luan.new_error(message).throw()
	end

Luan.eval (text [, source_name])

Evaluates text as a Luan expression.

Could be defined as:

	function Luan.eval(text,source_name)
		return Luan.load( "return "..text, source_name or "eval" )()
	end

Luan.get_metatable (table)

If table does not have a metatable, returns nil. Otherwise, if the table's metatable has a "__metatable" field, returns the associated value. Otherwise, returns the metatable of the given table.

Luan.ipairs (t)

Returns an iterator function so that the construction

	for i,v in ipairs(t) do body end

will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value.

Could be defined as:

	function Luan.ipairs(t)
		local i = 0
		return function()
			if i < #t then
				i = i + 1
				return i, t[i]
			end
		end
	end

Luan.load (text, source_name [, env])

Loads a chunk.

The text is compiled. If there are no syntactic errors, returns the compiled chunk as a function; otherwise, throws an error.

The source_name parameter is a string saying where the text came from. It is used to produce error messages.

If the env parameter is supplied, it becomes the _ENV of the chunk.

Luan.load_file ([file_uri])

Similar to load, but gets the chunk from file file_uri or from the standard input, if no file uri is given.

Could be defined as:

	function Luan.load_file(file_uri)
		file_uri = file_uri or "stdin:"
		local f = Io.uri(file_uri)
		f.exists() or Luan.error("file '"..file_uri.."' not found")
		return Luan.load( f.read_text(), file_uri )
	end

Luan.new_error (message)

Creates a new error table containing the message assigned to "message". The error table also contains a throw function which throws the error. The table also contains a list of stack trace elements where each stack trace element is a table containing "source", "line", and possible "call_to". The table also has a metatable containing "__to_string" to render the error.

To print the current stack trace, you could do:

	Io.print( Luan.new_error "stack" )

Luan.pairs (t)

If t has a metamethod __pairs, calls it with t as argument and returns the result from the call.

Otherwise, returns a function so that the construction

	for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

Luan.pcall (f [, arg1, ···])

Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error.


print (···)

Receives any number of arguments and prints their values to stdout, using the tostring function to convert each argument to a string. print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use string.format and io.write.

Luan.range (start, stop [, step])

Based on the Python range() function, this lets one iterate through a sequence of numbers.

Example use:

	for i in range(1,10) do
		Io.print("count up:",i)
	end
	for i in range(10,0,-1) do
		Io.print("count down:",i)
	end

Could be defined as:

	function Luan.range(start, stop, step)
		step = step or 1
		step == 0 and Luan.error "bad argument #3 (step may not be zero)"
		local i = start
		return function()
			if step > 0 and i <= stop or step < 0 and i >= stop then
				local rtn = i
				i = i + step
				return rtn
			end
		end
	end

Luan.raw_equal (v1, v2)

Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.

Luan.raw_get (table, index)

Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.

Luan.raw_len (v)

Returns the length of the object v, which must be a table or a string, without invoking any metamethod. Returns an integer.

Luan.raw_set (table, index, value)

Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value.

Luan.set_metatable (table, metatable)

Sets the metatable for the given table. If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" field, raises an error.

Luan.stringify (v [,strict])

Receives a value of any type and converts it to a string that is a Luan expression. strict is a boolean. If strict is true then invalid types throw an error. If strict is false then invalid types are represented but the resulting expression is invalid. strict defaults to true.

Luan.to_string (v)

Receives a value of any type and converts it to a string in a human-readable format.

If the metatable of v has a "__to_string" field, then to_string calls the corresponding value with v as argument, and uses the result of the call as its result.

Luan.try (t, ···)

Implements try-catch as found in other languages where each block is in table t. t[1] is the "try" block. The t.catch and t.finally blocks are optional. Any extra arguments are passed to the "try" function. Returns the result of the "try" block or the "catch" block.

Example use:

try {
	function()
		a_dangerous_fn()
	end
	catch = function(e)
		-- handle error
	end
	finally = function()
		-- clean up
	end
}

Could be defined as:

	function Luan.try(t)
		local r = { Luan.pcall(t[1]) }
		if r[1] then
			Table.remove(r,1)
		elseif t.catch ~= nil then
			r = { t.catch(r[2]) }
		else
			t.finally and t.finally()
			r[2].throw()
		end
		t.finally and t.finally()
		return Table.unpack(r)
	end

Luan.type (v)

Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "binary", "boolean", "table", "function", and "java".

Luan.values (···)

Returns a function so that the construction

	for v in Luan.values(···) do body end

will iterate over all values of ···.

Luan.VERSION

A global variable (not a function) that holds a string containing the current interpreter version. The current value of this variable is "0.22".

Modules

Include this library by:

	local Package = require "luan:Package.luan"

The package library provides basic facilities for loading modules in Luan.

Package.load (mod_uri)

Loads the given module. The function starts by looking into the Package.loaded table to determine whether mod_uri is already loaded. If it is, then Package.load returns the value stored at Package.loaded[mod_uri]. Otherwise, it tries to load a new value for the module.

To load a new value, Package.load first checks if mod_uri starts with "java:". If yes, then this is a Java class which is loaded by special Java code.

Otherwise Package.load tries to read the text of the file referred to by mod_uri. If the file doesn't exist, then Package.load returns false. If the file exists, then its content is compiled into a chunk by calling Luan.load. This chunk is run passing in mod_uri as an argument. The value returned by the chunk must not be nil and is loaded.

If a new value for the module successful loaded, then it is stored in Package.loaded[mod_uri]. The value is returned.

Package.loaded

A table used by Package.load to control which modules are already loaded. When you load a module mod_uri and Package.loaded[mod_uri] is not nil, Package.load simply returns the value stored there.

This variable is only a reference to the real table; assignments to this variable do not change the table used by Package.load.

String Manipulation

Include this library by:

	local String = require "luan:String.luan"

This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Luan, the first character is at position 1 (not at 0, as in Java). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.

String.char (···)

Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.

String.concat (···)

Concatenates the to_string value of all arguments.

String.encode (s)

Encodes argument s into a string that can be placed in quotes so as to return the original value of the string.

String.find (s, pattern [, init [, plain]])

Looks for the first match of pattern (see Pattern) in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered magic. Note that if plain is given, then init must be given as well.

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

String.format (formatstring, ···)

Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the Java function String.format because Luan calls this internally.

Note that Java's String.format is too stupid to convert between ints and floats, so you must provide the right kind of number.

String.gmatch (s, pattern)

Returns an iterator function that, each time it is called, returns the next captures from pattern (see Pattern) over the string s. If pattern specifies no captures, then the whole match is produced in each call.

As an example, the following loop will iterate over all the words from string s, printing one per line:

	local s = "hello world from Lua"
	for w in String.gmatch(s, [[\w+]]) do
		print(w)
	end

The next example collects all pairs key=value from the given string into a table:

	local t = {}
	local s = "from=world, to=Lua"
	for k, v in String.gmatch(s, [[(\w+)=(\w+)]]) do
		t[k] = v
	end

For this function, a caret '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.

String.gsub (s, pattern, repl [, n])

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern (see Pattern) have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred. The name gsub comes from Global SUBstitution.

If repl is a string, then its value is used for replacement. The character \ works as an escape character. Any sequence in repl of the form $d, with d between 1 and 9, stands for the value of the d-th captured substring. The sequence $0 stands for the whole match.

If repl is a table, then the table is queried for every match, using the first capture as the key.

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order.

In any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.

If the value returned by the table query or by the function call is not nil, then it is used as the replacement string; otherwise, if it is nil, then there is no replacement (that is, the original match is kept in the string).

Here are some examples:

     x = String.gsub("hello world", [[(\w+)]], "$1 $1")
     --> x="hello hello world world"
     
     x = String.gsub("hello world", [[\w+]], "$0 $0", 1)
     --> x="hello hello world"
     
     x = String.gsub("hello world from Luan", [[(\w+)\s*(\w+)]], "$2 $1")
     --> x="world hello Luan from"
          
     x = String.gsub("4+5 = $return 4+5$", [[\$(.*?)\$]], function (s)
           return load(s)()
         end)
     --> x="4+5 = 9"
     
     local t = {name="lua", version="5.3"}
     x = String.gsub("$name-$version.tar.gz", [[\$(\w+)]], t)
     --> x="lua-5.3.tar.gz"

String.literal (s)

Returns a string which matches the literal string s in a regular expression. This function is simply the Java method Pattern.quote.

String.lower (s)

Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged.

String.match (s, pattern [, init])

Looks for the first match of pattern (see Pattern) in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative.

String.matches (s, pattern)

Returns a boolean indicating whether the pattern can be found in string s. This function is equivalent to

     return String.match(s,pattern) ~= nil

String.rep (s, n [, sep])

Returns a string that is the concatenation of n copies of the string s separated by the string sep. The default value for sep is the empty string (that is, no separator). Returns the empty string if n is not positive.

String.reverse (s)

Returns a string that is the string s reversed.

String.split (s, pattern [, limit])

Splits s using regex pattern and returns the results. If limit is positive, then only returns at most that many results. If limit is zero, then remove trailing empty results.

String.sub (s, i [, j])

Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

If, after the translation of negative indices, i is less than 1, it is corrected to 1. If j is greater than the string length, it is corrected to that length. If, after these corrections, i is greater than j, the function returns the empty string.

String.to_binary (s)

Converts a string to a binary by calling the Java method String.getBytes.

String.to_number (s [, base])

When called with no base, to_number tries to convert its argument to a number. If the argument is a string convertible to a number, then to_number returns this number; otherwise, it returns nil. The conversion of strings can result in integers or floats.

When called with base, then s must be a string to be interpreted as an integer numeral in that base. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. If the string s is not a valid numeral in the given base, the function returns nil.

String.trim (s)

Removes the leading and trailing whitespace by calling the Java method String.trim.

String.unicode (s [, i [, j]])

Returns the internal numerical codes of the characters s[i], s[i+1], ..., s[j]. The default value for i is 1; the default value for j is i. These indices are corrected following the same rules of function String.sub.

String.upper (s)

Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.

Binary Manipulation

Include this library by:

	local Binary = require "luan:Binary.luan"

Binary.binary (···)

Receives zero or more bytes (as integers). Returns a binary with length equal to the number of arguments, in which each byte has the internal numerical code equal to its corresponding argument.

Binary.byte (b [, i [, j]])

Returns the internal numerical codes of the bytes b[i], b[i+1], ..., b[j]. The default value for i is 1; the default value for j is i. These indices are corrected following the same rules of function String.sub.

Binary.to_string (b)

Converts the binary b to a string using the Java String constructor.

Table Manipulation

Include this library by:

	local Table = require "luan:Table.luan"

This library provides generic functions for table manipulation. It provides all its functions inside the table Table.

Table.clear (tbl)

Clears the table.

Table.concat (list [, sep [, i [, j]]])

Given a list, returns the string list[i]..sep..list[i+1] ··· sep..list[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is #list. If i is greater than j, returns the empty string.

Table.copy (tbl [, i [, j]])

If i is nil, returns a shallow copy of tbl. Otherwise returns a new table which is a list of the elements tbl[i] ··· tbl[j]. By default, j is #tbl.

Table.insert (list, pos, value)

Inserts element value at position pos in list, shifting up the elements list[pos], list[pos+1], ···, list[#list].

Table.is_empty (tbl)

Table.pack (···)

Returns a new table with all parameters stored into keys 1, 2, etc. and with a field "n" with the total number of parameters. Note that the resulting table may not be a sequence.

Table.remove (list, pos)

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].

Table.size (tbl)

Table.sort (list [, comp])

Sorts list elements in a given order, in-place, from list[1] to list[#list]. If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that not comp(list[i+1],list[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.

The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.

Table.unpack (list [, i [, j]])

Returns the elements from the given list. This function is equivalent to

     return list[i], list[i+1], ···, list[j]

By default, i is 1 and j is #list.

Number Manipulation

Include this library by:

	local Number = require "luan:Number.luan"

Number.double (x)

Returns x as a double.

Number.integer (x)

If the value x is convertible to an integer, returns that integer. Otherwise throws an error.

Number.long (x)

If the value x is convertible to an long, returns that long. Otherwise throws an error.

Number.long_to_string (i, radix)

Converts long value i to a string by calling Long.toString.

Number.type (x)

Returns a string for the numeric type of x. Possible return values include "integer", "long", "double", and "float".

Mathematical Functions

Include this library by:

	local Math = require "luan:Math.luan"

This library provides basic mathematical functions. It provides all its functions and constants inside the table Math.

Math.abs (x)

Returns the absolute value of x.

Math.acos (x)

Returns the arc cosine of x (in radians).

Math.asin (x)

Returns the arc sine of x (in radians).

Math.atan (y, x)

Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of x being zero.)

Math.ceil (x)

Returns the smallest integral value larger than or equal to x.

Math.cos (x)

Returns the cosine of x (assumed to be in radians).

Math.deg (x)

Converts the angle x from radians to degrees.

Math.exp (x)

Returns the value ex (where e is the base of natural logarithms).

Math.floor (x)

Returns the largest integral value smaller than or equal to x.

Math.fmod (x, y)

Returns the remainder of the division of x by y that rounds the quotient towards zero.

Math.huge

A value larger than any other numerical value.

Math.log (x [, base])

Returns the logarithm of x in the given base. The default for base is e (so that the function returns the natural logarithm of x).

Math.max (x, ···)

Returns the argument with the maximum value, according to the Lua operator <.

Math.max_integer

An integer with the maximum value for an integer.

Math.min (x, ···)

Returns the argument with the minimum value, according to the Lua operator <.

Math.min_integer

An integer with the minimum value for an integer.

Math.modf (x)

Returns the integral part of x and the fractional part of x.

Math.pi

The value of π.

Math.rad (x)

Converts the angle x from degrees to radians.

Math.random ([m [, n])

When called without arguments, returns a pseudo-random float with uniform distribution in the range [0,1). When called with two integers m and n, Math.random returns a pseudo-random integer with uniform distribution in the range [m, n]. (The value m-n cannot be negative and must fit in a Luan integer.) The call Math.random(n) is equivalent to Math.random(1,n).

This function is an interface to the underling pseudo-random generator function provided by Java. No guarantees can be given for its statistical properties.

Math.sin (x)

Returns the sine of x (assumed to be in radians).

Math.sqrt (x)

Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)

Math.tan (x)

Returns the tangent of x (assumed to be in radians).

6.8 – Input and Output Facilities

The I/O library provides two different styles for file manipulation. The first one uses implicit file handles; that is, there are operations to set a default input file and a default output file, and all input/output operations are over these default files. The second style uses explicit file handles.

When using implicit file handles, all operations are supplied by table io. When using explicit file handles, the operation io.open returns a file handle and then all operations are supplied as methods of the file handle.

The table io also provides three predefined file handles with their usual meanings from C: io.stdin, io.stdout, and io.stderr. The I/O library never closes these files.

Unless otherwise stated, all I/O functions return nil on failure (plus an error message as a second result and a system-dependent error code as a third result) and some value different from nil on success. On non-POSIX systems, the computation of the error message and error code in case of errors may be not thread safe, because they rely on the global C variable errno.


io.close ([file])

Equivalent to file:close(). Without a file, closes the default output file.


io.flush ()

Equivalent to io.output():flush().


io.input ([file])

When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without parameters, it returns the current default input file.

In case of errors this function raises the error, instead of returning an error code.


io.lines ([filename ···])

Opens the given file name in read mode and returns an iterator function that works like file:lines(···) over the opened file. When the iterator function detects the end of file, it returns no values (to finish the loop) and automatically closes the file.

The call io.lines() (with no file name) is equivalent to io.input():lines("*l"); that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.

In case of errors this function raises the error, instead of returning an error code.


io.open (filename [, mode])

This function opens a file, in the mode specified in the string mode. It returns a new file handle, or, in case of errors, nil plus an error message.

The mode string can be any of the following:

The mode string can also have a 'b' at the end, which is needed in some systems to open the file in binary mode.


io.output ([file])

Similar to io.input, but operates over the default output file.


io.popen (prog [, mode])

This function is system dependent and is not available on all platforms.

Starts program prog in a separated process and returns a file handle that you can use to read data from this program (if mode is "r", the default) or to write data to this program (if mode is "w").


io.read (···)

Equivalent to io.input():read(···).


io.tmpfile ()

Returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends.


io.type (obj)

Checks whether obj is a valid file handle. Returns the string "file" if obj is an open file handle, "closed file" if obj is a closed file handle, or nil if obj is not a file handle.


io.write (···)

Equivalent to io.output():write(···).


file:close ()

Closes file. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.

When closing a file handle created with io.popen, file:close returns the same values returned by os.execute.


file:flush ()

Saves any written data to file.


file:lines (···)

Returns an iterator function that, each time it is called, reads the file according to the given formats. When no format is given, uses "l" as a default. As an example, the construction

     for c in file:lines(1) do body end

will iterate over all characters of the file, starting at the current position. Unlike io.lines, this function does not close the file when the loop ends.

In case of errors this function raises the error, instead of returning an error code.


file:read (···)

Reads the file file, according to the given formats, which specify what to read. For each format, the function returns a string or a number with the characters read, or nil if it cannot read data with the specified format. (In this latter case, the function does not read subsequent formats.) When called without formats, it uses a default format that reads the next line (see below).

The available formats are

The formats "l" and "L" should be used only for text files.


file:seek ([whence [, offset]])

Sets and gets the file position, measured from the beginning of the file, to the position given by offset plus a base specified by the string whence, as follows:

In case of success, seek returns the final file position, measured in bytes from the beginning of the file. If seek fails, it returns nil, plus a string describing the error.

The default value for whence is "cur", and for offset is 0. Therefore, the call file:seek() returns the current file position, without changing it; the call file:seek("set") sets the position to the beginning of the file (and returns 0); and the call file:seek("end") sets the position to the end of the file, and returns its size.


file:setvbuf (mode [, size])

Sets the buffering mode for an output file. There are three available modes:

For the last two cases, size specifies the size of the buffer, in bytes. The default is an appropriate size.


file:write (···)

Writes the value of each of its arguments to file. The arguments must be strings or numbers.

In case of success, this function returns file. Otherwise it returns nil plus a string describing the error.

6.9 – Operating System Facilities

This library is implemented through table os.


os.clock ()

Returns an approximation of the amount in seconds of CPU time used by the program.


os.date ([format [, time]])

Returns a string or a table containing date and time, formatted according to the given string format.

If the time argument is present, this is the time to be formatted (see the os.time function for a description of this value). Otherwise, date formats the current time.

If format starts with '!', then the date is formatted in Coordinated Universal Time. After this optional character, if format is the string "*t", then date returns a table with the following fields: year (four digits), month (1–12), day (1–31), hour (0–23), min (0–59), sec (0–61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving flag, a boolean). This last field may be absent if the information is not available.

If format is not "*t", then date returns the date as a string, formatted according to the same rules as the ISO C function strftime.

When called without arguments, date returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date() is equivalent to os.date("%c")).

On non-POSIX systems, this function may be not thread safe because of its reliance on C function gmtime and C function localtime.


os.difftime (t2, t1)

Returns the difference, in seconds, from time t1 to time t2 (where the times are values returned by os.time). In POSIX, Windows, and some other systems, this value is exactly t2-t1.


os.execute ([command])

This function is equivalent to the ISO C function system. It passes command to be executed by an operating system shell. Its first result is true if the command terminated successfully, or nil otherwise. After this first result the function returns a string plus a number, as follows:

When called without a command, os.execute returns a boolean that is true if a shell is available.


os.exit ([code [, close]])

Calls the ISO C function exit to terminate the host program. If code is true, the returned status is EXIT_SUCCESS; if code is false, the returned status is EXIT_FAILURE; if code is a number, the returned status is this number. The default value for code is true.

If the optional second argument close is true, closes the Lua state before exiting.


os.getenv (varname)

Returns the value of the process environment variable varname, or nil if the variable is not defined.


os.remove (filename)

Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns nil, plus a string describing the error and the error code.


os.rename (oldname, newname)

Renames file or directory named oldname to newname. If this function fails, it returns nil, plus a string describing the error and the error code.


os.setlocale (locale [, category])

Sets the current locale of the program. locale is a system-dependent string specifying a locale; category is an optional string describing which category to change: "all", "collate", "ctype", "monetary", "numeric", or "time"; the default category is "all". The function returns the name of the new locale, or nil if the request cannot be honored.

If locale is the empty string, the current locale is set to an implementation-defined native locale. If locale is the string "C", the current locale is set to the standard C locale.

When called with nil as the first argument, this function only returns the name of the current locale for the given category.

This function may be not thread safe because of its reliance on C function setlocale.


os.time ([table])

Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year, month, and day, and may have fields hour (default is 12), min (default is 0), sec (default is 0), and isdst (default is nil). For a description of these fields, see the os.date function.

The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time can be used only as an argument to os.date and os.difftime.


os.tmpname ()

Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.

On POSIX systems, this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it).

When possible, you may prefer to use io.tmpfile, which automatically removes the file when the program ends.

6.10 – The Debug Library

This library provides the functionality of the debug interface (§4.9) to Lua programs. You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow.

All functions in this library are provided inside the debug table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread.


debug.debug ()

Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont finishes this function, so that the caller continues its execution.

Note that commands for debug.debug are not lexically nested within any function and so have no direct access to local variables.


debug.gethook ([thread])

Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the debug.sethook function).


debug.getinfo ([thread,] f [, what])

Returns a table with information about a function. You can give the function directly or you can give a number as the value of f, which means the function running at level f of the call stack of the given thread: level 0 is the current function (getinfo itself); level 1 is the function that called getinfo (except for tail calls, which do not count on the stack); and so on. If f is a number larger than the number of active functions, then getinfo returns nil.

The returned table can contain all the fields returned by lua_getinfo, with the string what describing which fields to fill in. The default for what is to get all information available, except the table of valid lines. If present, the option 'f' adds a field named func with the function itself. If present, the option 'L' adds a field named activelines with the table of valid lines.

For instance, the expression debug.getinfo(1,"n").name returns a table with a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information about the print function.


debug.getlocal ([thread,] f, local)

This function returns the name and the value of the local variable with index local of the function at level f of the stack. This function accesses not only explicit local variables, but also parameters, temporaries, etc.

The first parameter or local variable has index 1, and so on, following the order that they are declared in the code, counting only the variables that are active in the current scope of the function. Negative indices refer to vararg parameters; -1 is the first vararg parameter. The function returns nil if there is no variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo to check whether the level is valid.)

Variable names starting with '(' (open parenthesis) represent variables with no known names (internal variables such as loop control variables, and variables from chunks saved without debug information).

The parameter f may also be a function. In that case, getlocal returns only the name of function parameters.


debug.getmetatable (value)

Returns the metatable of the given value or nil if it does not have a metatable.


debug.getregistry ()

Returns the registry table (see §4.5).


debug.getupvalue (f, up)

This function returns the name and the value of the upvalue with index up of the function f. The function returns nil if there is no upvalue with the given index.

Variable names starting with '(' (open parenthesis) represent variables with no known names (variables from chunks saved without debug information).


debug.getuservalue (u)

Returns the Lua value associated to u. If u is not a userdata, returns nil.


debug.sethook ([thread,] hook, mask [, count])

Sets the given function as a hook. The string mask and the number count describe when the hook will be called. The string mask may have any combination of the following characters, with the given meaning:

Moreover, with a count different from zero, the hook is called also after every count instructions.

When called without arguments, debug.sethook turns off the hook.

When the hook is called, its first parameter is a string describing the event that has triggered its call: "call" (or "tail call"), "return", "line", and "count". For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo with level 2 to get more information about the running function (level 0 is the getinfo function, and level 1 is the hook function).


debug.setlocal ([thread,] level, local, value)

This function assigns the value value to the local variable with index local of the function at level level of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call getinfo to check whether the level is valid.) Otherwise, it returns the name of the local variable.

See debug.getlocal for more information about variable indices and names.


debug.setmetatable (value, table)

Sets the metatable for the given value to the given table (which can be nil). Returns value.


debug.setupvalue (f, up, value)

This function assigns the value value to the upvalue with index up of the function f. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.


debug.setuservalue (udata, value)

Sets the given value as the Lua value associated to the given udata. udata must be a full userdata.

Returns udata.


debug.traceback ([thread,] [message [, level]])

If message is present but is neither a string nor nil, this function returns message without further processing. Otherwise, it returns a string with a traceback of the call stack. The optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback (default is 1, the function calling traceback).


debug.upvalueid (f, n)

Returns a unique identifier (as a light userdata) for the upvalue numbered n from the given function.

These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices.


debug.upvaluejoin (f1, n1, f2, n2)

Make the n1-th upvalue of the Lua closure f1 refer to the n2-th upvalue of the Lua closure f2.

7 – Lua Standalone

Although Lua has been designed as an extension language, to be embedded in a host C program, it is also frequently used as a standalone language. An interpreter for Lua as a standalone language, called simply lua, is provided with the standard distribution. The standalone interpreter includes all standard libraries, including the debug library. Its usage is:

     lua [options] [script [args]]

The options are:

After handling its options, lua runs the given script. When called without arguments, lua behaves as lua -v -i when the standard input (stdin) is a terminal, and as lua - otherwise.

When called without option -E, the interpreter checks for an environment variable LUA_INIT_5_3 (or LUA_INIT if the versioned name is not defined) before running any argument. If the variable content has the format @filename, then lua executes the file. Otherwise, lua executes the string itself.

When called with option -E, besides ignoring LUA_INIT, Lua also ignores the values of LUA_PATH and LUA_CPATH, setting the values of package.path and package.cpath with the default paths defined in luaconf.h.

All options are handled in order, except -i and -E. For instance, an invocation like

     $ lua -e'a=1' -e 'print(a)' script.lua

will first set a to 1, then print the value of a, and finally run the file script.lua with no arguments. (Here $ is the shell prompt. Your prompt may be different.)

Before running any code, lua collects all command-line arguments in a global table called arg. The script name goes to index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus its options) go to negative indices. For instance, in the call

     $ lua -la b.lua t1 t2

the table is like this:

     arg = { [-2] = "lua", [-1] = "-la",
             [0] = "b.lua",
             [1] = "t1", [2] = "t2" }

If there is no script in the call, the interpreter name goes to index 0, followed by the other arguments. For instance, the call

     $ lua -e "print(arg[1])"

will print "-e". If there is a script, the script is called with parameters arg[1], ···, arg[#arg]. (Like all chunks in Lua, the script is compiled as a vararg function.)

In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt.

In case of unprotected errors in the script, the interpreter reports the error to the standard error stream. If the error object is not a string but has a metamethod __to_string, the interpreter calls this metamethod to produce the final message. Otherwise, the interpreter converts the error object to a string and adds a stack traceback to it.

When finishing normally, the interpreter closes its main Lua state (see lua_close). The script can avoid this step by calling os.exit to terminate.

To allow the use of Lua as a script interpreter in Unix systems, the standalone interpreter skips the first line of a chunk if it starts with #. Therefore, Lua scripts can be made into executable programs by using chmod +x and the #! form, as in

     #!/usr/local/bin/lua

(Of course, the location of the Lua interpreter may be different in your machine. If lua is in your PATH, then

     #!/usr/bin/env lua

is a more portable solution.)

8 – Incompatibilities with the Previous Version

Here we list the incompatibilities that you may find when moving a program from Lua 5.2 to Lua 5.3. You can avoid some incompatibilities by compiling Lua with appropriate options (see file luaconf.h). However, all these compatibility options will be removed in the future.

Lua versions can always change the C API in ways that do not imply source-code changes in a program, such as the numeric values for constants or the implementation of functions as macros. Therefore, you should not assume that binaries are compatible between different Lua versions. Always recompile clients of the Lua API when using a new version.

Similarly, Lua versions can always change the internal representation of precompiled chunks; precompiled chunks are not compatible between different Lua versions.

The standard paths in the official distribution may change between versions.

8.1 – Changes in the Language

8.2 – Changes in the Libraries

8.3 – Changes in the API

9 – The Complete Syntax of Lua

Here is the complete syntax of Lua in extended BNF. As usual in extended BNF, {A} means 0 or more As, and [A] means an optional A. (For operator precedences, see §3.4.8; for a description of the terminals Name, Numeral, and LiteralString, see §3.1.)


	chunk ::= block

	block ::= {stat} [retstat]

	stat ::=  ‘;’ | 
		 varlist ‘=’ explist | 
		 functioncall | 
		 label | 
		 break | 
		 goto Name | 
		 do block end | 
		 while exp do block end | 
		 repeat block until exp | 
		 if exp then block {elseif exp then block} [else block] end | 
		 for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end | 
		 for namelist in explist do block end | 
		 function funcname funcbody | 
		 local function Name funcbody | 
		 local namelist [‘=’ explist] 

	retstat ::= return [explist] [‘;’]

	label ::= ‘::’ Name ‘::’

	funcname ::= Name {‘.’ Name} [‘:’ Name]

	varlist ::= var {‘,’ var}

	var ::=  Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name 

	namelist ::= Name {‘,’ Name}

	explist ::= exp {‘,’ exp}

	exp ::=  nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | 
		 prefixexp | tableconstructor | exp binop exp | unop exp 

	prefixexp ::= var | functioncall | ‘(’ exp ‘)’

	functioncall ::=  prefixexp args | prefixexp ‘:’ Name args 

	args ::=  ‘(’ [explist] ‘)’ | tableconstructor | LiteralString 

	functiondef ::= function funcbody

	funcbody ::= ‘(’ [parlist] ‘)’ block end

	parlist ::= namelist [‘,’ ‘...’] | ‘...’

	tableconstructor ::= ‘{’ [fieldlist] ‘}’

	fieldlist ::= field {fieldsep field} [fieldsep]

	field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp

	fieldsep ::= ‘,’ | ‘;’

	binop ::=  ‘+’ | ‘-’ | ‘*’ | ‘/’ | ‘//’ | ‘^’ | ‘%’ | 
		 ‘&’ | ‘~’ | ‘|’ | ‘>>’ | ‘<<’ | ‘..’ | 
		 ‘<’ | ‘<=’ | ‘>’ | ‘>=’ | ‘==’ | ‘~=’ | 
		 and | or

	unop ::= ‘-’ | not | ‘#’ | ‘~


Last update: Fri Jan 16 00:58:20 BRST 2015