From 22912c77c80f8de8f7accd3319c726f7c5349fd3 Mon Sep 17 00:00:00 2001 From: Lua Team Date: Fri, 8 Jan 2010 12:00:00 +0000 Subject: Lua 5.2.0-work1 --- doc/manual.html | 1615 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 1151 insertions(+), 464 deletions(-) (limited to 'doc/manual.html') diff --git a/doc/manual.html b/doc/manual.html index f46f17c8..83d2bb09 100644 --- a/doc/manual.html +++ b/doc/manual.html @@ -1,39 +1,31 @@ - + -Lua 5.1 Reference Manual - - - +Lua 5.2 Reference Manual + - +

- -Lua 5.1 Reference Manual +[Lua logo] +Lua 5.2 Reference Manual

by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes

-Copyright © 2006-2008 Lua.org, PUC-Rio. -Freely available under the terms of the -Lua license. +Copyright +© 2010 Lua.org, PUC-Rio. All rights reserved.


-

- -contents -· -index

- + @@ -110,6 +102,13 @@ at the end of this manual.

2.1 - Lexical Conventions

+

+Lua is a free-form language. +It ignores spaces (including new lines) and comments +between lexical elements (tokens), +except as delimiters between names and keywords. + +

Names (also called identifiers) @@ -117,9 +116,6 @@ in Lua can be any string of letters, digits, and underscores, not beginning with a digit. This coincides with the definition of names in most languages. -(The definition of letter depends on the current locale: -any character considered alphabetic by the current locale -can be used in an identifier.) Identifiers are used to name variables and table fields. @@ -192,10 +188,17 @@ A closing long bracket is defined similarly; for instance, a closing long bracket of level 4 is written as ]====]. A long string 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 proper 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. -They can contain anything except a closing bracket of the proper 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. +You should not use long strings for non-text data; +Use instead a regular quoted literal with explicit escape sequences +for control characters.

@@ -429,20 +432,6 @@ The syntax var.Name is just syntactic sugar for All global variables live as fields in ordinary Lua tables, called environment tables or simply environments (see §2.9). -Each function has its own reference to an environment, -so that all global variables in this function -will refer to this environment table. -When a function is created, -it inherits the environment from the function that created it. -To get the environment table of a Lua function, -you call getfenv. -To replace it, -you call setfenv. -(You can only manipulate the environment of C functions -through the debug library; (see §5.9).) - - -

An access to a global variable x is equivalent to _env.x, which in turn is equivalent to @@ -450,7 +439,7 @@ which in turn is equivalent to

      gettable_event(_env, "x")
 

