5 - 标准库
The standard libraries provide useful functions that are implemented
directly through the C API. Some of these functions provide essential
services to the language (e.g., type
and getmetatable
);
others provide access to "outside" services (e.g., I/O); and others
could be implemented in Lua itself, but are quite useful or have
critical performance to deserve an implementation in C (e.g., sort
).
All libraries are implemented through the official C API and are
provided as separate C modules. Currently, Lua has the following
standard libraries:
- 基本库 basic library;
- 字符串操作 string manipulation;
- 表操作 table manipulation;
- 数学函数 (sin, log 等等)mathematical functions (sin, log, etc.);
- 输入输出 input and output;
- 操作系统机制 operating system facilities;
- 调试机制 debug facilities.
Except for the basic library, each library provides all its functions as fields of a global table or as methods of its objects.
To have access to these libraries, the C host program must first call the functions luaopen_base
(for the basic library), luaopen_string
(for the string library), luaopen_table
(for the table library), luaopen_math
(for the mathematical library), luaopen_io
(for the I/O and the Operating System libraries), and luaopen_debug
(for the debug library). These functions are declared in lualib.h
.
5.1 - 基本函数 Basic Functions
The basic library provides some core functions to Lua. If you do not
include this library in your application, you should check carefully
whether you need to provide some alternative implementation for some of
its facilities.
assert (v [, message])
Issues an error when the value of its argument v
is nil or false; otherwise, returns this value. message
is an error message; when absent, it defaults to "assertion failed!"
collectgarbage ([limit])
Sets the garbage-collection threshold to the given limit (in Kbytes)
and checks it against the byte counter. If the new threshold is smaller
than the byte counter, then Lua immediately runs the garbage collector
(see 2.9). If limit
is absent, it defaults to zero (thus forcing a garbage-collection cycle).
dofile (filename)
Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile
executes the contents of the standard input (stdin
). Returns any value returned by the chunk. In case of errors, dofile
propagates the error to its caller (that is, it does not run in protected mode).
Terminates the last protected function called and returns message
as the error message. Function error
never returns.
The level
argument specifies where the error message points the error. With level 1 (the default), the error position is where the error
function was called. Level 2 points the error to where the function that called error
was called; and so on.
_G
A global variable (not a function) that holds the global environment (that is, _G._G = _G
). Lua itself does not use this variable; changing its value does not affect any environment. (Use setfenv
to change environments.)
getfenv (f)
Returns the current environment in use by the function. f
can be a Lua function or a number, which specifies the function at that stack level: Level 1 is the function calling getfenv
. If the given function is not a Lua function, or if f
is 0, getfenv
returns the global environment. The default for f
is 1.
If the environment has a "__fenv"
field, returns the associated value, instead of the environment.
If the object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable"
field, returns the associated value. Otherwise, returns the metatable of the given object.
gcinfo ()
Returns two results: the number of Kbytes of dynamic memory that Lua
is using and the current garbage collector threshold (also in Kbytes).
ipairs (t)
Returns an iterator function, the table t
, and 0, so that the construction
for i,v in ipairs(t) do ... end
will iterate over the pairs (1,t[1]
), (2,t[2]
), ..., up to the first integer key with a nil value in the table.
loadfile (filename)
Loads a file as a Lua chunk (without running it). If there are no
errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.
loadlib (libname, funcname)
Links the program with the dynamic C library libname
. Inside this library, looks for a function funcname
and returns this function as a C function.
libname
must be the complete file name of the C library, including any eventual path and extension.
This function is not supported by ANSI C. As such, it is only
available on some platforms (Windows, Linux, Solaris, BSD, plus other
Unix systems that support the dlfcn
standard).
loadstring (string [, chunkname])
Loads a string as a Lua chunk (without running it). If there are no
errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.
The optional parameter chunkname
is the name to be used in error messages and debug information.
To load and run a given string, use the idiom
assert(loadstring(s))()
next (table [, index])
Allows a program to traverse all fields of a table. Its first
argument is a table and its second argument is an index in this table. next
returns the next index of the table and the value associated with the index. When called with nil as its second argument, next
returns the first index of the table and its associated value. When called with the last index, or with nil in an empty table, next
returns nil. If the second argument is absent, then it is interpreted as nil.
Lua has no declaration of fields; There is no difference between a field not present in a table or a field with value nil. Therefore, next
only considers fields with non-nil values. The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs
function.)
The behavior of next
is undefined if, during the traversal, you assign any value to a non-existent field in the table.
pairs (t)
Returns the next
function and the table t
(plus a nil), so that the construction
for k,v in pairs(t) do ... end
will iterate over all key-value pairs of table t
.
Calls function f
with the given arguments in protected mode. That means that any error inside f
is not propagated; instead, pcall
catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall
also returns all results from the call, after this first result. In case of any error, pcall
returns false plus the error message.
print (e1, e2, ...)
Receives any number of arguments, and prints their values in stdout
, using the tostring
function to convert them to strings. This function is not intended for
formatted output, but only as a quick way to show a value, typically
for debugging. For formatted output, use format
(see 5.3).
rawequal (v1, v2)
Checks whether v1
is equal to v2
, without invoking any metamethod. Returns a boolean.
rawget (table, index)
Gets the real value of table[index]
, without invoking any metamethod. table
must be a table; index
is any value different from nil.
rawset (table, index, value)
Sets the real value of table[index]
to value
, without invoking any metamethod. table
must be a table, index
is any value different from nil, and value
is any Lua value.
require (packagename)
Loads the given package. The function starts by looking into the table _LOADED
to determine whether packagename
is already loaded. If it is, then require
returns the value that the package returned when it was first loaded.
Otherwise, it searches a path looking for a file to load.
If the global variable LUA_PATH
is a string, this string is the path. Otherwise, require
tries the environment variable LUA_PATH
. As a last resort, it uses the predefined path "?;?.lua"
.
The path is a sequence of templates separated by semicolons. For each template, require
will change each interrogation mark in the template to packagename
, and then will try to load the resulting file name. So, for instance, if the path is
"./?.lua;./?.lc;/usr/local/?/?.lua;/lasttry"
a require "mod"
will try to load the files ./mod.lua
, ./mod.lc
, /usr/local/mod/mod.lua
, and /lasttry
, in that order.
The function stops the search as soon as it can load a file, and then it runs the file. After that, it associates, in table _LOADED
, the package name with the value that the package returned, and returns that value. If the package returns nil (or no value), require
converts this value to true. If the package returns false, require
also returns false. However, as the mark in table _LOADED
is false, any new attempt to reload the file will happen as if the package was not loaded (that is, the package will be loaded again).
If there is any error loading or running the file, or if it cannot find any file in the path, then require
signals an error.
While running a file, require
defines the global variable _REQUIREDNAME
with the package name. The package being loaded always runs within the global environment.
Sets the current environment to be used by the given function. f
can be a Lua function or a number, which specifies the function at that stack level: Level 1 is the function calling setfenv
.
As a special case, when f
is 0 setfenv
changes the global environment of the running thread.
If the original environment has a "__fenv"
field, setfenv
raises an error.
setmetatable (table, metatable)
Sets the metatable for the given table. (You cannot change the metatable of a userdata from Lua.) If metatable
is nil, removes the metatable of the given table. If the original metatable has a "__metatable"
field, raises an error.
tonumber (e [, base])
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber
returns that number; otherwise, it returns nil.
An optional argument specifies the base to interpret the
numeral. The base may be any integer between 2 and 36, inclusive. 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. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part (see 2.2.1). In other bases, only unsigned integers are accepted.
tostring (e)
Receives an argument of any type and converts it to a string in a
reasonable format. For complete control of how numbers are converted,
use format
(see 5.3).
If the metatable of e
has a "__tostring"
field, tostring
calls the corresponding value with e
as argument, and uses the result of the call as its result.
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"
, "boolean
, "table"
, "function"
, "thread"
, and "userdata"
.
unpack (list)
Returns all elements from the given list. This function is equivalent to
return list[1], list[2], ..., list[n]
except that the above code can be written only for a fixed n. The number n is the size of the list, as defined for the table.getn
function.
_VERSION
A global variable (not a function) that holds a string containing
the current interpreter version. The current content of this string is "Lua 5.0"
.
xpcall (f, err)
This function is similar to pcall
, except that you can set a new error handler.
xpcall
calls function f
in protected mode, using err
as the error handler. Any error inside f
is not propagated; instead, xpcall
catches the error, calls the err
function with the original error object, and returns a status code. Its
first result is the status code (a boolean), which is true if the call
succeeds without errors. In such case, xpcall
also returns all results from the call, after this first result. In case of any error, xpcall
returns false plus the result from err
.
5.2 - Coroutine Manipulation
The operations related to coroutines comprise a sub-library of the basic library and come inside the table coroutine
. See 2.10 for a general description of coroutines.
coroutine.create (f)
Creates a new coroutine, with body f
. f
must be a Lua function. Returns this new coroutine, an object with type "thread"
.
coroutine.resume (co, val1, ...)
Starts or continues the execution of coroutine co
. The first time you resume a coroutine, it starts running its body. The arguments val1
, ... go as the arguments to the body function. If the coroutine has yielded, resume
restarts it; the arguments val1
, ... go as the results from the yield.
If the coroutine runs without any errors, resume
returns true plus any values passed to yield
(if the coroutine yields) or any values returned by the body function (if the coroutine terminates). If there is any error, resume
returns false plus the error message.
coroutine.status (co)
Returns the status of coroutine co
, as a string: "running"
, if the coroutine is running (that is, it called status
); "suspended"
, if the coroutine is suspended in a call to yield
, or if it has not started running yet; and "dead"
if the coroutine has finished its body function, or if it has stopped with an error.
coroutine.wrap (f)
Creates a new coroutine, with body f
. f
must be a Lua function. Returns a function that resumes the coroutine
each time it is called. Any arguments passed to the function behave as
the extra arguments to resume
. Returns the same values returned by resume
, except the first boolean. In case of error, propagates the error.
coroutine.yield (val1, ...)
Suspends the execution of the calling coroutine. The coroutine
cannot be running neither a C function, nor a metamethod, nor an
iterator. Any arguments to yield
go as extra results to resume
.
5.3 - String Manipulation
This library provides generic functions for string manipulation,
such as finding and extracting substrings, and pattern matching. When
indexing a string in Lua, the first character is at position 1 (not
at 0, as in C). 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.
The string library provides all its functions inside the table string
.
string.byte (s [, i])
Returns the internal numerical code of the i
-th character of s
, or nil if the index is out of range. If i
is absent, then it is assumed to be 1. i
may be negative.
Note that numerical codes are not necessarily portable across platforms.
string.char (i1, i2, ...)
Receives 0 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 correspondent argument.
Note that numerical codes are not necessarily portable across platforms.
string.dump (function)
Returns a binary representation of the given function, so that a later loadstring
on that string returns a copy of the function. function
must be a Lua function without upvalues.
string.find (s, pattern [, init [, plain]])
Looks for the first match of pattern
in the string s
. If it finds one, then find
returns the indices of s
where this occurrence starts and ends; otherwise, it returns nil. If the pattern specifies captures (see string.gsub
below), the captured strings are returned as extra results. A third, optional numerical argument init
specifies where to start the search; it may be negative and its default value is 1. 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 too.
string.len (s)
Receives a string and returns its length. The empty string ""
has length 0. Embedded zeros are counted, so "a/000b/000c"
has length 5.
string.lower (s)
Receives a string and returns a copy of that string with all
uppercase letters changed to lowercase. All other characters are left
unchanged. The definition of what is an uppercase letter depends on the
current locale.
string.rep (s, n)
Returns a string that is the concatenation of n
copies of the string s
.
string.sub (s, i [, j])
Returns the substring of s
that starts at i
and continues until j
; i
and j
may 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
.
string.upper (s)
Receives a string and returns a copy of that string with all
lowercase letters changed to uppercase. All other characters are left
unchanged. The definition of what is a lowercase letter depends on the
current locale.
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 printf
family of standard C functions. The only differences are that the options/modifiers *
, l
, L
, n
, p
, and h
are not supported, and there is an extra option, q
. The q
option formats a string in a form suitable to be safely read back by
the Lua interpreter: The string is written between double quotes, and
all double quotes, newlines, and backslashes in the string are
correctly escaped when written. For instance, the call
string.format('%q', 'a string with "quotes" and /n new line')
will produce the string:
"a string with /"quotes/" and /
new line"
The options c
, d
, E
, e
, f
, g
, G
, i
, o
, u
, X
, and x
all expect a number as argument, whereas q
and s
expect a string. The *
modifier can be simulated by building the appropriate format string. For example, "%*g"
can be simulated with "%"..width.."g"
.
String values to be formatted with %s
cannot contain embedded zeros.
string.gfind (s, pat)
Returns an iterator function that, each time it is called, returns the next captures from pattern pat
over string s
.
If pat
specifies no captures, then the whole match is produced in each call.
As an example, the following loop
s = "hello world from Lua"
for w in string.gfind(s, "%a+") do
print(w)
end
will iterate over all the words from string s
, printing one per line. The next example collects all pairs key=value
from the given string into a table:
t = {}
s = "from=world, to=Lua"
for k, v in string.gfind(s, "(%w+)=(%w+)") do
t[k] = v
end
string.gsub (s, pat, repl [, n])
Returns a copy of s
in which all occurrences of the pattern pat
have been replaced by a replacement string specified by repl
. gsub
also returns, as a second value, the total number of substitutions made.
If repl
is a string, then its value is used for replacement. Any sequence in repl
of the form %
n, with n between 1 and 9, stands for the value of the n-th captured substring (see below).
If repl
is a function, then this function is called
every time a match occurs, with all captured substrings passed as
arguments, in order; if the pattern specifies no captures, then the
whole match is passed as a sole argument. If the value returned by this
function is a string, then it is used as the replacement string;
otherwise, the replacement string is the empty string.
The optional last parameter n
limits the maximum number of substitutions to occur. For instance, when n
is 1 only the first occurrence of pat
is replaced.
Here are some examples:
x = string.gsub("hello world", "(%w+)", "%1 %1")
--> x="hello hello world world"
x = string.gsub("hello world", "(%w+)", "%1 %1", 1)
--> x="hello hello world"
x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"
x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
return loadstring(s)()
end)
--> x="4+5 = 9"
local t = {name="lua", version="5.0"}
x = string.gsub("$name_$version.tar.gz", "%$(%w+)", function (v)
return t[v]
end)
--> x="lua_5.0.tar.gz"
Patterns
A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:
- x (where x is not one of the magic characters
^$()%.[]*+-?
) --- represents the character x itself.
.
--- (a dot) represents all characters.
%a
--- represents all letters.
%c
--- represents all control characters.
%d
--- represents all digits.
%l
--- represents all lowercase letters.
%p
--- represents all punctuation characters.
%s
--- represents all space characters.
%u
--- represents all uppercase letters.
%w
--- represents all alphanumeric characters.
%x
--- represents all hexadecimal digits.
%z
--- represents the character with representation 0.
%x
(where x is any non-alphanumeric character) --- represents the character x. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a `%
′ when used to represent itself in a pattern.
-
[set]
--- represents the class which is the union of all characters in set. A range of characters may be specified by separating the end characters of the range with a `-
′. All classes %
x described above may also be used as components in set. All other characters in set represent themselves. For example, [%w_]
(or [_%w]
) represents all alphanumeric characters plus the underscore, [0-7]
represents the octal digits, and [0-7%l%-]
represents the octal digits plus the lowercase letters plus the `-
′ character.
The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z]
or [a-%%]
have no meaning.
-
[^set]
--- represents the complement of set, where set is interpreted as above.
For all classes represented by single letters (%a
, %c
, etc.), the corresponding uppercase letter represents the complement of the class. For instance, %S
represents all non-space characters.
The definitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z]
may not be equivalent to %l
. The second form should be preferred for portability.
A pattern item may be
- a single character class, which matches any single character in the class;
- a single character class followed by `
*
′, which
matches 0 or more repetitions of characters in the class. These
repetition items will always match the longest possible sequence; - a single character class followed by `
+
′, which
matches 1 or more repetitions of characters in the class. These
repetition items will always match the longest possible sequence; - a single character class followed by `
-
′, which also matches 0 or more repetitions of characters in the class. Unlike `*
′, these repetition items will always match the shortest possible sequence;
- a single character class followed by `
?
′, which matches 0 or 1 occurrence of a character in the class;
%n
, for n between 1 and 9; such item matches a substring equal to the n-th captured string (see below);
%bxy
, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item %b()
matches s with balanced parentheses.
A pattern is a sequence of pattern items. A `^
′ at the beginning of a pattern anchors the match at the beginning of the subject string. A `$
′ at the end of a pattern anchors the match at the end of the subject string. At other positions, `^
′ and `$
′ have no special meaning and represent themselves.
A pattern may contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))"
, the part of the string matching "a*(.)%w(%s*)"
is stored as the first capture (and therefore has number 1); the character matching .
is captured with number 2, and the part matching %s*
has number 3.
As a special case, the empty capture ()
captures the current string position (a number). For instance, if we apply the pattern "()aa()"
on the string "flaaap"
, there will be two captures: 3 and 5.
A pattern cannot contain embedded zeros. Use %z
instead.
5.4 - Table Manipulation
This library provides generic functions for table manipulation. It provides all its functions inside the table table
.
Most functions in the table library assume that the table
represents an array or a list. For those functions, an important
concept is the size of the array. There are three ways to specify that size:
- the field
"n"
--- When the table has a field "n"
with a numerical value, that value is assumed as its size.
setn
--- You can call the table.setn
function to explicitly set the size of a table.
- implicit size --- Otherwise, the size of the object is one less the first integer index with a nil value.
For more details, see the descriptions of the table.getn
and table.setn
functions.
table.concat (table [, sep [, i [, j]]])
Returns table[i]..sep..table[i+1] ... sep..table[j]
. The default value for sep
is the empty string, the default for i
is 1, and the default for j
is the size of the table. If i
is greater than j
, returns the empty string.
table.foreach (table, f)
Executes the given f
over all elements of table
. For each element, f
is called with the index and respective value as arguments. If f
returns a non-nil value, then the loop is broken, and this value is returned as the final value of foreach
.
See the next
function for extra information about table traversals.
table.foreachi (table, f)
Executes the given f
over the numerical indices of table
. For each index, f
is called with the index and respective value as arguments. Indices are visited in sequential order, from 1 to n
, where n
is the size of the table (see 5.4). If f
returns a non-nil value, then the loop is broken and this value is returned as the result of foreachi
.
Returns the size of a table, when seen as a list. If the table has an n
field with a numeric value, this value is the size of the table. Otherwise, if there was a previous call to table.setn
over this table, the respective value is returned. Otherwise, the size is one less the first integer index with a nil value.
table.sort (table [, comp])
Sorts table elements in a given order, in-place, from table[1]
to table[n]
, where n
is the size of the table (see 5.4). If comp
is given, then it must be a function that receives two table elements,
and returns true when the first is less than the second (so that not comp(a[i+1],a[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.insert (table, [pos,] value)
Inserts element value
at position pos
in table
, shifting up other elements to open space, if necessary. The default value for pos
is n+1
, where n
is the size of the table (see 5.4), so that a call table.insert(t,x)
inserts x
at the end of table t
. This function also updates the size of the table by calling table.setn(table, n+1)
.
table.remove (table [, pos])
Removes from table
the element at position pos
,
shifting down other elements to close the space, if necessary. Returns
the value of the removed element. The default value for pos
is n
, where n
is the size of the table (see 5.4), so that a call table.remove(t)
removes the last element of table t
. This function also updates the size of the table by calling table.setn(table, n-1)
.
table.setn (table, n)
Updates the size of a table. If the table has a field "n"
with a numerical value, that value is changed to the given n
. Otherwise, it updates an internal state so that subsequent calls to table.getn(table)
return n
.
5.5 - Mathematical Functions
This library is an interface to most of the functions of the
standard C math library. (Some have slightly different names.) It
provides all its functions inside the table math
. In addition, it registers the global __pow
for the binary exponentiation operator ^
, so that x^y
returns xy. The library provides the following functions:
math.abs math.acos math.asin math.atan math.atan2
math.ceil math.cos math.deg math.exp math.floor
math.log math.log10 math.max math.min math.mod
math.pow math.rad math.sin math.sqrt math.tan
math.frexp math.ldexp math.random math.randomseed
plus a variable math.pi
. Most of them are only
interfaces to the corresponding functions in the C library. All
trigonometric functions work in radians (previous versions of Lua used
degrees). The functions math.deg
and math.rad
convert between radians and degrees.
The function math.max
returns the maximum value of its numeric arguments. Similarly, math.min
computes the minimum. Both can be used with 1, 2, or more arguments.
The functions math.random
and math.randomseed
are interfaces to the simple random generator functions rand
and srand
that are provided by ANSI C. (No guarantees can be given for their statistical properties.) When called without arguments, math.random
returns a pseudo-random real number in the range [0,1). When called with a number n, math.random
returns a pseudo-random integer in the range [1,n]. When called with two arguments, l and u, math.random
returns a pseudo-random integer in the range [l,u]. The math.randomseed
function sets a "seed" for the pseudo-random generator: Equal seeds produce equal sequences of numbers.
5.6 - Input and Output Facilities
The I/O library provides two different styles for file manipulation.
The first one uses implicit file descriptors, that is, there are
operations to set a default input file and a default output file, and
all input/output operations are over those default files. The second
style uses explicit file descriptors.
When using implicit file descriptors, all operations are supplied by table io
. When using explicit file descriptors, the operation io.open
returns a file descriptor and then all operations are supplied as methods by the file descriptor.
The table io
also provides three predefined file descriptors with their usual meanings from C: io.stdin
, io.stdout
, and io.stderr
.
A file handle is a userdata containing the file stream (FILE*
), with a distinctive metatable created by the I/O library.
Unless otherwise stated, all I/O functions return nil on failure (plus an error message as a second result) and some value different from nil on success.
io.close ([file])
Equivalent to file:close
. Without a file
, closes the default output file.
io.flush ()
Equivalent to file:flush
over the default output file.
io.input ([file])
When called with a file name, it opens the named file (in text
mode), and sets its handle as the default input file. When called with
a file handle, it simply sets that file handle as the default input
file. When called without parameters, it returns the current default
input file.
In case of errors this function raises the error, instead of returning an error code.
io.lines ([filename])
Opens the given file name in read mode and returns an iterator
function that, each time it is called, returns a new line from the
file. Therefore, the construction
for line in io.lines(filename) do ... end
will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
The call io.lines()
(without a file name) is equivalent to io.input():lines()
, that is, it iterates over the lines of the default input file.
io.open (filename [, mode])
This function opens a file, in the mode specified in the string mode
. It returns a new file handle, or, in case of errors, nil plus an error message.
The mode
string can be any of the following:
- "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.
The mode
string may also have a b
at the
end, which is needed in some systems to open the file in binary mode.
This string is exactly what is used in the standard C function fopen
.
io.output ([file])
Similar to io.input
, but operates over the default output file.
io.read (format1, ...)
Equivalent to io.input():read
.
io.tmpfile ()
Returns a handle for a temporary file. This file is open in update mode and it is automatically removed when the program ends.
io.type (obj)
Checks whether obj
is a valid file handle. Returns the string "file"
if obj
is an open file handle, "closed file"
if obj
is a closed file handle, and nil if obj
is not a file handle.
io.write (value1, ...)
Equivalent to io.output():write
.
file:close ()
Closes file
.
file:flush ()
Saves any written data to file
.
file:lines ()
Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction
for line in file:lines() do ... end
will iterate over all lines of the file. (Unlike io.lines
, this function does not close the file when the loop ends.)
file:read (format1, ...)
Reads the file file
, according to the given formats,
which specify what to read. For each format, the function returns a
string (or a number) with the characters read, or nil if it
cannot read data with the specified format. When called without
formats, it uses a default format that reads the entire next line (see
below).
The available formats are
- "*n" reads a number; this is the only format that returns a number instead of a string.
- "*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.
- number reads a string with up to that number of characters, returning nil on end of file. If number is zero, it reads nothing and returns an empty string, or nil on end of file.
file:seek ([whence] [, offset])
Sets and gets the file position, measured from the beginning of the file, to the position given by offset
plus a base specified by the string whence
, as follows:
- "set" base is position 0 (beginning of the file);
- "cur" base is current position;
- "end" base is end of file;
In case of success, function seek
returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.
The default value for whence
is "cur"
, and for offset
is 0. Therefore, the call file:seek()
returns the current file position, without changing it; the call file:seek("set")
sets the position to the beginning of the file (and returns 0); and the call file:seek("end")
sets the position to the end of the file, and returns its size.
file:write (value1, ...)
Writes the value of each of its arguments to the filehandle file
. The arguments must be strings or numbers. To write other values, use tostring
or string.format
before write
.
5.7 - Operating System Facilities
This library is implemented through table os
.
os.clock ()
Returns an approximation of the amount of CPU time used by the program, in seconds.
os.date ([format [, time]])
Returns a string or a table containing date and time, formatted according to the given string format
.
If the time
argument is present, this is the time to be formatted (see the os.time
function for a description of this value). Otherwise, date
formats the current time.
If format
starts with `!
′, then the date is formatted in Coordinated Universal Time. After that optional character, if format
is *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).
If format
is not *t
, then date
returns the date as a string, formatted according to the same rules as the C function strftime
.
When called without arguments, date
returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date()
is equivalent to os.date("%c")
).
os.difftime (t2, t1)
Returns the number of seconds from time t1
to time t2
. In Posix, Windows, and some other systems, this value is exactly t2
-t1
.
os.execute (command)
This function is equivalent to the C function system
. It passes command
to be executed by an operating system shell. It returns a status code, which is system-dependent.
os.exit ([code])
Calls the C function exit
, with an optional code
, to terminate the host program. The default value for code
is the success code.
os.getenv (varname)
Returns the value of the process environment variable varname
, or nil if the variable is not defined.
os.remove (filename)
Deletes the file with the given name. If this function fails, it returns nil, plus a string describing the error.
os.rename (oldname, newname)
Renames file named oldname
to newname
. If this function fails, it returns nil, plus a string describing the error.
os.setlocale (locale [, category])
Sets the current locale of the program. locale
is a 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.
os.time ([table])
Returns the current time when called without arguments, or a time
representing the date and time specified by the given table. This table
must have fields year
, month
, and day
, and may have fields hour
, min
, sec
, and isdst
(for a description of these fields, see the os.date
function).
The returned value is a number, whose meaning depends on your
system. In Posix, Windows, and some other systems, this number counts
the number of seconds since some given start time (the "epoch"). In
other systems, the meaning is not specified, and the number returned by
time
can be used only as an argument to date
and difftime
.
os.tmpname ()
Returns a string with a file name that can be used for a temporary
file. The file must be explicitly opened before its use and removed
when no longer needed.
This function is equivalent to the tmpnam
C function, and many people (and even some compilers!) advise against
its use, because between the time you call this function and the time
you open the file, it is possible for another process to create a file
with the same name.
5.8 - The Reflexive Debug Interface
The debug
library provides the functionality of the
debug interface to Lua programs. You should exert care when using this
library. The functions provided here should be used exclusively for
debugging and similar tasks, such as profiling. Please resist the
temptation to use them as a usual programming tool: They can be very
slow. Moreover, setlocal
and getlocal
violate the privacy of local variables and therefore can compromise some otherwise secure code.
All functions in this library are provided inside a debug
table.
debug.debug ()
Enters an interactive mode with the user, running each string that
the user enters. Using simple commands and other debug facilities, the
user can inspect global and local variables, change their values,
evaluate s, and so on. A line containing only the word cont
finishes this function, so that the caller continues its execution.
Note that commands for debug.debug
are not lexically nested with any function, so they have no direct access to local variables.
debug.gethook ()
Returns the current hook settings, as three values: the current hook
function, the current hook mask, and the current hook count (as set by
the debug.sethook
function).
debug.getinfo (function [, what])
This function returns a table with information about a function. You
can give the function directly, or you can give a number as the value
of function
, which means the function running at level function
of the call stack: Level 0 is the current function (getinfo
itself); level 1 is the function that called getinfo
; and so on. If function
is a number larger than the number of active functions, then getinfo
returns nil.
The returned table contains all the fields returned by lua_getinfo
, with the string what
describing which fields to fill in. The default for what
is to get all information available. If present, the option `f
′ adds a field named func
with the function itself.
For instance, the debug.getinfo(1,"n").name
returns the name of the current function, if a reasonable name can be found, and debug.getinfo(print)
returns a table with all available information about the print
function.
debug.getlocal (level, local)
This function returns the name and the value of the local variable with index local
of the function at level level
of the stack. (The first parameter or local variable has index 1, and
so on, until the last active local variable.) 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 debug.getinfo
to check whether the level is valid.)
debug.getupvalue (func, up)
This function returns the name and the value of the upvalue with index up
of the function func
. The function returns nil if there is no upvalue with the given index.
debug.setlocal (level, local, value)
This function assigns the value value
to the local variable with index local
of the function at level level
of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level
out of range. (You can call getinfo
to check whether the level is valid.)
debug.setupvalue (func, up, value)
This function assigns the value value
to the upvalue with index up
of the function func
. The function returns nil if there is no upvalue with the given index.
debug.sethook (hook, mask [, count])
Sets the given function as a hook. The string mask
and the number count
describe when the hook will be called. The string mask may have 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.
With a count
different from zero, the hook is called after every count
instructions.
When called without arguments, the debug.sethook
function turns off the hook.
When the hook is called, its first parameter is always a string describing the event that triggered its call: "call"
, "return"
(or "tail return"
), "line"
, and "count"
. Moreover, for line events, it also gets as its second parameter the new line number. 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), unless the event is "tail return"
. In this case, Lua is only simulating the return, and a call to getinfo
will return invalid data.
debug.traceback ([message])
Returns a string with a traceback of the call stack. An optional message
string is appended at the beginning of the traceback. This function is typically used with xpcall
to produce better error messages.