Luan / Documentation reactionary software by fschmidt

Luan Reference Manual

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


Contents


Introduction

contents

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 features to Luan, but rather by providing a complete set of libraries.

Basic Concepts

contents

This section describes the basic concepts of the language.

Values and Types

contents

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

contents

The environment of a chunk starts with only one local variable: require. This function is 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

contents

Luan code can explicitly generate an error by calling the error function. If you need to catch errors in Luan, you can use the Try Statement.

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

Metatables and Metamethods

contents

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

contents

Luan uses Java's garbage collection.

The Language

contents

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

contents

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 catch continue do else elseif end_do end_for end_function end_if end_try end_while false finally for function if in local nil not or repeat return then true try 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

contents

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

contents

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

contents

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

contents

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

contents

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

contents

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 continue statement jumps to the beginning of a while, repeat, or for loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration:

	stat ::= continue

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

contents

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:

Try Statement

contents

The try statement has the same semantics as in Java.

	stat ::= try block [catch Name block] [finally block] end_try
	end_try ::= end_try | end

Function Calls as Statements

contents

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.

Logical Statement

contents

Logical expressions can be statements. This is useful in cases like this:

	x==5 or error "x should be 5"

Local Declarations

contents

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

contents

Template statements provide the full equivalent of JSP but in a general way. Template statements write 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 , "!\nBye ", name , ".\n" )

Expressions

contents

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

contents

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.

Floor division (//) is a division that rounds the quotient towards minus infinity, that is, the floor of the division of its operands.

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

contents

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

contents

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

contents

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

contents

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

The Length Operator

contents

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

contents

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

contents

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

contents

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

contents

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.

Backticks

contents

A block between backticks is run and then whatever was sent to standard output is returned as a string. Examples:

	local s = `%>1 + 1 = <%=1+1%><%`

	local s = ` fn(whatever) `

	local s = `%>
	...
	<%`

Backticks complement template statements.

Visibility Rules

contents

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

contents

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

contents

This is provided by default as a local variable for any Luan code as described in Environments.

require (mod_uri)

contents

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

A special case is:

	require "java"

This 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.

Basic Functions

contents

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])

contents

Could be defined as:

	function Luan.do_file(uri)
		local fn = Luan.load_file(uri) or Luan.error("file '"..uri.."' not found")
		return fn()
	end

Luan.error (message)

contents

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 [, env]])

contents

Evaluates text as a Luan expression.

Could be defined as:

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

Luan.get_metatable (table)

contents

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.hash_code (v)

contents

Returns the hash code of v.

Luan.ipairs (t)

contents

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 [, persist]]])

contents

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. Defaults to "load".

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

The persist parameter is a boolean which determines if the compiled code is persistently cached to a temporary file. Defaults to false.

Luan.load_file (file_uri)

contents

Similar to load, but gets the chunk from file file_uri. file_uri can be a string or a uri table.

Luan.new_error (message)

contents

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)

contents

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.range (start, stop [, step])

contents

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)

contents

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

Luan.raw_get (table, index)

contents

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)

contents

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)

contents

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 Luan value.

Luan.set_metatable (table, metatable)

contents

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 [,options])

contents

Receives a value of any type and converts it to a string that is a Luan expression. options is a table. If options.strict==true then invalid types throw an error. Otherwise invalid types are represented but the resulting expression is invalid. If options.number_types==true then numbers will be wrapped in functions for their type.

Luan.to_string (v)

contents

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.type (v)

contents

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 (···)

contents

Returns a function so that the construction

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

will iterate over all values of ···.

Luan.VERSION

contents

A global variable (not a function) that holds a string containing the current Luan version.

Modules

contents

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)

contents

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

contents

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

contents

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 (···)

contents

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.contains (s, s2)

contents

Returns a boolean indicating whether the s contains s2.

String.encode (s)

contents

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

String.ends_with (s, s2)

contents

Returns a boolean indicating whether the s ends with s2.

String.find (s, s2 [, init])

contents

Looks for the first substring s2 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.

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

String.format (formatstring, ···)

contents

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.lower (s)

contents

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

String.regex (s)

contents

Returns a regex table for the pattern s.

String.regex_quote (s)

contents

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

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

contents

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.replace (s, target, replacement)

contents

Returns a string where each substring target in s is replaced by replacement.

String.reverse (s)

contents