-where _env is the environment of the running function. +where _env is the current environment (see §2.9). (See §2.8 for a complete description of the gettable_event function. This function is not defined or callable in Lua. @@ -862,6 +851,43 @@ The visibility rules for local variables are explained in §2 +

2.4.8 - Lexical Environments

+ +

+A lexical environment defines a new current environment (see §2.9) +for the code inside its block: + +

+	stat ::= in exp do block end
+

+That is, a lexical environment changes the +table used to resolve all accesses +to global (free) variables inside a block. + + +

+Inside a lexical environment, +the result of exp becomes the current environment. +Expression exp is evaluated only once in the beginning of +the statement and it is stored in a hidden local variable named +(environment). +Then, any global variable +(that is, a variable not declared as a local) +var inside block is accessed as +(environment).var. +Moreover, functions defined inside the block also use the +current environment as their environments (see §2.9). + + +

+A lexical environment does not shadow local declarations. +That is, any local variable that is visible just before +a lexical environment is still visible inside the environment. + + + + +

2.5 - Expressions

@@ -1078,7 +1104,7 @@ Otherwise, the "concat" metamethod is called (see §2.8).

2.5.5 - The Length Operator

-The length operator is denoted by the unary operator #. +The length operator is denoted by the unary prefix operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte). @@ -1089,7 +1115,8 @@ The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. -For a regular array, with non-nil values from 1 to a given n, +For a regular array, where all non-nil values +have keys from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" @@ -1100,6 +1127,11 @@ directly precedes a nil value the array). +

+A program can modify the behavior of the length operator for +any value but strings through metamethods (see §2.8). + + @@ -1237,7 +1269,7 @@ that is, the argument list is a single literal string.

-As an exception to the free-format syntax of Lua, +As an exception to the free-form character of Lua, you cannot put a line break before the '(' in a function call. This restriction avoids some ambiguities in the language. If you write @@ -1247,7 +1279,8 @@ If you write (g).x(a)

Lua would see that as a single statement, a = f(g).x(a). -So, if you want two statements, you must add a semi-colon between them. +In this case, if you want two statements, +you must add a semi-colon between them. If you actually want to call f, you must remove the line break before (g). @@ -1557,6 +1590,8 @@ Tables and full userdata have individual metatables Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc. +By default, a value has no metatable, +but the string library sets a metatable for the string type (see §5.4).

@@ -1734,14 +1769,13 @@ the # operation. function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length - elseif type(op) == "table" then - return #op -- primitive table length else local h = metatable(op).__len if h then - -- call the handler with the operand - return (h(op)) - else -- no handler available: default behavior + return (h(op)) -- call handler with the operand + elseif type(op) == "table" then + return #op -- primitive table length + else -- no handler available: error error(···) end end @@ -1923,23 +1957,24 @@ called when Lua calls a value.

2.9 - Environments

-Besides metatables, -objects of types thread, function, and userdata -have another table associated with them, -called their environment. +Each function and userdata in Lua +has a table associated with it, +called its environment. Like metatables, environments are regular tables and multiple objects can share the same environment. +>From Lua, +you can manipulate the environment of an object +only through the debug library (see §5.10).

-Threads are created sharing the environment of the creating thread. Userdata and C functions are created sharing the environment of the creating C function. Non-nested Lua functions (created by loadfile, loadstring or load) -are created sharing the environment of the creating thread. -Nested Lua functions are created sharing the environment of -the creating Lua function. +are created sharing the global environment. +Nested Lua functions are created sharing the current environment +of where it is defined.

@@ -1948,14 +1983,6 @@ It is only a convenience feature for programmers to associate a table to a userdata. -

-Environments associated with threads are called -global environments. -They are used as the default environment for threads and -non-nested Lua functions created by the thread -and can be directly accessed by C code (see §3.3). - -

The environment associated with a C function can be directly accessed by C code (see §3.3). @@ -1964,20 +1991,15 @@ and userdata created by the function.

-Environments associated with Lua functions are used to resolve -all accesses to global variables within the function (see §2.3). -They are used as the default environment for nested Lua functions -created by the function. - - -

-You can change the environment of a Lua function or the -running thread by calling setfenv. -You can get the environment of a Lua function or the running thread -by calling getfenv. -To manipulate the environment of other objects -(userdata, C functions, other threads) you must -use the C API. +The environment associated with a Lua function is used as the +current environment of all code in the function outside +a lexical environment (see §2.4.8). +A lexical environment changes the +current environment inside its scope. +In any case, +the current environment is the table +Lua uses to resolve global variables and to initialize +the environment of nested functions. @@ -2029,6 +2051,16 @@ The default, 200, means that the collector runs at "twice" the speed of memory allocation. +

+If you set the step multiplier to a very large number +(such as 2^30), +the collector behaves like a stop-the-world collector. +If you then set the pause to 200, +the collector behaves as in old Lua versions, +doing a complete collection every time Lua doubles its +memory usage. + +

You can change these numbers by calling lua_gc in C or collectgarbage in Lua. @@ -2106,6 +2138,28 @@ If __mode contains 'v', the values in the table are weak. +

+Userdata with finalizers has a special behavior in weak tables. +When a userdata is a value in a weak table, +it is removed from the table the first time it is collected, +before running its finalizer. +When it is a key, however, +it is removed from the table only when it is really freed, +after running its finalizer. +This behavior allows the finalizer to access values +associated with the userdata through weak tables. + + +

+A table with weak keys and strong values +is also called an ephemeron table. +In an ephemeron table, +a value is considered reachable only if its key is reachable. +In particular, +if the only reference to a key comes from its value, +the pair is removed. + +

After you use a table as a metatable, you should not change the value of its __mode field. @@ -2309,7 +2363,7 @@ you are responsible for ensuring consistency. In particular, you are responsible for controlling stack overflow. You can use the function lua_checkstack -to grow the stack size. +to ensure that the stack has extra slots when pushing new elements.

@@ -2320,10 +2374,19 @@ so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack. +

+When you call a Lua function +without a fixed number of results (see lua_call), +Lua ensures that the stack has enough size for all results, +but it does not ensure any extra space. +So, before pushing anything in the stack after such a call +you should use lua_checkstack. + +

Most query functions accept as indices any value inside the available stack space, that is, indices up to the maximum stack size -you have set through lua_checkstack. +that you have set through lua_checkstack. Such indices are called acceptable indices. More formally, we define an acceptable index as follows: @@ -2342,8 +2405,7 @@ Note that 0 is never an acceptable index.

Unless otherwise noted, -any function that accepts valid indices can also be called with -pseudo-indices, +any function that accepts valid indices also accepts pseudo-indices, which represent some Lua values that are accessible to C code but which are not in the stack. Pseudo-indices are used to access the thread environment, @@ -2353,8 +2415,6 @@ and the upvalues of a C function (see §3.4).

-The thread environment (where global variables live) is -always at pseudo-index LUA_GLOBALSINDEX. The environment of the running C function is always at pseudo-index LUA_ENVIRONINDEX. @@ -2365,7 +2425,7 @@ you can use regular table operations over an environment table. For instance, to access the value of a global variable, do

-     lua_getfield(L, LUA_GLOBALSINDEX, varname);
+     lua_getfield(L, LUA_ENVIRONINDEX, varname);
 
@@ -2416,9 +2476,52 @@ or a light userdata with the address of a C object in your code.

The integer keys in the registry are used by the reference mechanism, implemented by the auxiliary library, -and therefore should not be used for other purposes. +and by some predefined values. +Therefore, integer keys should not be used for other purposes. + + +

+When you create a new Lua state, +its registry comes with some predefined values. +These predefined values are indexed with integer keys +defined as constants in lua.h. +The following constants are defined: + +

+ @@ -2429,7 +2532,7 @@ Internally, Lua uses the C longjmp facility to handle errors. (You can also choose to use exceptions if you use C++; see file luaconf.h.) When Lua faces any error -(such as memory allocation errors, type errors, syntax errors, +(such as a memory allocation error, type errors, syntax errors, and runtime errors) it raises an error; that is, it does a long jump. @@ -2438,6 +2541,15 @@ to set a recover point; any error jumps to the most recent active recover point. +

+If an error happens outside any protected environment, +Lua calls a panic function (see lua_atpanic) +and then calls abort, +thus exiting the host application. +Your panic function can avoid this exit by +never returning (e.g., doing a long jump). + +

Most functions in the API can throw an error, for instance due to a memory allocation error. @@ -2452,7 +2564,75 @@ Inside a C function you can throw an error by calling -

3.7 - Functions and Types

+

3.7 - Handling Yields in C

+ +

+Internally, Lua uses the C longjmp facility to yield a coroutine. +Therefore, if a function foo calls an API function +and this API function yields +(directly or indirectly by calling another function that yields), +Lua cannot return to foo any more, +because the longjmp removes its frame from the C stack. + + +

+To avoid this kind of problem, +Lua raises an error whenever it tries to yield accross an API call, +except for three functions: +lua_yieldk, lua_callk, and lua_pcallk. +All those functions receive a continuation function +(as a parameter called k) to continue execution after an yield. + + +

+To explain continuations, +let us set some terminology. +We have a C function called from Lua which we will call +the original function. +This original function may call one of those three functions in the C API, +which we will call the callee function, +that may yield the current thread. +(This will happen when the callee function is lua_yieldk, +or when the callee function is either lua_callk or lua_pcallk +and the function called by them yields.) + + +

+Suppose the running thread yields while executing the callee function. +After the thread resumes, +it eventually will finish running the callee function. +However, +the callee function cannot return to the original function, +because its frame in the C stack was destroyed by the yield. +Instead, Lua calls a continuation function, +which was given as an argument to the callee function. +As the name implies, +the continuation function should continue the task +of the original function. + + +

+Lua treats the continuation function as if it was the original function. +The continuation function receives the same Lua stack +from the original function, +in the same state it would be if the callee function had returned. +(For instance, +after a lua_callk the function and its arguments are +removed from the stack and replaced by the results from the call.) +It also has the same upvalues. +Whatever it returns is handled by Lua as if it was the return +of the original function. + + +

+The only difference in the Lua state between the original function +and its continuation is the result of a call to lua_getctx. + + + + + +

3.8 - Functions and Types

Here we list all functions and types from the C API in @@ -2498,18 +2678,48 @@ but not exactly the same. Its arguments are ud, an opaque pointer passed to lua_newstate; ptr, a pointer to the block being allocated/reallocated/freed; -osize, the original size of the block; +osize, the original size of the block or some code about what +is being allocated; nsize, the new size of the block. -ptr is NULL if and only if osize is zero. -When nsize is zero, the allocator must return NULL; -if osize is not zero, -it should free the block pointed to by ptr. -When nsize is not zero, the allocator returns NULL -if and only if it cannot fill the request. -When nsize is not zero and osize is zero, -the allocator should behave like malloc. -When nsize and osize are not zero, + + +

+When ptr is not NULL, +osize is the previous size of the block +pointed by ptr, +that is, the size given when it was allocated or reallocated. + + +

+When ptr is NULL, +osize codes the kind of object that Lua is allocating. +osize is any of +LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, +LUA_TUSERDATA, or LUA_TTHREAD when (and only when) +Lua is creating a new object of that type. +When osize is some other value, +Lua is allocating memory for something else. + + +

+Lua assumes the following behavior from the allocator function: + + +

+When nsize is zero: +if ptr is not NULL, +the allocator should free the block pointed to by ptr. +Anyway, the allocator must return NULL. + + +

+When nsize is not zero: +if ptr is NULL, +the allocator should behave like malloc; +when ptr is not NULL, the allocator behaves like realloc. +The allocator returns NULL +if and only if it cannot fill the request. Lua assumes that the allocator never fails when osize >= nsize. @@ -2534,6 +2744,9 @@ This code assumes that free(NULL) has no effect and that realloc(NULL, size) is equivalent to malloc(size). ANSI C ensures both behaviors. +It also assumes that realloc does not fail when shrinking a block. +(ANSI C does not ensure this behavior, +but it seems a safe assumption.) @@ -2544,20 +2757,14 @@ ANSI C ensures both behaviors.

lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);

-Sets a new panic function and returns the old one. +Sets a new panic function and returns the old one (see §3.6).

-If an error happens outside any protected environment, -Lua calls a panic function -and then calls exit(EXIT_FAILURE), -thus exiting the host application. -Your panic function can avoid this exit by -never returning (e.g., doing a long jump). - - -

-The panic function can access the error message at the top of the stack. +The panic function should not try to run anything on the failed Lua state. +However, it can still use the debug API (see §3.9) +to gather information about the state. +In particular, the error message is at the top of the stack. @@ -2606,14 +2813,14 @@ equivalent to this Lua code: Here it is in C:

-     lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
+     lua_getfield(L, LUA_ENVIRONINDEX, "f"); /* function to be called */
      lua_pushstring(L, "how");                        /* 1st argument */
-     lua_getfield(L, LUA_GLOBALSINDEX, "t");   /* table to be indexed */
+     lua_getfield(L, LUA_ENVIRONINDEX, "t");   /* table to be indexed */
      lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
      lua_remove(L, -2);                  /* remove 't' from the stack */
      lua_pushinteger(L, 14);                          /* 3rd argument */
      lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
-     lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global 'a' */
+     lua_setfield(L, LUA_ENVIRONINDEX, "a");        /* set global 'a' */
 

Note that the code above is "balanced": at its end, the stack is back to its original configuration. @@ -2623,6 +2830,19 @@ This is considered good programming practice. +


lua_callk

+[-(nargs + 1), +nresults, e] +

void lua_callk (lua_State *L, int nargs, int nresults,
+                          int ctx, lua_CFunction k);
+ +

+This function behaves exactly like lua_call, +but allows the called function to yield (see §3.7). + + + + +


lua_CFunction

typedef int (*lua_CFunction) (lua_State *L);
@@ -2675,12 +2895,15 @@ of numerical arguments and returns their average and sum:

lua_checkstack

-[-0, +0, m] +[-0, +0, -]

int lua_checkstack (lua_State *L, int extra);

Ensures that there are at least extra free stack slots in the stack. -It returns false if it cannot grow the stack to that size. +It returns false if it cannot grant the request, +because it would cause the stack to be larger than a fixed maximum size +(typically at least a few thousand elements) or +because it cannot allocate memory for the new stack size. This function never shrinks the stack; if the stack is already larger than the new size, it is left unchanged. @@ -2708,6 +2931,33 @@ to avoid growing too large. +


lua_compare

+[-0, +0, e] +

int lua_compare (lua_State *L, int index1, int index2, int op);
+ +

+Returns 1 if the value at acceptable index index1 satisfies op +when compared with the value at acceptable index index2, +following the semantics of the corresponding Lua operator +(that is, may call metamethods). +Otherwise returns 0. +Also returns 0 if any of the indices is non valid. + + +

+The value of op must be one of the following constants: + +

+ + + +

lua_concat

[-n, +1, e]

void lua_concat (lua_State *L, int n);
@@ -2725,19 +2975,15 @@ Concatenation is performed following the usual semantics of Lua -

lua_cpcall

-[-0, +(0|1), -] -

int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
+

lua_copy

+[-0, +0, -] +

void lua_copy (lua_State *L, int fromidx, int toidx);

-Calls the C function func in protected mode. -func starts with only one element in its stack, -a light userdata containing ud. -In case of errors, -lua_cpcall returns the same error codes as lua_pcall, -plus the error object on the top of the stack; -otherwise, it returns zero, and does not change the stack. -All values returned by func are discarded. +Moves the element at the valid index fromidx +into the valid index toidx +without shifting any element +(therefore replacing the value at that position). @@ -2788,22 +3034,6 @@ This function does not pop the Lua function from the stack. -


lua_equal

-[-0, +0, e] -

int lua_equal (lua_State *L, int index1, int index2);
- -

-Returns 1 if the two values in acceptable indices index1 and -index2 are equal, -following the semantics of the Lua == operator -(that is, may call metamethods). -Otherwise returns 0. -Also returns 0 if any of the indices is non valid. - - - - -


lua_error

[-1, +0, v]

int lua_error (lua_State *L);
@@ -2877,6 +3107,11 @@ the collector (see §2.10). The function returns the previous value of the step multiplier. +
  • LUA_GCISRUNNING: +returns a boolean that tells whether the collector is running +(i.e., not stopped). +
  • + @@ -2895,6 +3130,42 @@ opaque pointer passed to lua_newstate. +

    lua_getctx

    +[-0, +0, -] +

    int lua_getctx  (lua_State *L, int *ctx);
    + +

    +This function is called by a continuation function (see §3.7) +to retrieve the status of the thread and a context information. + + +

    +When called in the original function, +lua_getctx always returns LUA_OK +and does not change the value of its argument ctx. +When called inside a continuation function, +lua_getctx returns LUA_YIELD and sets +the value of ctx to be the context information +(the value passed as the ctx argument +to the callee together with the continuation function). + + +

    +When the callee is lua_pcallk, +Lua may also call its continuation function +to handle errors during the call. +That is, upon an error in the function called by lua_pcallk, +Lua may not return lua_pcallk +but instead may call the continuation function. +In that case, a call to lua_getctx will return the error code +(the value that would be returned by lua_pcallk); +the value of ctx will be set to the context information, +as in the case of an yield. + + + + +


    lua_getfenv

    [-0, +1, -]

    void lua_getfenv (lua_State *L, int index);
    @@ -2930,7 +3201,7 @@ Pushes onto the stack the value of the global name. It is defined as a macro:
    -     #define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, s)
    +     #define lua_getglobal(L,s)  lua_getfield(L, LUA_ENVIRONINDEX, s)
     
    @@ -3164,17 +3435,14 @@ Returns 1 if the value at the given acceptable index is a userdata -

    lua_lessthan

    -[-0, +0, e] -

    int lua_lessthan (lua_State *L, int index1, int index2);
    +

    lua_len

    +[-0, +1, e] +

    void lua_len (lua_State *L, int index);

    -Returns 1 if the value at acceptable index index1 is smaller -than the value at acceptable index index2, -following the semantics of the Lua < operator -(that is, may call metamethods). -Otherwise returns 0. -Also returns 0 if any of the indices is non valid. +Returns the "length" of the value at the given acceptable index; +it is equivalent to the '#' operator in Lua (see §2.5.5). +The result is pushed on the stack. @@ -3185,7 +3453,7 @@ Also returns 0 if any of the indices is non valid.

    int lua_load (lua_State *L,
                   lua_Reader reader,
                   void *data,
    -              const char *chunkname);
    + const char *source);

    Loads a Lua chunk. @@ -3197,7 +3465,7 @@ The return values of lua_load are:

    @@ -3224,8 +3498,8 @@ The data argument is an opaque value passed to the reader function.

    -The chunkname argument gives a name to the chunk, -which is used for error messages and in debug information (see §3.8). +The source argument gives a name to the chunk, +which is used for error messages and in debug information (see §3.9). @@ -3236,8 +3510,8 @@ which is used for error messages and in debug information (see &s

    lua_State *lua_newstate (lua_Alloc f, void *ud);

    -Creates a new, independent state. -Returns NULL if cannot create the state +Creates a new thread running in a new, independent state. +Returns NULL if cannot create the thread/state (due to lack of memory). The argument f is the allocator function; Lua does all memory allocation for this state through this function. @@ -3267,7 +3541,7 @@ It is equivalent to lua_createtable(L, 0, 0).

    Creates a new thread, pushes it on the stack, and returns a pointer to a lua_State that represents this new thread. -The new state returned by this function shares with the original state +The new thread returned by this function shares with the original thread all global objects (such as tables), but has an independent execution stack. @@ -3316,7 +3590,7 @@ Lua frees its corresponding memory.

    Pops a key from the stack, -and pushes a key-value pair from the table at the given index +and pushes a key–value pair from the table at the given index (the "next" pair after the given key). If there are no more elements in the table, then lua_next returns 0 (and pushes nothing). @@ -3356,32 +3630,13 @@ this confuses the next call to lua_next.

    The type of numbers in Lua. By default, it is double, but that can be changed in luaconf.h. - - -

    -Through the configuration file you can change +Through this configuration file you can change Lua to operate with another type for numbers (e.g., float or long). -


    lua_objlen

    -[-0, +0, -] -

    size_t lua_objlen (lua_State *L, int index);
    - -

    -Returns the "length" of the value at the given acceptable index: -for strings, this is the string length; -for tables, this is the result of the length operator ('#'); -for userdata, this is the size of the block of memory allocated -for the userdata; -for other values, it is 0. - - - - -


    lua_pcall

    [-(nargs + 1), +(nresults|1), -]

    int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
    @@ -3424,12 +3679,14 @@ since by then the stack has unwound.

    -The lua_pcall function returns 0 in case of success -or one of the following error codes +The lua_pcall function returns one of the following codes (defined in lua.h):

    +

    lua_pcallk

    +[-(nargs + 1), +(nresults|1), -] +

    int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
    +                          int ctx, lua_CFunction k);
    + +

    +This function behaves exactly like lua_pcall, +but allows the called function to yield (see §3.7). + + + + +


    lua_pop

    [-n, +0, -]

    void lua_pop (lua_State *L, int n);
    @@ -3583,7 +3859,7 @@ Pushes a light userdata onto the stack.

    Userdata represent C values in Lua. -A light userdata represents a pointer. +A light userdata represents a pointer, a void*. It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). @@ -3609,7 +3885,7 @@ In these cases, it automatically provides the string length.


    lua_pushlstring

    [-0, +1, m] -

    void lua_pushlstring (lua_State *L, const char *s, size_t len);
    +
    const char *lua_pushlstring (lua_State *L, const char *s, size_t len);

    Pushes the string pointed to by s with size len @@ -3620,6 +3896,10 @@ the function returns. The string can contain embedded zeros. +

    +Returns a pointer to the internal copy of the string. + + @@ -3647,7 +3927,7 @@ Pushes a number with value n onto the stack.


    lua_pushstring

    [-0, +1, m] -

    void lua_pushstring (lua_State *L, const char *s);
    +
    const char *lua_pushstring (lua_State *L, const char *s);

    Pushes the zero-terminated string pointed to by s @@ -3659,6 +3939,10 @@ The string cannot contain embedded zeros; it is assumed to end at the first zero. +

    +Returns a pointer to the internal copy of the string. + + @@ -3733,7 +4017,7 @@ Similar to lua_gettable, but does a raw

    Pushes onto the stack the value t[n], -where t is the value at the given valid index. +where t is the table at the given valid index. The access is raw; that is, it does not invoke metamethods. @@ -3741,6 +4025,23 @@ that is, it does not invoke metamethods. +


    lua_rawlen

    +[-0, +0, -] +

    size_t lua_rawlen (lua_State *L, int index);
    + +

    +Returns the raw "length" of the value at the given acceptable index: +for strings, this is the string length; +for tables, this is the result of the length operator ('#') +with no metamethods; +for userdata, this is the size of the block of memory allocated +for the userdata; +for other values, it is 0. + + + + +


    lua_rawset

    [-2, +0, m]

    void lua_rawset (lua_State *L, int index);
    @@ -3759,7 +4060,7 @@ Similar to lua_settable, but does a raw

    Does the equivalent of t[n] = v, -where t is the value at the given valid index +where t is the table at the given valid index and v is the value at the top of the stack. @@ -3831,9 +4132,10 @@ because a pseudo-index is not an actual stack position.

    void lua_replace (lua_State *L, int index);

    -Moves the top element into the given position (and pops it), +Moves the top element into the given position without shifting any element -(therefore replacing the value at the given position). +(therefore replacing the value at the given position), +and then pops the top element. @@ -3848,9 +4150,8 @@ Starts and resumes a coroutine in a given thread.

    -To start a coroutine, you first create a new thread -(see lua_newthread); -then you push onto its stack the main function plus any arguments; +To start a coroutine, +you push onto the thread stack the main function plus any arguments; then you call lua_resume, with narg being the number of arguments. This call returns when the coroutine suspends or finishes its execution. @@ -3858,14 +4159,20 @@ When it returns, the stack contains all values passed to lua_resume returns LUA_YIELD if the coroutine yields, -0 if the coroutine finishes its execution +LUA_OK if the coroutine finishes its execution without errors, or an error code in case of errors (see lua_pcall). + + +

    In case of errors, the stack is not unwound, so you can use the debug API over it. The error message is on the top of the stack. -To restart a coroutine, you put on its stack only the values to + + +

    +To resume a coroutine, you put on its stack only the values to be passed as results from yield, and then call lua_resume. @@ -3893,7 +4200,7 @@ with user data ud. Pops a table from the stack and sets it as the new environment for the value at the given index. If the value at the given index is -neither a function nor a thread nor a userdata, +neither a function nor a userdata, lua_setfenv returns 0. Otherwise it returns 1. @@ -3930,7 +4237,7 @@ sets it as the new value of global name. It is defined as a macro:

    -     #define lua_setglobal(L,s)   lua_setfield(L, LUA_GLOBALSINDEX, s)
    +     #define lua_setglobal(L,s)   lua_setfield(L, LUA_ENVIRONINDEX, s)
     
    @@ -4012,8 +4319,9 @@ Returns the status of the thread L.

    -The status can be 0 for a normal thread, -an error code if the thread finished its execution with an error, +The status can be 0 (LUA_OK) for a normal thread, +an error code if the thread finished the execution +of a lua_resume with an error, or LUA_YIELD if the thread is suspended. @@ -4028,10 +4336,10 @@ or LUA_YIELD if the thread is suspended Converts the Lua value at the given acceptable index to a C boolean value (0 or 1). Like all tests in Lua, -lua_toboolean returns 1 for any Lua value +lua_toboolean returns true for any Lua value different from false and nil; -otherwise it returns 0. -It also returns 0 when called with a non-valid index. +otherwise it returns false. +It also returns false when called with a non-valid index. (If you want to accept only actual boolean values, use lua_isboolean to test the value's type.) @@ -4188,16 +4496,16 @@ or LUA_TNONE for a non-valid index (that is, an index to an "empty" stack position). The types returned by lua_type are coded by the following constants defined in lua.h: -LUA_TNIL, -LUA_TNUMBER, -LUA_TBOOLEAN, -LUA_TSTRING, -LUA_TTABLE, -LUA_TFUNCTION, -LUA_TUSERDATA, -LUA_TTHREAD, +LUA_TNIL, +LUA_TNUMBER, +LUA_TBOOLEAN, +LUA_TSTRING, +LUA_TTABLE, +LUA_TFUNCTION, +LUA_TUSERDATA, +LUA_TTHREAD, and -LUA_TLIGHTUSERDATA. +LUA_TLIGHTUSERDATA. @@ -4215,6 +4523,21 @@ which must be one the values returned by lua_type

    lua_version

    +[-0, +0, v] +

    const lua_Number *lua_version (lua_State *L);
    + +

    +Returns the address of the version number stored in the Lua core. +When called with a valid lua_State, +returns the address of the version used to create that state. +When called with NULL, +returns the address of the version running the call. + + + + +


    lua_Writer

    typedef int (*lua_Writer) (lua_State *L,
                                const void* p,
    @@ -4260,6 +4583,22 @@ and pushes them onto the stack to.
     [-?, +?, -]
     
    int lua_yield  (lua_State *L, int nresults);
    +

    +This function is equivalent to lua_yieldk, +but it has no continuation (see §3.7). +Therefore, when the thread resumes, +it returns to the function that called +the function calling lua_yield. + + + + + +


    lua_yieldk

    +[-?, +?, -] +

    int lua_yieldk  (lua_State *L, int nresults, int ctx,
    +                           lua_CFunction k);
    +

    Yields a coroutine. @@ -4269,23 +4608,36 @@ This function should only be called as the return expression of a C function, as follows:

    -     return lua_yield (L, nresults);
    +     return lua_yield (L, nresults, i, k);
     

    -When a C function calls lua_yield in that way, +When a C function calls lua_yieldk in that way, the running coroutine suspends its execution, and the call to lua_resume that started this coroutine returns. The parameter nresults is the number of values from the stack that are passed as results to lua_resume. +

    +When the coroutine is resumed again, +Lua calls the given continuation function k to continue +the execution of the C function that yielded (see §3.7). +This continuation function receives the same stack +from the previous function, +with the results removed and +replaced by the arguments passed to lua_resume. +Moreover, +the continuation function may access the value ctx +by calling lua_getctx. -

    3.8 - The Debug Interface

    -

    + +

    3.9 - The Debug Interface

    + +

    Lua has no built-in debugging facilities. Instead, it offers a special interface by means of functions and hooks. @@ -4303,9 +4655,12 @@ that need "inside information" from the interpreter. const char *what; /* (S) */ const char *source; /* (S) */ int currentline; /* (l) */ - int nups; /* (u) number of upvalues */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ + unsigned char nups; /* (u) number of upvalues */ + unsigned char nparams; /* (u) number of parameters */ + char isvararg; /* (u) */ + char istailcall; /* (t) */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ other fields @@ -4326,10 +4681,15 @@ The fields of lua_Debug have the following

    • source: -If the function was defined in a string, -then source is that string. -If the function was defined in a file, -then source starts with a '@' followed by the file name. +the source of the chunk that created the function. +If source starts with a '@', +it means that the function was defined in a file where +the file name follows the '@'. +If source starts with a '=', +the rest of it should describe the source in a user-dependent manner. +Otherwise, +the function was defined in a string where +source is that string.
    • short_src: @@ -4347,10 +4707,7 @@ the line number where the definition of the function ends.
    • what: the string "Lua" if the function is a Lua function, "C" if it is a C function, -"main" if it is the main part of a chunk, -and "tail" if it was a function that did a tail call. -In the latter case, -Lua has no other information about the function. +"main" if it is the main part of a chunk.
    • currentline: @@ -4380,10 +4737,25 @@ according to how the function was called. (Lua uses the empty string when no other option seems to apply.)
    • +
    • istailcall: +true if this function invocation was called by a tail call. +In this case, the caller of this level is not in the stack. +
    • +
    • nups: the number of upvalues of the function.
    • +
    • nparams: +the number of fixed parameters of the function +(always 0 for C functions). +
    • + +
    • isvararg: +whether the function is a vararg function +(always true for C functions). +
    • +
    @@ -4441,13 +4813,13 @@ given as argument to a hook (see lua_Hook). To get information about a function you push it onto the stack and start the what string with the character '>'. (In that case, -lua_getinfo pops the function in the top of the stack.) +lua_getinfo pops the function from the top of the stack.) For instance, to know in which line a function f was defined, you can write the following code:
          lua_Debug ar;
    -     lua_getfield(L, LUA_GLOBALSINDEX, "f");  /* get global 'f' */
    +     lua_getfield(L, LUA_ENVIRONINDEX, "f");  /* get global 'f' */
          lua_getinfo(L, ">S", &ar);
          printf("%d\n", ar.linedefined);
     
    @@ -4470,6 +4842,9 @@ fills in the fields source, short_src,
  • 'l': fills in the field currentline;
  • +
  • 't': fills in the field istailcall; +
  • +
  • 'u': fills in the field nups;
  • @@ -4589,16 +4964,17 @@ Whenever a hook is called, its ar argument has its field event set to the specific event that triggered the hook. Lua identifies these events with the following constants: LUA_HOOKCALL, LUA_HOOKRET, -LUA_HOOKTAILRET, LUA_HOOKLINE, +LUA_HOOKTAILCALL, LUA_HOOKLINE, and LUA_HOOKCOUNT. 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 can 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. + + +

    +For call events, event can be LUA_HOOKCALL, +the normal value, or LUA_HOOKTAILCALL, for a tail call; +in this case, there will be no corresponding return event.

    @@ -4705,6 +5081,29 @@ when the index is greater than the number of upvalues. +


    lua_upvalueid

    +[-0, +0, -] +

    void *(lua_upvalueid) (lua_State *L, int funcindex, int n);
    + +

    +Returns an unique identifier for the upvalue numbered n +from the closure at index fidx. +Parameters funcindex and n are as in the lua_getupvalue +(see lua_getupvalue) +(but n cannot be greater than the number of upvalues). + + +

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

    4 - The Auxiliary Library

    @@ -4728,19 +5127,22 @@ have a prefix luaL_.

    All functions in the auxiliary library are built on top of the basic API, -and so they provide nothing that cannot be done with this API. +and so they provide nothing that cannot be done with that API.

    Several functions in the auxiliary library are used to check C function arguments. -Their names are always luaL_check* or luaL_opt*. -All of these functions throw an error if the check is not satisfied. Because the error message is formatted for arguments (e.g., "bad argument #1"), you should not use these functions for other stack values. +

    +Functions called luaL_check* +always throw an error if the check is not satisfied. + +

    4.1 - Functions and Types

    @@ -4938,10 +5340,10 @@ Calls a metamethod. If the object at index obj has a metatable and this metatable has a field e, this function calls this field and passes the object as its only argument. -In this case this function returns 1 and pushes onto the +In this case this function returns true and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, -this function returns 0 (without pushing any value on the stack). +this function returns false (without pushing any value on the stack). @@ -5064,7 +5466,8 @@ to use strings instead of numbers to select options.)

    Grows the stack size to top + sz elements, raising an error if the stack cannot grow to that size. -msg is an additional text to go into the error message. +msg is an additional text to go into the error message +(or NULL for no additional text). @@ -5105,7 +5508,24 @@ See lua_type for the encoding of types for

    Checks whether the function argument narg is a userdata -of the type tname (see luaL_newmetatable). +of the type tname (see luaL_newmetatable) and +returns the userdata address (see lua_touserdata). + + + + + +


    luaL_checkversion

    +[-0, +0, -] +

    void *luaL_checkversion (lua_State *L);
    + +

    +Checks whether the core running the call, +the core that created the Lua state, +and the code making the call are all using the same version of Lua. +Also checks whether the core running the call +and the core that created the Lua state +are using the same address space. @@ -5122,15 +5542,15 @@ It is defined as the following macro:

          (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
     

    -It returns 0 if there are no errors -or 1 in case of errors. +It returns false if there are no errors +or true in case of errors.


    luaL_dostring

    -[-0, +?, m] +[-0, +?, -]

    int luaL_dostring (lua_State *L, const char *str);

    @@ -5140,8 +5560,8 @@ It is defined as the following macro:

          (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
     

    -It returns 0 if there are no errors -or 1 in case of errors. +It returns false if there are no errors +or true in case of errors. @@ -5179,7 +5599,7 @@ Pushes onto the stack the field e from the metatable of the object at index obj. If the object does not have a metatable, or if the metatable does not have this field, -returns 0 and pushes nothing. +returns false and pushes nothing. @@ -5214,8 +5634,23 @@ Pushes the resulting string on the stack and returns it. +


    luaL_len

    +[-0, +1, e] +

    int luaL_len (lua_State *L, int index);
    + +

    +Returns the "length" of the value at the given acceptable index +as a number; +it is equivalent to the '#' operator in Lua (see §2.5.5). +Raises an error if the result of the operation is not a number. +(This only may happen through metamethods.) + + + + +


    luaL_loadbuffer

    -[-0, +1, m] +[-0, +1, -]

    int luaL_loadbuffer (lua_State *L,
                          const char *buff,
                          size_t sz,
    @@ -5264,7 +5699,7 @@ it does not run it.
     
     
     

    luaL_loadstring

    -[-0, +1, m] +[-0, +1, -]

    int luaL_loadstring (lua_State *L, const char *s);

    @@ -5314,7 +5749,7 @@ with tname in the registry. Creates a new Lua state. It calls lua_newstate with an allocator based on the standard C realloc function -and then sets a panic function (see lua_atpanic) that prints +and then sets a panic function (see §3.6) that prints an error message to the standard error output in case of fatal errors. @@ -5527,8 +5962,10 @@ Opens a library.

    When called with libname equal to NULL, -it simply registers all functions in the list l +it simply registers all functions in the array l (see luaL_Reg) into the table on the top of the stack. +The pointer l may be NULL, +representing an empty list.

    @@ -5550,6 +5987,35 @@ on the top of the stack. +


    luaL_testudata

    +[-0, +0, m] +

    void *luaL_testudata (lua_State *L, int narg, const char *tname);
    + +

    +This function works like luaL_checkudata, +except that, when the test fails, +it returns NULL instead of throwing an error. + + + + + +


    luaL_traceback

    +[-0, +1, m] +

    luaL_traceback (lua_State *L, lua_State *L1,
    +                          const char *msg, int level);
    + +

    +Creates and pushes a traceback of the stack L1. +If msg is not NULL it is appended +at the beginning of the traceback. +The level parameter tells at which level +to start the traceback. + + + + +


    luaL_typename

    [-0, +0, -]

    const char *luaL_typename (lua_State *L, int index);
    @@ -5561,9 +6027,9 @@ Returns the name of the type of the value at the given index. -

    luaL_typerror

    +


    luaL_typeerror

    [-0, +0, v] -

    int luaL_typerror (lua_State *L, int narg, const char *tname);
    +
    int luaL_typeerror (lua_State *L, int narg, const char *tname);

    Generates an error with a message like the following: @@ -5645,7 +6111,7 @@ Currently, Lua has the following standard libraries:

      -
    • basic library,
    • which includes the coroutine sub-library; +
    • basic library, which includes the coroutine sub-library;
    • package library;
    • @@ -5655,6 +6121,8 @@ Currently, Lua has the following standard libraries:
    • mathematical functions (sin, log, etc.);
    • +
    • bitwise operations;
    • +
    • input and output;
    • operating system facilities;
    • @@ -5678,6 +6146,7 @@ it can open them individually by calling luaopen_string (for the string library), luaopen_table (for the table library), luaopen_math (for the mathematical library), +luaopen_bitlib (for the bit library), luaopen_io (for the I/O library), luaopen_os (for the Operating System library), and luaopen_debug (for the debug library). @@ -5709,7 +6178,7 @@ when absent, it defaults to "assertion failed!"

      -


      collectgarbage (opt [, arg])

      +

      collectgarbage ([opt [, arg]])

      @@ -5718,6 +6187,11 @@ It performs different functions according to its first argument, opt +

    • "collect": +performs a full garbage-collection cycle. +This is the default option. +
    • +
    • "stop": stops the garbage collector.
    • @@ -5726,12 +6200,16 @@ stops the garbage collector. restarts the garbage collector. -
    • "collect": -performs a full garbage-collection cycle. -
    • -
    • "count": -returns the total memory in use by Lua (in Kbytes). +returns the total memory in use by Lua (in Kbytes) and +a second value with the total memory in bytes modulo 1024. +The first value has a fractional part, +so the following equality is always true: + +
      +     k, b = collectgarbage("count")
      +     assert(k*1024 == math.floor(k)*1024 + b)
      +

    • "step": @@ -5755,12 +6233,17 @@ the collector (see §2.10). Returns the previous value for step.
    • +
    • "isrunning": +returns a boolean that tells whether the collector is running +(i.e., not stopped). +
    • +

    -


    dofile (filename)

    +

    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). @@ -5780,7 +6263,7 @@ Function error never returns.

    Usually, error adds some information about the error position -at the beginning of the message. +at the beginning of the message, if the message is a string. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. @@ -5795,25 +6278,10 @@ to the message.


    _G

    A global variable (not a function) that -holds the global environment (that is, _G._G = _G). +holds the global environment (so that _G._G = _G). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa. -(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 -that 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. @@ -5837,29 +6305,46 @@ Otherwise, returns the metatable of the given object.

    -Returns three values: an iterator function, the table t, and 0, +If t has a metamethod __ipairs, +calls it with t as argument and returns the first three +results from the call. + + +

    +Otherwise, +returns three values: an iterator function, the table t, and 0, so that the construction

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

    will iterate over the pairs (1,t[1]), (2,t[2]), ···, -up to the first integer key absent from the table. +up to the length of the table, +as defined by the length operator (see §2.5.5).

    -


    load (func [, chunkname])

    +

    load (ld [, source [, mode]])

    -Loads a chunk using function func to get its pieces. -Each call to func must return a string that concatenates +Loads a chunk. + + +

    +If ld is a function, +calls it repeatedly to get the chunk pieces. +Each call to ld must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk. +

    +If ld is a string, the chunk is this string. + +

    If there are no errors, returns the compiled chunk as a function; @@ -5868,12 +6353,33 @@ The environment of the returned function is the global environment.

    -chunkname is used as the chunk name for error messages -and debug information. +source is used as the source of the chunk for error messages +and debug information (see §3.9). When absent, it defaults to "=(load)". +

    +The string mode controls whether the chunk can be text or binary +(that is, a precompiled chunk). +A letter 't' in mode allows a text chunk; +a letter 'b' allows a binary chunk. +The default is "bt". + + + + +

    +


    loadin (env, ...)

    + + +

    +This function is similar to load, +but sets env as the environment +of the created function in case of success. +The parameters after env are similar to those of load, too. + +

    @@ -5955,7 +6461,14 @@ In particular, you may clear existing fields.

    -Returns three values: the next function, the table t, and nil, +If t has a metamethod __pairs, +calls it with t as argument and returns the first three +results from the call. + + +

    +Otherwise, +returns three values: the next function, the table t, and nil, so that the construction

    @@ -5972,7 +6485,7 @@ the table during its traversal.
     
     
     

    -


    pcall (f, arg1, ···)

    +

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

    @@ -6043,33 +6556,14 @@ This function returns table.

    If index is a number, -returns all arguments after argument number index. +returns all arguments after argument number index; +a negative number indexes from the end (-1 is the last argument). Otherwise, index must be the string "#", and select returns the total number of extra arguments it received. -

    -


    setfenv (f, table)

    - - -

    -Sets the environment to be used by the given function. -f can be a Lua function or a number -that specifies the function at that stack level: -Level 1 is the function calling setfenv. -setfenv returns the given function. - - -

    -As a special case, when f is 0 setfenv changes -the environment of the running thread. -In this case, setfenv returns no values. - - - -


    setmetatable (table, metatable)

    @@ -6143,22 +6637,6 @@ and "userdata". -

    -


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

    -Returns the elements from the given table. -This function is equivalent to - -
    -     return list[i], list[i+1], ···, list[j]
    -

    -except that the above code can be written only for a fixed number -of elements. -By default, i is 1 and j is the length of the list, -as defined by the length operator (see §2.5.5). - - - -


    _VERSION

    A global variable (not a function) that @@ -6169,27 +6647,12 @@ The current contents of this variable is "Lua 5.1".

    -


    xpcall (f, err)

    +

    xpcall (f, err [, arg1, ···])

    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 this 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. +except that it sets a new error handler err. @@ -6250,8 +6713,8 @@ If there is any error,

    -Returns the running coroutine, -or nil when called by the main thread. +Returns the running coroutine plus a boolean, +true when the running coroutine is the main one. @@ -6322,7 +6785,7 @@ Everything else is exported in a table package -Creates a module. +Creates and returns a module. If there is a table in package.loaded[name], this table is the module. Otherwise, if there is a global table t with the given name, @@ -6334,11 +6797,14 @@ This function also initializes t._NAME with the given name, t._M with the module (t itself), and t._PACKAGE with the package name (the full module name minus last component; see below). -Finally, module sets t as the new environment -of the current function and the new value of package.loaded[name], +Finally, module sets t as the new value of package.loaded[name], so that require returns t. +

    +The module function returns the module table t. + +

    If name is a compound name (that is, one with components separated by dots), @@ -6355,6 +6821,12 @@ the module name, where each option is a function to be applied over the module. +

    +To keep compatibility with old versions of Lua, +module also sets t as the new environment +of the current function. + +

    @@ -6411,6 +6883,38 @@ then require signals an error. +

    +


    package.config

    + + +

    +A string describing some compile-time configurations for packages. +This string is a sequence of lines: + +

      + +
    • The first line is the directory separator string. +Default is '\' for Windows and '/' for all other systems.
    • + +
    • The second line is the character that separates templates in a path. +Default is ';'.
    • + +
    • The third line is the string that marks the +substitution points in a template. +Default is '?'.
    • + +
    • The fourth line is a string that, in a path in Windows, +is replaced by the executable's directory. +Default is '!'.
    • + +
    • The fifth line is a mark to ignore all before it when bulding the +luaopen_ function name. +Default is '-'.
    • + +
    + + +


    package.cpath

    @@ -6441,6 +6945,12 @@ When you require a module modname and require simply returns the value stored there. +

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

    @@ -6471,27 +6981,14 @@ The first searcher simply looks for a loader in the

    The second searcher looks for a loader as a Lua library, using the path stored at package.path. -A path is a sequence of templates separated by semicolons. -For each template, -the searcher will change each interrogation -mark in the template by filename, -which is the module name with each dot replaced by a -"directory separator" (such as "/" in Unix); -then it will try to open the resulting file name. -So, for instance, if the Lua path is the string - -

    -     "./?.lua;./?.lc;/usr/local/?/init.lua"
    -

    -the search for a Lua file for module foo -will try to open the files -./foo.lua, ./foo.lc, and -/usr/local/foo/init.lua, in that order. +The search is done as described in function package.searchpath.

    The third searcher looks for a loader as a C library, using the path given by the variable package.cpath. +Again, +the search is done as described in function package.searchpath. For instance, if the C path is the string @@ -6537,7 +7034,15 @@ with each submodule keeping its original open function.

    Dynamically links the host program with the C library libname. -Inside this library, looks for a function funcname + + +

    +If funcname is "*", +then it only links with the library, +making the symbols exported by the library +available to other dynamically linked libraries. +Otherwise, +it looks for a function funcname inside the library and returns this function as a C function. (So, funcname must follow the protocol (see lua_CFunction)). @@ -6549,13 +7054,13 @@ Unlike require, it does not perform any path searching and does not automatically adds extensions. libname must be the complete file name of the C library, -including if necessary a path and extension. +including if necessary a path and an extension. funcname must be the exact name exported by the C library (which may depend on the C compiler and linker used).

    -This function is not supported by ANSI C. +This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn standard). @@ -6593,6 +7098,41 @@ A table to store loaders for specific modules +

    +


    package.searchpath (name, path)

    + + +

    +Searches for the given name in the given path. + + +

    +A path is string containing a sequence of +templates separated by semicolons. +For each template, +the function changes each interrogation +mark in the template by name, +and then tries to open the resulting file name. +For instance, if the path is the string + +

    +     "./?.lua;./?.lc;/usr/local/?/init.lua"
    +

    +the search for name foo +will try to open the files +./foo.lua, ./foo.lc, and +/usr/local/foo/init.lua, in that order. + + +

    +Returns the resulting name of the first file that it can +open in read mode (after closing it), +or nil plus an error message if none succeeds. +(This error message lists all file names it tried to open.) + + + +


    package.seeall (module)

    @@ -7070,6 +7610,16 @@ For instance, the item %b() matches expressions with balanced parentheses. +
  • +%f[set], a frontier pattern; +such item matches an empty string at any position such that +the next character belongs to set +and the previous character does not belong to set. +The set set is interpreted as previously described. +The beggining and the end of the subject are handled as if +they were the character '\0'. +
  • + @@ -7161,14 +7711,13 @@ of table t.

    -


    table.maxn (table)

    +

    table.pack (···)

    -Returns the largest positive numerical index of the given table, -or zero if the table has no positive numerical indices. -(To do its job this function does a linear traversal of -the whole table.) +Returns a new table with all parameters stored into +keys 1, 2, etc. +and with a field "n" with the total number of parameters. @@ -7211,6 +7760,22 @@ may have their relative positions changed by the sort. +

    +


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

    +Returns the elements from the given table. +This function is equivalent to + +
    +     return list[i], list[i+1], ···, list[j]
    +

    +except that the above code can be written only for a fixed number +of elements. +By default, i is 1 and j is the length of the list, +as defined by the length operator (see §2.5.5). + + + + @@ -7380,21 +7945,13 @@ Returns m2e (e should be an integer).

    -


    math.log (x)

    - - -

    -Returns the natural logarithm of x. - - - - -

    -


    math.log10 (x)

    +

    math.log (x [, base])

    -Returns the base-10 logarithm of x. +Returns the logarithm of x in the given base. +The default for base is $e$ +(so that the function returns the natural logarithm of x). @@ -7551,7 +8108,141 @@ Returns the hyperbolic tangent of x. -

    5.7 - Input and Output Facilities

    +

    5.7 - Bitwise operations

    + +

    +This library provides bitwise operations. +It provides all its functions inside the table bit. +Unless otherwise stated, +all functions accept as arguments and return numbers +in the range [0,2^32 - 1]. +Standard Lua does not use 2-complement representation for numbers, +so in standard Lua (that is, with floating-point numbers) you +cannot use negative numbers with this library. +In particular, -1 is not the same as 0xffffffff. + + +

    +


    bit.band (···)

    + + +

    +Returns the bitwise and of its operands. + + + + +

    +


    bit.bnot (x)

    + + +

    +Returns the bitwise negation of x. +For any valid x, +the following identity holds: + +

    +     assert(bit.bnot(x) == 2^32 - 1 - x)
    +
    + + + +

    +


    bit.bor (···)

    + + +

    +Returns the bitwise or of its operands. + + + + +

    +


    bit.brotate (x, disp)

    + + +

    +Returns the number x rotated disp bits to the left. +The number disp may be any representable integer. + + +

    +For any valid displacement, +the following identity holds: + +

    +     assert(bit.rotate(x, disp) == bit.rotate(x, disp % 32))
    +

    +This allows you to consider that +negative displacements rotate to the right. + + + + +

    +


    bit.bshift (x, disp)

    + + +

    +Returns the number x shifted disp bits to the left. +The number disp may be any representable integer. +Negative displacements shift to the right. +In any direction, vacant bits are filled with zeros. +In particular, +displacements with absolute values higher than +the total number of bits in the representation of x +result in zero (all bits are shifted out). + + +

    +For positive displacements, +the following equality holds: + +

    +     assert(bit.bshift(b, disp) == (b * 2^disp) % 2^32)
    +
    + +

    +For negative displacements, +the following equality holds: + +

    +     assert(bit.bshift(b, disp) == math.floor(b * 2^disp))
    +
    + +

    +This shift operation is what is called logical shift. +For an arithmetic shift, +you should use the arithmetic operators. + + + + +

    +


    bit.btest (···)

    + + +

    +Returns a boolean signaling +whether the bitwise and of its operands is different from zero. + + + + +

    +


    bit.bxor (···)

    + + +

    +Returns the bitwise exclusive or of its operands. + + + + + + + +

    5.8 - Input and Output Facilities

    The I/O library provides two different styles for file manipulation. @@ -7679,8 +8370,6 @@ The mode string can be any of the following:

    The mode string can also have a 'b' at the end, which is needed in some systems to open the file in binary mode. -This string is exactly what is used in the -standard C function fopen. @@ -7770,6 +8459,11 @@ their handles are garbage collected, but that takes an unpredictable amount of time to happen. +

    +If file was created with io.popen, +a sucessful close returns the exit status of the process. + +

    @@ -7930,12 +8624,17 @@ To write other values, use tostring or string.format before write. +

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

    5.8 - Operating System Facilities

    + + +

    5.9 - Operating System Facilities

    This library is implemented through table os. @@ -8023,7 +8722,7 @@ and zero otherwise.

    -


    os.exit ([code])

    +

    os.exit ([code [, close])

    @@ -8033,6 +8732,11 @@ to terminate the host program. The default value for code is the success code. +

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

    @@ -8156,7 +8860,7 @@ which automatically removes the file when the program ends. -

    5.9 - The Debug Library

    +

    5.10 - The Debug Library

    This library provides @@ -8236,7 +8940,8 @@ or you can give a number as the value of function, which means the function running at level function of the call stack of the given thread: level 0 is the current function (getinfo itself); -level 1 is the function that called getinfo; +level 1 is the function that called getinfo +(except for tail calls, which do not count on the stack); and so on. If function is a number larger than the number of active functions, then getinfo returns nil. @@ -8362,8 +9067,8 @@ When called without arguments,

    When the hook is called, its first parameter is a string describing the event that has triggered its call: -"call", "return" (or "tail return", -when simulating a return from a tail call), +"call" (or "tail call"), +"return", "line", and "count". For line events, the hook also gets the new line number as its second parameter. @@ -8371,10 +9076,7 @@ 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. +and level 1 is the hook function). @@ -8425,7 +9127,10 @@ Otherwise, it returns the name of the upvalue.

    -Returns a string with a traceback of the call stack. +If message is present but is not a string, +this function returns message without further processing. +Otherwise, +returns a string with a traceback of the call stack. An optional message string is appended at the beginning of the traceback. An optional level number tells at which level @@ -8528,6 +9233,17 @@ 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 a string, +the interpreter adds a stack traceback to it. +Otherwise, if the error object has a metamethod __tostring, +the interpreter calls this metamethod to produce the final message. +Finally, if the error object is nil, +the interpreter does not report the error. + +

    If the global variable _PROMPT contains a string, then its value is used as the prompt. @@ -8577,8 +9293,8 @@ is a more portable solution.)

    Here we list the incompatibilities that you may find when moving a program -from Lua 5.0 to Lua 5.1. -You can avoid most of the incompatibilities compiling Lua with +from Lua 5.1 to Lua 5.2. +You can avoid some incompatibilities compiling Lua with appropriate options (see file luaconf.h). However, all these compatibility options will be removed in the next version of Lua. @@ -8589,21 +9305,21 @@ all these compatibility options will be removed in the next version of Lua.

    • -The vararg system changed from the pseudo-argument arg with a -table with the extra arguments to the vararg expression. -(See compile-time option LUA_COMPAT_VARARG in luaconf.h.) +Lua identifiers cannot use locale-dependent letters.
    • -There was a subtle change in the scope of the implicit -variables of the for statement and for the repeat statement. +Doing a step in the garbage collector does not restart the collector +if it has been stopped.
    • -The long string/long comment syntax ([[string]]) -does not allow nesting. -You can use the new syntax ([=[string]=]) in these cases. -(See compile-time option LUA_COMPAT_LSTR in luaconf.h.) +Weak tables with weak keys now perform like ephemeron tables. +
    • + +
    • +Threads do not have individual environments. +All threads share a sinle fixed environment.
    @@ -8615,53 +9331,31 @@ You can use the new syntax ([=[string]=]) in these cases.
    • -Function string.gfind was renamed string.gmatch. -(See compile-time option LUA_COMPAT_GFIND in luaconf.h.) +The debug library is not loaded by default. +You must explicitly require it.
    • -When string.gsub is called with a function as its -third argument, -whenever this function returns nil or false the -replacement string is the whole match, -instead of the empty string. +Functions setfenv and getfenv are deprecated. +To set the environment of a Lua function, +use lexical environments or the new function loadin. +(If you really need them, +you may use their equivalents in the debug library.)
    • -Function table.setn was deprecated. -Function table.getn corresponds -to the new length operator (#); -use the operator instead of the function. -(See compile-time option LUA_COMPAT_GETN in luaconf.h.) +Function math.log10 is deprecated. +Use math.log with 10 as its second argument, instead.
    • -Function loadlib was renamed package.loadlib. -(See compile-time option LUA_COMPAT_LOADLIB in luaconf.h.) +Function table.maxn is deprecated. +Write it in Lua if you really need it.
    • -Function math.mod was renamed math.fmod. -(See compile-time option LUA_COMPAT_MOD in luaconf.h.) -
    • - -
    • -Functions table.foreach and table.foreachi are deprecated. -You can use a for loop with pairs or ipairs instead. -
    • - -
    • -There were substantial changes in function require due to -the new module system. -However, the new behavior is mostly compatible with the old, -but require gets the path from package.path instead -of from LUA_PATH. -
    • - -
    • -Function collectgarbage has different arguments. -Function gcinfo is deprecated; -use collectgarbage("count") instead. +Function unpack was moved into the table library +and therefore must be called as table.unpack.
    @@ -8673,36 +9367,38 @@ use collectgarbage("count") instead.
    • -The luaopen_* functions (to open libraries) -cannot be called directly, -like a regular C function. -They must be called through Lua, -like a Lua function. +Pseudoindex LUA_GLOBALSINDEX was deprecated. +You may use the pseudoindex LUA_ENVIRONINDEX instead, +if the C function does not change its standard environment. +Otherwise, you should get the global environment from the registry +(see §3.5).
    • -Function lua_open was replaced by lua_newstate to -allow the user to set a memory-allocation function. -You can use luaL_newstate from the standard library to -create a state with a standard allocation function -(based on realloc). +Macros lua_getglobal, lua_setglobal, and lua_register +now operate over the function environment instead of the global +environment. +(This is more consistent with how Lua manipulates global variables.)
    • -Functions luaL_getn and luaL_setn -(from the auxiliary library) are deprecated. -Use lua_objlen instead of luaL_getn -and nothing instead of luaL_setn. +luaL_typerror was renamed luaL_typeerror, +to have a correct spelling.
    • -Function luaL_openlib was replaced by luaL_register. +Function lua_cpcall is deprecated. +Use the new cpcall function defined in the registry instead +(see §3.5).
    • -Function luaL_checkudata now throws an error when the given value -is not a userdata of the expected type. -(In Lua 5.0 it returned NULL.) +Functions lua_equal and lua_lessthan are deprecated. +Use the new lua_compare with appropriate options instead. +
    • + +
    • +Function lua_objlen was renamed lua_rawlen.
    @@ -8735,7 +9431,8 @@ Here is the complete syntax of Lua in extended BNF. for namelist in explist do block end | function funcname funcbody | local function Name funcbody | - local namelist [`=´ explist] + local namelist [`=´ explist] | + in exp do block end laststat ::= return [explist] | break @@ -8787,15 +9484,5 @@ Here is the complete syntax of Lua in extended BNF. - -
    - -Last update: -Mon Aug 18 13:25:46 BRT 2008 - - - -- cgit v1.2.1