Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ierusalimschy R.Lua 5.0 reference manual.2003.pdf
Скачиваний:
12
Добавлен:
23.08.2013
Размер:
474.82 Кб
Скачать

The line hook is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). (This event only happens while Lua is executing a Lua function.)

The count hook is called after the interpreter executes every count instructions. (This event only happens while Lua is executing a Lua function.)

A hook is disabled by setting mask to zero.

You can get the current hook, the current mask, and the current count with the next functions:

lua_Hook lua_gethook

(lua_State *L);

int

lua_gethookmask

(lua_State

*L);

int

lua_gethookcount (lua_State

*L);

Whenever a hook is called, its ar argument has its field event set to the specific event that triggered the hook. Moreover, for line events, the field currentline is also set. To get the value of any other field in ar, the hook must call lua_getinfo. For return events, event may be LUA_HOOKRET, the normal value, or LUA_HOOKTAILRET. In the latter case, Lua is simulating a return from a function that did a tail call; in this case, it is useless to call lua_getinfo.

While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls back Lua to execute a function or a chunk, that execution occurs without any calls to hooks.

5Standard Libraries

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 o cial C API and are provided as separate C modules.

Currently, Lua has the following standard libraries:

basic library;

string manipulation;

table manipulation;

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.

38

5.1Basic 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).

• error (message [, level])

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 a ect 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.

39

• getmetatable (object)

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

40

• 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 di erence 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.

• pcall (f, arg1, arg2, ...)

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 di erent 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 di erent from nil, and value is any Lua value.

41

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

• setfenv (f, table)

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.

42