Returns a string that is the string s reversed.

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

contents

Splits s using substring s2 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.starts_with (s, s2)

contents

Returns a boolean indicating whether the s starts with s2.

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

contents

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)

contents

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

String.to_number (s [, base])

contents

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)

contents

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

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

contents

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)

contents

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.

Regular Expressions

contents

Regular expressions are handled using a regex table generated by String.regex.

Pattern matching is based on the Java Pattern class.

regex.find (s [, init])

contents

Looks for the first match of the regex 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.

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

regex.gmatch (s)

contents

Returns an iterator function that, each time it is called, returns the next captures from the regex over the string s. If the regex 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 r = String.regex[[\w+]]
	local s = "hello world from Lua"
	for w in r.gmatch(s) do
		print(w)
	end

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

	local t = {}
	local r = String.regex[[(\w+)=(\w+)]]
	local s = "from=world, to=Lua"
	for k, v in r.gmatch(s) 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.

regex.gsub (s, repl [, n])

contents

Returns a copy of s in which all (or the first n, if given) occurrences of the regex 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 regex specifies no captures, then it behaves as if the whole regex 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:

	local r = String.regex[[(\w+)]]
	local x = r.gsub("hello world", "$1 $1")
	--> x="hello hello world world"

	local r = String.regex[[(\w+)]]
	local x = r.gsub("hello world", "$0 $0", 1)
	--> x="hello hello world"

	local r = String.regex[[(\w+)\s*(\w+)]]
	local x = r.gsub("hello world from Luan", "$2 $1")
	--> x="world hello Luan from"
	     
	local r = String.regex[[\$(.*?)\$]]
	local x = r.gsub("4+5 = $return 4+5$", function(s)
		return load(s)()
	end)
	--> x="4+5 = 9"

	local r = String.regex[[\$(\w+)]]
	local t = {name="lua", version="5.3"}
	local x = r.gsub("$name-$version.tar.gz", t)
	--> x="lua-5.3.tar.gz"

regex.match (s [, init])

contents

Looks for the first match of the regex in the string s. If it finds one, then match returns the captures from the regex; otherwise it returns nil. If the regex 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.

regex.matches (s)

contents

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

     return regex.match(s) ~= nil

regex.set (pattern)

contents

Changes the regex pattern to pattern.

regex.split (s [, limit])

contents

Splits s using the regex 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.

Binary Manipulation

contents

Include this library by:

	local Binary = require "luan:Binary.luan"

Binary.binary (···)

contents

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]])

contents

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 [,charset])

contents

If charset is not nil then converts the binary b to a string using the Java String constructor, else makes each byte a char.

Table Manipulation

contents

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)

contents

Clears the table.

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

contents

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]])

contents

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)

contents

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

Table.is_empty (tbl)

contents

Table.is_list (tbl)

contents

Table.pack (···)

contents

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)

contents

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)

contents

Table.sort (list [, comp])

contents

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]])

contents

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.n or #list.

Number Manipulation

contents

Include this library by:

	local Number = require "luan:Number.luan"

Number.double (x)

contents

Returns x as a double.

Number.float (x)

contents

Returns x as a float.

Number.integer (x)

contents

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

Number.long (x)

contents

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

Number.long_to_string (i, radix)

contents

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

Number.type (x)

contents

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

Mathematical Functions

contents

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)

contents

Returns the absolute value of x.

Math.acos (x)

contents

Returns the arc cosine of x (in radians).

Math.asin (x)

contents

Returns the arc sine of x (in radians).

Math.atan (y, x)

contents

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)

contents

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

Math.cos (x)

contents

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

Math.deg (x)

contents

Converts the angle x from radians to degrees.

Math.exp (x)

contents

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

Math.floor (x)

contents

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

Math.fmod (x, y)

contents

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

Math.huge

contents

A value larger than any other numerical value.

Math.log (x [, base])

contents

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, ···)

contents

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

Math.max_integer

contents

An integer with the maximum value for an integer.

Math.min (x, ···)

contents

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

Math.min_integer

contents

An integer with the minimum value for an integer.

Math.modf (x)

contents

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

Math.pi

contents

The value of π.

Math.rad (x)

contents

Converts the angle x from degrees to radians.

Math.random ([m [, n])

contents

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)

contents

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

Math.sqrt (x)

contents

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

Math.tan (x)

contents

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