Original copyright © 2015 Lua.org, PUC-Rio. Freely available under the terms of the Lua license. Modified for Luan.
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.
This section describes the basic concepts of the language.
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.
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.
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.
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
You can query the metatable of any table
using the
You can replace the metatable of tables
using the
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, '
Here are the events:
"add":
the "sub":
the "mul":
the "div":
the "mod":
the "pow":
the "unm":
the "concat":
the "len":
the "eq":
the "lt":
the "le":
the "index":
The indexing access
Despite the name,
the metamethod for this event can be any type.
If it is a function,
it is called with "new_index":
The indexing assignment
Like with indexing,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with
Whenever there is a "new_index" metamethod,
Luan does not perform the primitive assignment.
(If necessary,
the metamethod itself can call "gc":
This is when a table is garbage collected. When the table's finalize method is called by the Java garbage collector, if there is a "
Luan uses Java's garbage collection.
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.
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:
Luan is a case-sensitive language:
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:
'
Luan can specify any character in a literal string by its numerical value.
This can be done
with the escape sequence
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
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 numerical constant (or numeral)
can be written with an optional fractional part
and an optional decimal exponent,
marked by a letter '
Examples of valid float constants are
A comment starts with a double hyphen (
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):
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:
The meaning of accesses to table fields can be changed via metatables.
An access to an indexed variable
The syntax
Global variables are not available by default. To enable global variable, you must define
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.
A block is a list of statements,
which are executed sequentially:
Luan has empty statements
that allow you to separate statements with semicolons,
start a block with a semicolon
or write two semicolons in sequence:
A block can be explicitly delimited to produce a single statement:
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).
The unit of compilation of Luan is called a chunk.
Syntactically,
a chunk is simply a 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.
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:
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
sets
exchanges the values of
cyclically permutes the values of
The meaning of assignments to global variables
and table fields can be changed via metatables.
An assignment to an indexed variable
An assignment to a global name
The control structures
if, while, and repeat have the usual meaning and
familiar syntax:
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 repeat–until 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:
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
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:
A for statement like
is equivalent to the code:
Note the following:
The try statement has the same semantics as in Java.
To allow possible side-effects,
function calls can be executed as statements:
In this case, all returned values are thrown away.
Function calls are explained in Function Calls.
Local variables can be declared anywhere inside a block.
The declaration can include an initial assignment:
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 provide the full equivalent of JSP but in a general way. Template statements write to standard output. For example: is equivalent to the code:
The basic expressions in Luan are the following:
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 ('
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:
Any expression enclosed in parentheses always results in only one value.
Thus,
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.)
Luan generally avoids automatic conversions.
String concatenation automatically converts all of its arguments to strings.
Luan provides library functions for explicit type conversions.
Luan supports the following relational operators:
These operators always result in false or true.
Equality (
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
Equality comparisons do not convert strings to numbers
or vice versa.
Thus,
The operator
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
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:
(In this manual,
The string concatenation operator in Luan is
denoted by two dots ('
The length operator is denoted by the unary prefix operator
A program can modify the behavior of the length operator for
any table through the
Unless a
has a length of
Operator precedence in Luan follows the table below,
from lower to higher priority:
As usual,
you can use parentheses to change the precedences of an expression.
The concatenation ('
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
Each field of the form
is equivalent to
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
The field list can have an optional trailing separator,
as a convenience for machine-generated code.
A function call in Luan has the following syntax:
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:
All argument expressions are evaluated before the call.
A call of the form
The syntax for function definition is
The following syntactic sugar simplifies function definitions:
The statement
translates to
The statement
translates to
The statement
translates to
not to
(This only makes a difference when the body of the function
contains references to
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:
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 ('
As an example, consider the following definitions:
Then, we have the following mapping from arguments to parameters and
to the vararg expression:
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.
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:
Notice that, in a declaration like
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:
The loop creates ten closures
(that is, ten instances of the anonymous function).
Each of these closures uses a different
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.,
This is provided by default as a local variable for any Luan code as described in Environments.
Example use:
Could be defined as:
A special case is:
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.
Include this library by:
The basic library provides basic functions to Luan that don't depend on other libaries.
Could be defined as:
Throws an error containing the message.
Could be defined as:
Evaluates
Could be defined as:
If
Returns the hash code of
Returns an iterator function
so that the construction
will iterate over the key–value pairs
(
Could be defined as:
Loads a chunk.
The
The
If the
The
Similar to
Creates a new error table containing the message assigned to "
To print the current stack trace, you could do:
If
Otherwise,
returns a function
so that the construction
will iterate over all key–value pairs of table
Based on the Python range() function, this lets one iterate through a sequence of numbers.
Example use:
Could be defined as:
Checks whether
Gets the real value of
Returns the length of the object
Sets the real value of
Sets the metatable for the given table.
If
Receives a value of any type and converts it to a string that is a Luan expression.
Receives a value of any type and
converts it to a string in a human-readable format.
If the metatable of
Returns the type of its only argument, coded as a string.
The possible results of this function are
"
Returns a function so that the construction
will iterate over all values of
A global variable (not a function) that
holds a string containing the current Luan version.
Include this library by:
The package library provides basic
facilities for loading modules in Luan.
Loads the given module.
The function starts by looking into the
To load a new value,
Otherwise
If a new value for the module successful loaded, then it is stored in
A table used by
This variable is only a reference to the real table;
assignments to this variable do not change the
table used by
Include this library by:
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.
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.
Encodes argument
Looks for the first match of
If the pattern has captures,
then in a successful match
the captured values are also returned,
after the two indices.
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
Note that Java's
Returns an iterator function that,
each time it is called,
returns the next captures from
As an example, the following loop
will iterate over all the words from string
The next example collects all pairs
For this function, a caret '
Returns a copy of
If
If
If
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:
Receives a string and returns a copy of this string with all
uppercase letters changed to lowercase.
All other characters are left unchanged.
Looks for the first match of
Returns a boolean indicating whether the
Returns a string which matches the literal string
Returns a string that is the concatenation of
Returns a string that is the string
Splits
Returns the substring of
If, after the translation of negative indices,
Converts a string to a binary by calling the Java method
When called with no
When called with
Removes the leading and trailing whitespace by calling the Java method
Returns the internal numerical codes of the characters
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.
Include this library by:
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.
Returns the internal numerical codes of the bytes
If
Include this library by:
This library provides generic functions for table manipulation.
It provides all its functions inside the table
Clears the table.
Given a list,
returns the string
If
Inserts element
Returns a new table with all parameters stored into keys 1, 2, etc.
and with a field "
Removes from
Sorts list elements in a given order, in-place,
from
The sort algorithm is not stable;
that is, elements considered equal by the given order
may have their relative positions changed by the sort.
Returns the elements from the given list.
This function is equivalent to
By default,
Include this library by:
Returns
Returns
If the value
If the value
Converts long value
Returns a string for the numeric type of
Include this library by:
This library provides basic mathematical functions.
It provides all its functions and constants inside the table
Returns the absolute value of
Returns the arc cosine of
Returns the arc sine of
Returns the arc tangent of
Returns the smallest integral value larger than or equal to
Returns the cosine of
Converts the angle
Returns the value ex
(where
Returns the largest integral value smaller than or equal to
Returns the remainder of the division of
A value larger than any other numerical value.
Returns the logarithm of
Returns the argument with the maximum value,
according to the Lua operator
An integer with the maximum value for an integer.
Returns the argument with the minimum value,
according to the Lua operator
An integer with the minimum value for an integer.
Returns the integral part of
The value of π.
Converts the angle
When called without arguments,
returns a pseudo-random float with uniform distribution
in the range [0,1).
When called with two integers
This function is an interface to the underling
pseudo-random generator function provided by Java.
No guarantees can be given for its statistical properties.
Returns the sine of
Returns the square root of
Returns the tangent of
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
The table
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
Equivalent to
Equivalent to
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.
Opens the given file name in read mode
and returns an iterator function that
works like
The call
In case of errors this function raises the error,
instead of returning an error code.
This function opens a file,
in the mode specified in the string
The
The
Similar to
This function is system dependent and is not available
on all platforms.
Starts program
Equivalent to
Returns a handle for a temporary file.
This file is opened in update mode
and it is automatically removed when the program ends.
Checks whether
Equivalent to
Closes
When closing a file handle created with
Saves any written data to
Returns an iterator function that,
each time it is called,
reads the file according to the given formats.
When no format is given,
uses "
will iterate over all characters of the file,
starting at the current position.
Unlike
In case of errors this function raises the error,
instead of returning an error code.
Reads the file
The available formats are
The formats "
Sets and gets the file position,
measured from the beginning of the file,
to the position given by
In case of success,
The default value for
Sets the buffering mode for an output file.
There are three available modes:
For the last two cases,
Writes the value of each of its arguments to
In case of success, this function returns
This library is implemented through table
Returns an approximation of the amount in seconds of CPU time
used by the program.
Returns a string or a table containing date and time,
formatted according to the given string
If the
If
If
When called without arguments,
On non-POSIX systems,
this function may be not thread safe
because of its reliance on C function
Returns the difference, in seconds,
from time
This function is equivalent to the ISO C function
When called without a
Calls the ISO C function
If the optional second argument
Returns the value of the process environment variable
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.
Renames file or directory named
Sets the current locale of the program.
If
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
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
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
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
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
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
Note that commands for
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
Returns a table with information about a function.
You can give the function directly
or you can give a number as the value of
The returned table can contain all the fields returned by
For instance, the expression
This function returns the name and the value of the local variable
with index
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
Variable names starting with '
The parameter
Returns the metatable of the given
Returns the registry table (see §4.5).
This function returns the name and the value of the upvalue
with index
Variable names starting with '
Returns the Lua value associated to
Sets the given function as a hook.
The string
Moreover,
with a
When called without arguments,
When the hook is called, its first parameter is a string
describing the event that has triggered its call:
This function assigns the value
See
Sets the metatable for the given
This function assigns the value
Sets the given
Returns
If
Returns a unique identifier (as a light userdata)
for the upvalue numbered
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.
Make the
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
The options are:
After handling its options,
When called without option
When called with option
All options are handled in order, except
will first set
Before running any code,
the table is like this:
If there is no script in the call,
the interpreter name goes to index 0,
followed by the other arguments.
For instance, the call
will print "
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
When finishing normally,
the interpreter closes its main Lua state
(see
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
(Of course,
the location of the Lua interpreter may be different in your machine.
If
is a more portable solution.)
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
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.
You can fix these differences by forcing a number to be a float
(in Lua 5.2 all numbers were float),
in particular writing constants with an ending
(Formally this is not an incompatibility,
because Lua does not specify how numbers are formatted as strings,
but some programs assumed a specific format.)
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.)
"add"
and the metamethod is the function that performs the addition.
get_metatable function.
set_metatable function.
__';
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)
+ operation.
If any operand for an addition is a table,
Luan will try to call a metamethod.
First, Luan will check the first operand (even if it is valid).
If that operand does not define a metamethod for the "__add" event,
then Luan will check the second operand.
If Luan can find a metamethod,
it calls the metamethod with the two operands as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
Otherwise,
it raises an error.
- operation.
Behavior similar to the "add" operation.
* operation.
Behavior similar to the "add" operation.
/ operation.
Behavior similar to the "add" operation.
% operation.
Behavior similar to the "add" operation.
^ (exponentiation) operation.
Behavior similar to the "add" operation.
- (unary minus) operation.
Behavior similar to the "add" operation.
.. (concatenation) operation.
Behavior similar to the "add" operation.
# (length) operation.
If there is a metamethod,
Luan calls it with the object as argument,
and the result of the call
(always adjusted to one value)
is the result of the operation.
If there is no metamethod but the object is a table,
then Luan uses the table length operation (see The Length Operator).
Otherwise, Luan raises an error.
== (equal) operation.
Behavior similar to the "add" operation,
except that Luan will try a metamethod only when the values
being compared are both tables
and they are not primitively equal.
The result of the call is always converted to a boolean.
< (less than) operation.
Behavior similar to the "add" operation.
The result of the call is always converted to a boolean.
<= (less equal) operation.
Unlike other operations,
The less-equal operation can use two different events.
First, Luan looks for the "__le" metamethod in both operands,
like in the "lt" operation.
If it cannot find such a metamethod,
then it will try the "__lt" event,
assuming that a <= b is equivalent to not (b < a).
As with the other comparison operators,
the result is always a boolean.
table[key].
This event happens
when key is not present in table.
The metamethod is looked up in table.
table and key as arguments.
Otherwise
the final result is the result of indexing this metamethod object with key.
(This indexing is regular, not raw,
and therefore can trigger another metamethod if the metamethod object is a table.)
table[key] = value.
Like the index event,
this event happens when
when key is not present in table.
The metamethod is looked up in table.
table, key, and value as arguments.
If it is a table,
Luan does an indexing assignment to this table with the same key and value.
(This assignment is regular, not raw,
and therefore can trigger another metamethod.)
raw_set
to do the assignment.)
__gc" metamethod then it is called with the table as a parameter.
Garbage Collection
The Language
Lexical Conventions
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
and is a reserved word, but And and AND
are two different, valid names.
+ - * / % ^ #
& ~ | << >> //
== ~= <= >= < > =
( ) { } [ ] ::
; : , . .. ...
\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.
\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.)
[[,
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.
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]
a = [==[
alo
123"]==]
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
3.0 3.1416 314.16e-2 0.31416E1 34e1
0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
--)
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
var ::= Name
var ::= prefixexp ‘[’ exp ‘]’
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.)
var.Name is just syntactic sugar for
var["Name"]:
var ::= prefixexp ‘.’ Name
_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
Blocks
block ::= {stat}
stat ::= ‘;’
stat ::= do block end_do
end_do ::= end_do | end
Chunks
chunk ::= block
Assignment
stat ::= varlist ‘=’ explist
varlist ::= var {‘,’ var}
explist ::= exp {‘,’ exp}
i = 3
i, a[i] = i+1, 20
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
x and y,
and
x, y, z = y, z, x
x, y, and z.
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.)
x = val
is equivalent to the assignment
_ENV.x = val (see Environments).
Global names are only available when _ENV is defined.
Control Structures
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
stat ::= break
stat ::= return [explist] [‘;’]
For Statement
stat ::= for namelist in exp do block end_for
namelist ::= Name {‘,’ Name}
end_for ::= end_for | end
for var_1, ···, var_n in exp do block end
do
local f = exp
while true do
local var_1, ···, var_n = f()
if var_1 == nil then break end
block
end
end
exp is evaluated only once.
Its result is an iterator function.
f is an invisible variable.
The name is here for explanatory purposes only.
var_i are local to the loop;
you cannot use their values after the for ends.
If you need these values,
then assign them to other variables before breaking or exiting the loop.
Try Statement
stat ::= try block [catch Name block] [finally block] end_try
end_try ::= end_try | end
Function Calls as Statements
stat ::= functioncall
Local Declarations
stat ::= local namelist [‘=’ explist]
Template Statements
local name = "Bob"
%>
Hello <%= name %>!
Bye <%= name %>.
<%
local name = "Bob"
require("luan:Io.luan").stdout.write( "Hello ", name , "!\nBye ", name , ".\n" )
Expressions
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 ‘)’
...'), can only be used when
directly inside a vararg function;
they are explained in Function Definitions.
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
(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
+: addition-: subtraction*: multiplication/: division%: modulo^: exponentiation-: unary minusCoercions and Conversions
Relational Operators
==: equality~=: inequality<: less than>: greater than<=: less or equal>=: greater or equal==) 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).
equals method.
"0"==0 evaluates to false,
and t[0] and t["0"] denote different
entries in a table.
~= is exactly the negation of equality (==).
a > b is translated to b < a
and a >= b is translated to b <= a.
Logical Operators
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
--> indicates the result of the preceding expression.)
Concatenation
..').
All operands are converted to strings.
The Length Operator
#.
The length of a string is its number of characters.
The length of a binary is its number of bytes.
__len metamethod (see Metatables and Metamethods).
__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}
2, because that is the last key in sequence.
Precedence
or
and
< > <= >= ~= ==
..
+ -
* / %
unary operators (not # -)
^
..') and exponentiation ('^')
operators are right associative.
All other binary operators are left associative.
Table Constructors
tableconstructor ::= ‘{’ fieldlist ‘}’
fieldlist ::= [field] {fieldsep [field]}
field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp
fieldsep ::= ‘,’ | ‘;’ | end_of_line
[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 }
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
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).
Function Calls
functioncall ::= prefixexp args
args ::= ‘(’ [explist] ‘)’
args ::= tableconstructor
args ::= LiteralString
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
functiondef ::= function funcbody
funcbody ::= ‘(’ [parlist] ‘)’ block end_function
end_function ::= end_function | end
stat ::= function funcname funcbody
stat ::= local function Name funcbody
funcname ::= Name {‘.’ Name} [‘:’ Name]
function f () body end
f = function () body end
function t.a.b.c.f () body end
t.a.b.c.f = function () body end
local function f () body end
local f; f = function () body end
local f = function () body end
f.)
parlist ::= namelist [‘,’ ‘...’] | ‘...’
...')
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).
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end
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
Visibility Rules
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)
local x = x,
the new x being declared is not in scope yet,
and so the second x refers to the outside variable.
a = {}
local x = 20
for i=1,10 do
local y = 0
a[i] = function () y=y+1; return x+y end
end
y variable,
while all of them share the same x.
Standard Libraries
type and get_metatable);
others provide access to "outside" services (e.g., I/O).
Default Environment
require (mod_uri)
local Table = require "luan:Table.luan"
local function require(mod_name)
return Package.load(mod_name) or Luan.error("module '"..mod_name.."' not found")
end
require "java"
Basic Functions
local Luan = require "luan:Luan.luan"
Luan.do_file ([uri])
function Luan.do_file(uri)
local fn = Luan.load_file(uri) or Luan.error("file '"..uri.."' not found")
return fn()
end
Luan.error (message)
function Luan.error(message)
Luan.new_error(message).throw()
end
Luan.eval (text [, source_name [, env]])text as a Luan expression.
function Luan.eval(text,source_name, env)
return Luan.load( "return "..text, source_name or "eval", env )()
end
Luan.get_metatable (table)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)v.
Luan.ipairs (t)
for i,v in ipairs(t) do body end
1,t[1]), (2,t[2]), ...,
up to the first nil value.
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]]])text is compiled.
If there are no syntactic errors,
returns the compiled chunk as a function;
otherwise, throws an error.
source_name parameter is a string saying where the text came from. It is used to produce error messages. Defaults to "load".
env parameter is supplied, it becomes the _ENV of the chunk.
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)load,
but gets the chunk from file file_uri.
file_uri can be a string or a uri table.
Luan.new_error (message)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.
Io.print( Luan.new_error "stack" )
Luan.pairs (t)t has a metamethod __pairs,
calls it with t as argument and returns the
result from the call.
for k,v in pairs(t) do body end
t.
Receives any number of arguments
and prints their values to print (···)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])
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
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)v1 is equal to v2,
without invoking any metamethod.
Returns a boolean.
Luan.raw_get (table, index)table[index],
without invoking any metamethod.
table must be a table;
index may be any value.
Luan.raw_len (v)v,
which must be a table or a string,
without invoking any metamethod.
Returns an integer.
Luan.raw_set (table, index, value)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)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])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)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)nil" (a string, not the value nil),
"number",
"string",
"binary",
"boolean",
"table",
"function",
and "java".
Luan.values (···)
for i, v in Luan.values(···) do body end
···.
Luan.VERSIONModules
local Package = require "luan:Package.luan"
Package.load (mod_uri)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.
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.
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.
Package.loaded[mod_uri]. The value is returned.
Package.loadedPackage.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.
Package.load.
String Manipulation
local String = require "luan:String.luan"
String.char (···)String.encode (s)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]])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.
String.format (formatstring, ···)String.format because Luan calls this internally.
String.format is too stupid to convert between ints and floats, so you must provide the right kind of number.
String.gmatch (s, pattern)pattern (see Pattern)
over the string s.
If pattern specifies no captures,
then the whole match is produced in each call.
s,
printing one per line:
local s = "hello world from Lua"
for w in String.gmatch(s, [[\w+]]) do
print(w)
end
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
^' at the start of a pattern does not
work as an anchor, as this would prevent the iteration.
String.gsub (s, pattern, repl [, n])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.
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.
repl is a table, then the table is queried for every match,
using the first capture as the key.
repl is a function, then this function is called every time a
match occurs, with all captured substrings passed as arguments,
in order.
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.lower (s)String.match (s, pattern [, init])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)pattern can be found in string s.
This function is equivalent to
return String.match(s,pattern) ~= nil
String.regex_quote (s)s in a regular expression. This function is simply the Java method Pattern.quote.
String.rep (s, n [, sep])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)s reversed.
String.split (s, pattern [, limit])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])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.
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)String.getBytes.
String.to_number (s [, base])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.
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)String.trim.
String.unicode (s [, i [, j]])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)Binary Manipulation
local Binary = require "luan:Binary.luan"
Binary.binary (···)Binary.byte (b [, i [, j]])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])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
local Table = require "luan:Table.luan"
Table.
Table.clear (tbl)Table.concat (list [, sep [, i [, j]]])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]])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)value at position pos in list,
shifting up the elements
list[pos], list[pos+1], ···, list[#list].
Table.is_empty (tbl)Table.pack (···)n" with the total number of parameters.
Note that the resulting table may not be a sequence.
Table.remove (list, pos)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])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.
Table.unpack (list [, i [, j]])
return list[i], list[i+1], ···, list[j]
i is 1 and j is list.n or #list.
Number Manipulation
local Number = require "luan:Number.luan"
Number.double (x)x as a double.
Number.float (x)x as a float.
Number.integer (x)x is convertible to an integer,
returns that integer.
Otherwise throws an error.
Number.long (x)x is convertible to an long,
returns that long.
Otherwise throws an error.
Number.long_to_string (i, radix)i to a string by calling Long.toString.
Number.type (x)x. Possible return values include "integer", "long", "double", and "float".
Mathematical Functions
local Math = require "luan:Math.luan"
Math.
Math.abs (x)x.
Math.acos (x)x (in radians).
Math.asin (x)x (in radians).
Math.atan (y, x)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)x.
Math.cos (x)x (assumed to be in radians).
Math.deg (x)x from radians to degrees.
Math.exp (x)e is the base of natural logarithms).
Math.floor (x)x.
Math.fmod (x, y)x by y
that rounds the quotient towards zero.
Math.hugeMath.log (x [, base])x in the given base.
The default for base is e
(so that the function returns the natural logarithm of x).
Math.max (x, ···)<.
Math.max_integerMath.min (x, ···)<.
Math.min_integerMath.modf (x)x and the fractional part of x.
Math.piMath.rad (x)x from degrees to radians.
Math.random ([m [, n])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).
Math.sin (x)x (assumed to be in radians).
Math.sqrt (x)x.
(You can also use the expression x^0.5 to compute this value.)
Math.tan (x)x (assumed to be in radians).
6.8 – Input and Output Facilities
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.
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.
errno.
io.close ([file])file:close().
Without a file, closes the default output file.
io.flush ()io.output():flush().
io.input ([file])io.lines ([filename ···])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.
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.
io.open (filename [, mode])mode.
It returns a new file handle,
or, in case of errors, nil plus an error message.
mode string can be any of the following:
r": read mode (the default);w": write mode;a": append mode;r+": update mode, all previous data is preserved;w+": update mode, all previous data is erased;a+": append update mode, previous data is preserved,
writing is only allowed at the end of file.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])io.input, but operates over the default output file.
io.popen (prog [, mode])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 (···)io.input():read(···).
io.tmpfile ()io.type (obj)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 (···)io.output():write(···).
file:close ()file.
Note that files are automatically closed when
their handles are garbage collected,
but that takes an unpredictable amount of time to happen.
io.popen,
file:close returns the same values
returned by os.execute.
file:flush ()file.
file:lines (···)l" as a default.
As an example, the construction
for c in file:lines(1) do body end
io.lines, this function does not close the file
when the loop ends.
file:read (···)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).
n":
reads a numeral and returns it as a float or an integer,
following the lexical conventions of Lua.
(The numeral may have leading spaces and a sign.)
This format always reads the longest input sequence that
is a valid prefix for a number;
if that prefix does not form a valid number
(e.g., an empty string, "0x", or "3.4e-"),
it is discarded and the function returns nil.
i":
reads an integral number and returns it as an integer.
a":
reads the whole file, starting at the current position.
On end of file, it returns the empty string.
l":
reads the next line skipping the end of line,
returning nil on end of file.
This is the default format.
L":
reads the next line keeping the end-of-line character (if present),
returning nil on end of file.
number is zero,
it reads nothing and returns an empty string,
or nil on end of file.
l" and "L" should be used only for text files.
file:seek ([whence [, offset]])offset plus a base
specified by the string whence, as follows:
set": base is position 0 (beginning of the file);cur": base is current position;end": base is end of file;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.
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])
no":
no buffering; the result of any output operation appears immediately.
full":
full buffering; output operation is performed only
when the buffer is full or when
you explicitly flush the file (see io.flush).
line":
line buffering; output is buffered until a newline is output
or there is any input from some special files
(such as a terminal device).
size
specifies the size of the buffer, in bytes.
The default is an appropriate size.
file:write (···)file.
The arguments must be strings or numbers.
file.
Otherwise it returns nil plus a string describing the error.
6.9 – Operating System Facilities
os.
os.clock ()os.date ([format [, time]])format.
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.
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.
format is not "*t",
then date returns the date as a string,
formatted according to the same rules as the ISO C function strftime.
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")).
gmtime and C function localtime.
os.difftime (t2, t1)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])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:
exit":
the command terminated normally;
the following number is the exit status of the command.
signal":
the command was terminated by a signal;
the following number is the signal that terminated the command.
command,
os.execute returns a boolean that is true if a shell is available.
os.exit ([code [, close]])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.
close is true,
closes the Lua state before exiting.
os.getenv (varname)varname,
or nil if the variable is not defined.
os.remove (filename)os.rename (oldname, newname)oldname to newname.
If this function fails, it returns nil,
plus a string describing the error and the error code.
os.setlocale (locale [, category])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.
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.
setlocale.
os.time ([table])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.
time can be used only as an argument to
os.date and os.difftime.
os.tmpname ()io.tmpfile,
which automatically removes the file when the program ends.
6.10 – The Debug Library
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 ()cont finishes this function,
so that the caller continues its execution.
debug.debug are not lexically nested
within any function and so have no direct access to local variables.
debug.gethook ([thread])debug.sethook function).
debug.getinfo ([thread,] f [, what])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.
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.
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)local of the function at level f of the stack.
This function accesses not only explicit local variables,
but also parameters, temporaries, etc.
debug.getinfo to check whether the level is valid.)
(' (open parenthesis)
represent variables with no known names
(internal variables such as loop control variables,
and variables from chunks saved without debug information).
f may also be a function.
In that case, getlocal returns only the name of function parameters.
debug.getmetatable (value)value
or nil if it does not have a metatable.
debug.getregistry ()debug.getupvalue (f, up)up of the function f.
The function returns nil if there is no upvalue with the given index.
(' (open parenthesis)
represent variables with no known names
(variables from chunks saved without debug information).
debug.getuservalue (u)u.
If u is not a userdata,
returns nil.
debug.sethook ([thread,] hook, mask [, count])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:
c': the hook is called every time Lua calls a function;r': the hook is called every time Lua returns from a function;l': the hook is called every time Lua enters a new line of code.count different from zero,
the hook is called also after every count instructions.
debug.sethook turns off the hook.
"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)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.
debug.getlocal for more information about
variable indices and names.
debug.setmetatable (value, table)value to the given table
(which can be nil).
Returns value.
debug.setupvalue (f, up, 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)value as
the Lua value associated to the given udata.
udata must be a full userdata.
udata.
debug.traceback ([thread,] [message [, level]])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)n
from the given function.
debug.upvaluejoin (f1, n1, f2, n2)n1-th upvalue of the Lua closure f1
refer to the n2-th upvalue of the Lua closure f2.
7 – Lua Standalone
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]]
-e stat: executes string stat;-l mod: "requires" mod;-i: enters interactive mode after running script;-v: prints version information;-E: ignores environment variables;--: stops handling options;-: executes stdin as a file and stops handling 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.
-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.
-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.
-i and -E.
For instance, an invocation like
$ lua -e'a=1' -e 'print(a)' script.lua
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.)
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
arg = { [-2] = "lua", [-1] = "-la",
[0] = "b.lua",
[1] = "t1", [2] = "t2" }
$ lua -e "print(arg[1])"
-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.)
__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.
lua_close).
The script can avoid this step by
calling os.exit to terminate.
#.
Therefore, Lua scripts can be made into executable programs
by using chmod +x and the #! form,
as in
#!/usr/local/bin/lua
lua is in your PATH,
then
#!/usr/bin/env lua
8 – Incompatibilities with the Previous Version
luaconf.h).
However,
all these compatibility options will be removed in the future.
8.1 – Changes in the Language
.0
or using x = x + 0.0 to convert a variable.
(This recommendation is only for a quick fix
for an occasional incompatibility;
it is not a general guideline for good programming.
For good programming,
use floats where you need floats
and integers where you need integers.)
.0 suffix
to the result if it looks like an integer.
(For instance, the float 2.0 will be printed as 2.0,
not as 2.)
You should always use an explicit format
when you need a specific format for numbers.
8.2 – Changes in the Libraries
bit32 library has been deprecated.
It is easy to require a compatible external library or,
better yet, to replace its functions with appropriate bitwise operations.
(Keep in mind that bit32 operates on 32-bit integers,
while the bitwise operators in standard Lua operate on 64-bit integers.)
ipairs iterator now respects metamethods and
its __ipairs metamethod has been deprecated.
io.read do not have a starting '*' anymore.
For compatibility, Lua will continue to ignore this character.
atan2, cosh, sinh, tanh, pow,
frexp, and ldexp.
You can replace math.pow(x,y) with x^y;
you can replace math.atan2 with math.atan,
which now accepts one or two parameters;
you can replace math.ldexp(x,exp) with x * 2.0^exp.
For the other operations,
you can either use an external library or
implement them in Lua.
require
changed the way it handles versioned names.
Now, the version should come after the module name
(as is usual in most other tools).
For compatibility, that searcher still tries the old format
if it cannot find an open function according to the new style.
(Lua 5.2 already worked that way,
but it did not document the change.)
8.3 – Changes in the API
lua_getctx,
so lua_getctx has been removed.
Adapt your code accordingly.
lua_dump has an extra parameter, strip.
Use 0 as the value of this parameter to get the old behavior.
lua_pushunsigned, lua_tounsigned, lua_tounsignedx,
luaL_checkunsigned, luaL_optunsigned)
were deprecated.
Use their signed equivalents with a type cast.
luaL_checkint, luaL_optint, luaL_checklong, luaL_optlong)
were deprecated.
Use their equivalent over lua_Integer with a type cast
(or, when possible, use lua_Integer in your code).
9 – The Complete Syntax of Lua
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