|
|
Óû§Ãû£ºkang888 ±ÊÃû£ºlua µØÇø£º ±±¾©-É쵯 ÐÐÒµ£ºÆäËû |
| ÈÕ | Ò» | ¶þ | Èý | ËÄ | Îå | Áù |
¶¯µ´Äê´ú Ư²´ÈËÉú
³¤¿Þ¸è--×ªÔØ
- ×÷Õߣº lua 2005Äê09ÔÂ5ÈÕ, ÐÇÆÚÒ» 16:39¡¡ »Ø¸´£¨0£© |¡¡ ÒýÓã¨0£© ¼ÓÈ벩²É
Lua5.0 ²Î¿¼ÊÖ²á(ÖÐÎÄ) No.4
5.3 - String Mani***tion
This library provides generic functions for string mani***tion, 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.
string.format (formatstring, e1, e2, ...) 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 re 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:
The interaction between ranges and classes is not defined. Therefore, patterns like [%a-z] or [a-%%] have no meaning.
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 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 Mani***tion
This library provides generic functions for table mani***tion. 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:
For more details see the descriptions of the table.getn and table.setn functions.
table.concat (table [, sep [, i [, j]]]) Returns table
..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.
table.getn (table) 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
, 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
) 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 mani***tion. 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:
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
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:
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 locae, 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 expressions, 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 expression 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:
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.
[±à¼]
6 - Lua ¶ÀÁ¢³ÌÐò
Lua Stand-alone
¾¡¹ÜLua±»Éè¼ÆÎªÒ»ÖÖÄÚǶÓÚC ÓïÑÔËÞÖ÷³ÌÐòÖеÄÀ©Õ¹ÓïÑÔ£¬Ëü»¹ÊǾ³£±»ÓÃ×÷Ò»¸ö¶ÀÁ¢³ÌÐòÓïÑÔ¡£Ò»¸öLuaµÄ½âÊͳÌÐò½«Lua×÷Ϊһ¸ö¶ÀÁ¢µÄÓïÑÔ£¬ÎÒÃdzÆÖ®Îª¼ò»¯µÄ lua£¬ËüÌṩÁ˱ê×¼µÄ·¢Ðа汾¡£¶ÀÁ¢µÄ½âÊÍÆ÷°üº¬ÁËËùÓбê×¼¿â¼ÓÉÏ·´ÉäÐԵĵ÷ÊÔ½Ó¿Ú¡£ËüµÄʹÓ÷½Ê½ÈçÏ£º
lua [options] [script [args]]
options ¿ÉÒÔÊÇÒÔÏÂÄÚÈÝ£º
ÔÚÍ£Ö¹´¦ÀíÑ¡Ïîºó£¬lua ÔËÐÐËù¸øµÄ½Å±¾£¬´«µÝËù¸ø²ÎÊý args¡£µ±ÎÞ²ÎÊýµ÷ÓÃʱ£¬lua ¾ÍÏñ stdin ÊdzÌÐòµÄÖÕ½áʱ lua -v -i Ëù±íÏÖµÄÒ»Ñù£¬¶øÇÒ»¹Óë lua- Ò»Ñù¡£
Before running any argument, the interpreter checks for an environment variable LUA_INIT. If its format is @filename, then lua executes the file. Otherwise, lua executes the string itself.
All options are handled in order, except -i. For instance, an invocation like
$ lua -e'a=1' -e 'print(a)' script.lua
will first set a to 1, then print a, and finally run the file script.lua. (Here, $ is the shell prompt. Your prompt may be different.)
Before starting to run the script, lua collects all arguments in the command line in a global table called arg. The script name is stored in index 0, the first argument after the script name goes to index 1, and so on. The field n gets the number of arguments after the script name. Any arguments before the script name (that is, the interpreter name plus the options) go to negative indices. For instance, in the call
$ lua -la.lua b.lua t1 t2
the interpreter first runs the file a.lua, then creates a table
arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua",
[1] = "t1", [2] = "t2"; n = 2 }
and finally runs the file b.lua.
ÔÚ½»»¥Ä£Ê½ÖУ¬Èç¹ûÄãдÈëÁËÒ»¸ö²»ÍêÕûµÄÓï¾ä£¬½âÊÍÆ÷½«µÈ´ýÄãµÄÍê³É¡£
If the global variable _PROMPT is defined as a string, then its value is used as the prompt. Therefore, the prompt can be changed directly on the command line:
$ lua -e"_PROMPT='myprompt> '" -i
(the outer pair of quotes is for the shell, the inner is for Lua), or in any Lua programs by assigning to _PROMPT. Note the use of -i to enter interactive mode; otherwise, the program would end just after the assignment to _PROMPT.
ÔÚUnixϵͳÖУ¬Lua½Å±¾¿ÉÒÔÓà chmod +x ½«Æä±ä³É¿ÉÖ´ÐгÌÐò£¬²¢ÇÒͨ¹ý #! ÐÎʽ£¬ÀýÈç
£¨µ±È»£¬Lua½âÊÍÆ÷µÄλÖÿÉÄÜÓÐËù²»Í¬£¬Èç¹û lua ÔÚÄãµÄ PATH ÖУ¬ÄÇô
¾ÍÊÇÒ»¸ö¸üͨÓõĽâ¾ö·½°¸¡££©
[±à¼]
ÖÂл
The Lua team is grateful to Tecgraf for its continued support to Lua. We thank everyone at Tecgraf, specially the head of the group, Marcelo Gattass. At the risk of omitting several names, we also thank the following individuals for supporting, contributing to, and spreading the word about Lua: Alan Watson. Andr¨¦ Clinio, Andr¨¦ Costa, Antonio Scuri, Asko Kauppi, Bret Mogiefsky, Cameron Laird, Carlos Cassino, Carlos Henrique Levy, Claudio Terra, David Jeske, Ed Ferguson, Edgar Toernig, Erik Hougaard, Jim Mathies, John Belmonte, John Passaniti, John Roll, Jon Erickson, Jon Kleiser, Mark Ian Barlow, Nick Trout, Noemi Rodriguez, Norman Ramsey, Philippe Lhoste, Renata Ratton, Renato Borges, Renato Cerqueira, Reuben Thomas, Stephan Herrmann, Steve Dekorte, Thatcher Ulrich, Tom¨¢s Gorham, Vincent Penquerc'h. Thank you!
[±à¼]
ÓëÒÔǰ°æ±¾µÄ²»¼æÈÝÐÔ
Lua 5.0 ÊÇÒ»¸öÖ÷°æ±¾£¬ËùÓÐÓë Lua 4.0 ÓÐһЩµØ·½²»¼æÈÝ¡£
ÒÔÏÂÊÇÓë v4.0 µÄ²»¼æÈÝÐÔ
[±à¼]
ÓïÑÔÉϵı䶯
[±à¼]
¿âµÄ±ä¸ü
[±à¼]
API Éϵĸ͝
[±à¼]
Lua ÍêÕûÓï·¨²Î¿¼
chunk ::= {stat [`;´]}
block ::= chunk
stat ::= varlist1 `=´ explist1 | functioncall | do block end | while exp do block end | repeat block until exp | if exp then block {elseif exp then block} [else block] end | return [explist1] | break | for Name `=´ exp `,´ exp [`,´ exp] do block end | for Name {`,´ Name} in explist1 do block end | function funcname funcbody | local function Name funcbody | local namelist [init]
funcname ::= Name {`.´ Name} [`:´ Name]
varlist1 ::= var {`,´ var}
var ::= Name | prefixexp `[´ exp `]´ | prefixexp `.´ Name
namelist ::= Name {`,´ Name}
init ::= `=´ explist1
explist1 ::= {exp `,´} exp
exp ::= nil | false | true | Number | Literal | function | prefixexp | tableconstructor | exp binop exp | unop exp
prefixexp ::= var | functioncall | `(´ exp `)´
args ::= `(´ [explist1] `)´ | tableconstructor | Literal
function ::= function funcbody
funcbody ::= `(´ [parlist1] `)´ block endnd
parlist1 ::= Name {`,´ Name} [`,´ `...´] | `...´
tableconstructor ::= `{´ [fieldlist] `}´ fieldlist ::= field {fieldsep field} [fieldsep] field ::= `[´ exp `]´ `=´ exp | name `=´ exp | exp fieldsep ::= `,´ | `;´
binop ::= `+´ | `-´ | `*´ | `/´ | `^´ | `..´ | `<´ | `<=´ | `>´ | `>=´ | `==´ | `~=´ | and | or
unop ::= `-´ | not
È¡×Ô"http://www.luachina.net/wiki/index.php/Lua%E5%8F%82%E8%80%83%E6%89%8B%E5%86%8C"
- ×÷Õߣº lua 2005Äê08ÔÂ31ÈÕ, ÐÇÆÚÈý 18:31¡¡ »Ø¸´£¨0£© |¡¡ ÒýÓã¨0£© ¼ÓÈ벩²É
Lua5.0 ²Î¿¼ÊÖ²á(ÖÐÎÄ) No.3
3.3 - ¶ÑÕ»²Ù×÷
һϵÄAPIÌṩÁË»ù±¾µÄÕ»²Ù×÷£º
void lua_settop (lua_State *L, int index);
void lua_pushvalue (lua_State *L, int index);
void lua_remove (lua_State *L, int index);
void lua_insert (lua_State *L, int index);
void lua_replace (lua_State *L, int index);
lua_settop ½ÓÊÜÈκοɽÓÊܵÄË÷Òý£¬»òÕß0£¬²¢ÇÒ½«¸ÃË÷ÒýÉèÖÃΪջ¶¥¡£Èç¹ûеÄÕ»¶¥±È¾ÉµÄ¸ü´ó£¬ÄÇôÐÂÔªËØ±»ÌîÉÏ nil Öµ¡£Èç¹ûË÷ÒýΪ 0£¬ÄÇôËùÓÐÕ»ÔªËØ»á±»Çå³ý¡£ÔÚ lua.h ÀïÃæ¶¨ÒåÁËÒ»¸öÓÐÓõĺê
#define lua_pop(L,n) lua_settop(L, -(n)-1)
ÓÃÒÔ´ÓÕ»Öе¯³ö n ¸öÔªËØ¡£
lua_pushvalue ½«Ò»¸öË÷ÒýÖ¸ÏòµÄÔªËØµÄ¿½±´Ñ¹ÈëÕ»¡£ lua_remove ɾ³ýÖ¸¶¨Î»ÖõÄÔªËØ£¬½«¸ÃÔªËØÉÏ·½µÄËùÓÐÔªËØÏÂÒÆÒÔÌîÂú¿Õȱ¡£lua_insert ½«Õ»¶¥ÔªËØÒƶ¯µ½Ö¸¶¨Î»Ö㬽«¸ÃλÖÃÒÔÉϵÄÔªËØÉÏÒÆ¡£lua_replace ½«Õ»¶¥ÔªËØÒƶ¯µ½Ö¸¶¨Î»Ööø²»Òƶ¯ÆäËûÈÎºÎÆäËûÔªËØ£¨Òò´ËÌæ´úÁ˸ø¶¨Î»ÖõÄÔªËØµÄÖµ£©¡£ËùÓÐÕâЩº¯ÊýÖ»½ÓÊÜÓÐЧµÄË÷Òý¡££¨Äã²»ÄÜʹÓÃαË÷Òýµ÷Óà lua_remove »ò lua_insert£¬ÒòΪËûÃDz»´ú±íÕ»ÖеÄλÖᣣ©
¾Ù¸öÀý×Ó£¬Èç¹ûÕ»¿ªÊ¼ÓÚ 10 20 30 40 50*£¨×Ôµ×ÏòÉÏ£»`*´ ±ê¼ÇÁËÕ»¶¥£©£¬ÄÇô£º
lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
lua_remove(L, -3) --> 10 20 30 40 30 30*
lua_remove(L, 6) --> 10 20 30 40 30*
lua_insert(L, 1) --> 30 10 20 30 40*
lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
lua_replace(L, 2) --> 30 40 20 30*
lua_settop(L, -3) --> 30 40*
lua_settop(L, 6) --> 30 40 nil nil nil nil*
[±à¼]
3.4 - ¶ÑÕ»²éѯ
ÏÂÃæµÄº¯Êý¿ÉÒÔÓÃÀ´¼ì²âÕ»ÄÚÔªËØµÄÀàÐÍ£º
int lua_type (lua_State *L, int index);
int lua_isnil (lua_State *L, int index);
int lua_isboolean (lua_State *L, int index);
int lua_isnumber (lua_State *L, int index);
int lua_isstring (lua_State *L, int index);
int lua_istable (lua_State *L, int index);
int lua_isfunction (lua_State *L, int index);
int lua_iscfunction (lua_State *L, int index);
int lua_isuserdata (lua_State *L, int index);
int lua_islightuserdata (lua_State *L, int index);
ÕâЩº¯ÊýÖ»ÄÜʹÓÿɽÓÊܵÄË÷Òý¡£
lua_type ·µ»ØÕ»ÖÐÔªËØÖµµÄÀàÐÍ£¬Èç¹ûËùÓÐË÷ÒýÎÞЧÔò·µ»Ø LUA_TNONE£¨¾ÍÊÇ˵Èç¹ûջΪ¿Õ£©¡£ÕâЩlua_type ´ú±íµÄ·µ»ØÖµ×÷Ϊ³£Á¿¶¨ÒåÔÚ lua.h ÖУºLUA_TNIL, LUA_TNUMBER, LUA_TBOOLEAN, LUA_TSTRING, LUA_TTABLE, LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD, LUA_TLIGHTUSERDATA¡£ÏÂÃæµÄº¯Êý½«ÕâЩ³£Á¿×ª»»³É×Ö·û´®£º
const char *lua_typename (lua_State *L, int type);
lua_is* º¯Êý·µ»Ø 1 µ±¶ÔÏóÓëËù¸øÀàÐͼæÈݵÄʱºò£¬ÆäËûÇé¿ö·µ»Ø 0¡£ lua_isboolean ÊÇÒ»¸öÀýÍ⣺ËüÖ»Õë¶Ô²¼¶ûֵʱ²Å»á³É¹¦£¨·ñÔò½«ÊÇÎÞÓõģ¬ÒòΪÈκÎÖµ¶¼ÊÇÒ»¸ö²¼¶ûÖµ£©¡£ÕâЩº¯Êý¶ÔÓÚÎÞЧÒýÓ÷µ»Ø 0¡£ lua_isnumber ½ÓÊÜÊý×ÖºÍÓÃÊý×Ö±íʾµÄ×Ö·û´®£»lua_isstring ½ÓÊÜ×Ö·û´®ºÍÊý×Ö£¨¼û 2.2.1£©£»lua_isfunction ½ÓÊÜLuaº¯ÊýºÍCº¯Êý£» lua_isuserdata ½ÓÊÜÍêÕûµÄºÍÇáÁ¿µÄÓû§Êý¾Ý¡£ÒªÇø·ÖC º¯ÊýºÍLua º¯Êý£¬Äã¿ÉÒÔʹÓà lua_iscfunction¡£ÒªÇø·ÖÓû§Êý¾Ý£¬Äã¿ÉÒÔʹÓà lua_islightuserdata¡£ÒªÇø·ÖÊý×Ö»¹ÊÇÓÃÊý×Ö±íʾµÄ×Ö·û´®£¬Äã¿ÉÒÔʹÓà lua_type¡£
ÕâЩAPI»¹°üº¬ÁËÓÃÓڱȽÏÕ»ÖеÄÁ½¸öÖµµÄ²Ù×÷£º
int lua_equal (lua_State *L, int index1, int index2);
int lua_rawequal (lua_State *L, int index1, int index2);
int lua_lessthan (lua_State *L, int index1, int index2);
lua_equal ºÍ lua_lessthan ÔڱȽÏËûÃǵĸ±±¾µÄʱºòÊǵÈЧµÄ£¨¼û 2.5.2£©¡£ lua_rawequal ÓÃÓڱȽϻù±¾ÀàÐ͵«²»°üÀ¨Ôª·½·¨¡£Èç¹ûÓÐÈκÎÐÎʽµÄÎÞЧË÷Òý£¬ÕâЩº¯Êý¶¼·µ»Ø 0£¨false£©¡£
[±à¼]
3.5 - ¶Ñջȡֵ
ΪÁ˽«Ò»¸öÕ»ÖеÄֵת±äΪָ¶¨µÄCÓïÑÔÀàÐÍ£¬ÄãÐèҪʹÓÃÒÔϵÄת»»º¯Êý£º
int lua_toboolean (lua_State *L, int index);
lua_Number lua_tonumber (lua_State *L, int index);
const char *lua_tostring (lua_State *L, int index);
size_t lua_strlen (lua_State *L, int index);
lua_CFunction lua_tocfunction (lua_State *L, int index);
void *lua_touserdata (lua_State *L, int index);
lua_State *lua_tothread (lua_State *L, int index);
void *lua_topointer (lua_State *L, int index);
ÕâЩº¯ÊýÓÉÈκοɽÓÊÜË÷Òý×÷Ϊ²ÎÊý½øÐе÷Óᣵ±Óöµ½Ò»¸öÎÞЧË÷Òý£¬º¯Êý±íÏÖΪ¾ÍºÃÏñ½ÓÊÜÁËÒ»¸ö´íÎóÀàÐ͵ÄÖµ¡£
lua_toboolean ½«Ë÷ÒýÖ¸ÏòµÄLuaֵת»»ÎªCÓïÑÔÀàÐ͵IJ¼¶ûÖµ£¨0 »ò 1£©¡£¾ÍÏñËùÓÐLuaÖеIJâÊÔÒ»Ñù£¬Èκβ»µÈÓÚ false »òÕß nil µÄLuaֵͨ¹ý lua_toboolean ¶¼½«·µ»Ø 1£»·ñÔò½«·µ»Ø 0¡£µ±È»£¬Èç¹ûÊÇÒ»¸öÎÞЧË÷Òý£¬Ò²½«·µ»Ø 0¡££¨Èç¹ûÄãÖ»Ïë½ÓÊÜÕæÊµµÄ²¼¶ûÖµ£¬Ê¹Óà lua_isboolean È¥²âÊÔÖµµÄÀàÐÍ¡££©
lua_tonumber ½«Ë÷ÒýÖ¸ÏòµÄLuaֵת»»³ÉÒ»¸öÊý×Ö£¨Ä¬ÈÏÇé¿öÏ£¬lua_Number ÊÇ doubleÀàÐÍ£©¡£LuaÖµ±ØÐëÊÇÒ»¸öÊý×Ö»òÕß¿Éת»¯ÎªÊý×ÖµÄ×Ö·û´®£¨¼û 2.2.1£©£»·ñÔò£¬lua_tonumber ·µ»Ø 0¡£
lua_tostring ½«Ë÷ÒýÖ¸ÏòµÄLuaֵת»»³É×Ö·û´®£¨const char*£©¡£LuaÖµ±ØÐëÊÇÒ»¸ö×Ö·û´®»òÕßÊý×Ö£»·ñÔò£¬º¯Êý·µ»Ø NULL¡£Èç¹ûÖµÊÇÒ»¸öÊý×Ö£¬lua_tostring »á½«Õ»ÖеÄÕæÊµÖµ±ä³ÉÒ»¸ö×Ö·û´®ÀàÐÍ¡££¨µ± lua_tostring Ó¦ÓÃÓÚ¼üʱÕâ¸ö¸Ä±ä½«ÒýÆð lua_next µÄ»ìÂÒ¡££©lua_tostring ÔÚLua ״̬ÄÚ²¿·µ»ØÒ»¸ö×Ö·û´®µÄÖ¸Õë¡£Õâ¸ö×Ö·û´®×ÜÊÇÒÔ 0£¨'\0'£©½á⣬¾ÍÏñC ÓïÑÔÀïµÄÒ»Ñù£¬µ«ÊÇÒ²¿ÉÄܰüº¬ÆäËû 0 ÔÚÆäÖС£Èç¹ûÄã²»ÖªµÀÒ»¸ö×Ö·û´®ÖÐÊÇ·ñ´æÔÚ 0 £¬Äã¿ÉÒÔʹÓà lua_strlen µÃµ½ËüµÄʵ¼Ê³¤¶È¡£ÒòΪLua¾ßÓÐÀ¬»øÊÕ¼¯»úÖÆ£¬ËùÒÔ²»Äܱ£Ö¤ lua_tostring ·µ»ØµÄÖ¸ÕëÈÔÈ»ÓÐЧ£¬µ±ÏàÓ¦µÄÖµ´ÓÕ»ÖÐɾ³ýÖ®ºó¡£Èç¹ûÄãÔÚµ±Ç°º¯Êý·µ»ØÖ®ºó»¹ÐèÒªÕâ¸ö×Ö·û´®£¬ÄãÐèÒª¸´ÖÆËü²¢ÇÒ½«Ëü´æÈë×¢²á±í£¨¼û 3.18£©¡£
lua_tocfunction ½«Õ»ÖеÄֵת»»ÎªC º¯Êý¡£Õâ¸öÖµ±ØÐëÊÇÒ»¸öC º¯Êý£»·ñÔò£¬lua_tocfunction ·µ»Ø NULL¡£ÀàÐÍ lua_CFunction ÔÚ 3.16 ÖÐÓÐÏêϸ½âÊÍ¡£
lua_tothread ½«Õ»ÖеÄֵת»»ÎªLuaỊ̈߳¨±»Ãè»æ³É lua_State *£©¡£Õâ¸öÖµ±ØÐëÊÇÒ»¸öỊ̈߳»·ñÔò£»lua_tothread ·µ»Ø NULL¡£
lua_topointer ½«Õ»ÖеÄֵת»»ÎªÍ¨ÓõÄC ÓïÑÔÖ¸Õ루void *£©¡£Õâ¸öÖµ¿ÉÄÜÊÇÒ»¸öÓû§Êý¾Ý¡¢±í¡¢Ï̡߳¢»òÕߺ¯Êý£»·ñÔò£¬lua_topointer ·µ»Ø NULL¡£Lua±£Ö¤Í¬ÖÖÀàÐ͵IJ»Í¬¶ÔÏ󽫷µ»Ø²»Í¬Ö¸Õ롣ûÓÐÖ±½ÓµÄ·½·¨½«Ö¸Õëת»»»ØÔÀ´µÄÖµ¡£Õâ¸öº¯Êýͨ³£ÓÃÓÚµ÷ÊÔ¡£
lua_touserdata ÔÚ 3.8 ÖÐÓÐÏêϸ½âÊÍ¡£
[±à¼]
3.6 - ½«ÖµÑ¹Èë¶ÑÕ»
ÒÔϵÄAPIº¯Êý½«C ÓïÑÔֵѹÈëÕ»£º
void lua_pushboolean (lua_State *L, int b);
void lua_pushnumber (lua_State *L, lua_Number n);
void lua_pushlstring (lua_State *L, const char *s, size_t len);
void lua_pushstring (lua_State *L, const char *s);
void lua_pushnil (lua_State *L);
void lua_pushcfunction (lua_State *L, lua_CFunction f);
void lua_pushlightuserdata (lua_State *L, void *p);
ÕâЩº¯Êý½ÓÊÜÒ»¸öC ÓïÑÔÖµ£¬½«Æäת»»³ÉÏàÓ¦µÄLua Öµ£¬²¢ÇÒ½«½á¹ûѹÈëÕ»¡£ÐèÒªÌØ±ð×¢ÒâµÄÊÇ£¬lua_pushlstring ºÍ lua_pushstring ½«¶ÔËù¸øµÄ×Ö·û´®×öÒ»¸öÄÚ²¿¿½±´¡£lua_pushstring Ö»ÄÜѹÈëºÏÊʵÄC ÓïÑÔ×Ö·û´®£¨Ò²¾ÍÊÇ˵£¬×Ö·û´®ÒªÒÔ '\0' ½á⣬²¢ÇÒ²»Äܰüº¬ÄÚǶµÄ 0£©£»·ñÔò£¬ÄãÐèҪʹÓøüͨÓÃµÄ lua_pushlstring º¯Êý£¬Ëü¿ÉÒÔ½ÓÊÜÒ»¸öÖ¸¶¨µÄ´óС¡£
Äã¿ÉÒÔѹÈë¡°¸ñʽ»¯µÄ¡±×Ö·û´®£º
const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);
ÕâЩº¯Êý½«¸ñʽ»¯µÄ×Ö·û´®Ñ¹ÈëÕ»²¢ÇÒ·µ»ØÕâ¸ö×Ö·û´®µÄÖ¸Õë¡£ËüÃÇºÍ sprintf¡¢vsprintf ÀàËÆ£¬µ«ÊÇÓÐÒ»Ð©ÖØÒªµÄ²»Í¬Ö®´¦£º
Õâ¸öº¯Êý
void lua_concat (lua_State *L, int n);
Á¬½ÓÕ»¶¥µÄ n ¸öÖµ£¬½«ËüÃǵ¯³ö£¬²¢ÇÒ½«½á¹ûÁôÔÚÕ»¶¥¡£Èç¹û n Ϊ 1£¬½á¹ûÊǵ¥¸ö×Ö·û´®£¨Ò²¾ÍÊÇ˵£¬º¯ÊýʲôҲ²»×ö£©£»Èç¹û n ÊÇ 0£¬½á¹ûÊÇ¿Õ×Ö·û´®¡£Á¬½ÓµÄÍê³ÉÒÀ¾ÝLuaµÄÓïÒ壨¼û 2.5.4£©¡£
[±à¼]
3.7 - ¿ØÖÆÀ¬»øÊÕ¼¯
LuaʹÓÃÁ½¸öÊý×Ö¿ØÖÆÀ¬»øÊÕ¼¯Ñ»·¡£Ò»¸öÊý×Ö±íʾLuaʹÓõĶ¯Ì¬ÄÚ´æµÄ×Ö½ÚÊý£¬ÁíÒ»¸öÊÇ·§Öµ¡££¨¼û 2.9£©¡£Ò»¸öÊý×Ö±íʾLuaʹÓõĶ¯Ì¬ÄÚ´æµÄ×Ö½ÚÊý£¬ÁíÒ»¸öÊÇ·§Öµ¡£µ±ÄÚ´æ×Ö½ÚÊýµ½´ï·§ÖµÊ±£¬Lua¾ÍÔËÐÐÀ¬»øÊÕ¼¯Æ÷£¬À´ÊÍ·ÅËÀ¶ÔÏóµÄ¿Õ¼ä¡£Ò»µ©×Ö½Ú¼ÆÊýÆ÷±»µ÷Õû£¬ÄÇô·§Öµ¾Í»á±»ÉèΪ×Ö½Ú¼ÆÊýÆ÷ÐÂÖµµÄÁ½±¶¡£
Äã¿ÉÒÔͨ¹ýÒÔϵĺ¯ÊýµÃµ½ÕâÁ½¸öÁ¿µÄµ±Ç°Öµ£º
int lua_getgccount (lua_State *L);
int lua_getgcthreshold (lua_State *L);
ËüÃǵķµ»ØÖµµÄµ¥Î»¶¼ÊÇǧ×Ö½Ú£¨K bytes£©¡£Äã¿ÉÒÔͨ¹ýÏÂÃæµÄº¯Êý¸Ä±ä·§Öµ
void lua_setgcthreshold (lua_State *L, int newthreshold);
È»ºó£¬Ðµķ§ÖµµÃµ¥Î»Ò²ÊÇǧ×Ö½Ú¡£µ±Äãµ÷ÓÃÕâ¸öº¯Êý£¬LuaÉèÖ÷§ÐÂÖµ²¢ÇÒºÍ×Ö½Ú¼ÆÊýÆ÷×÷±È½Ï¡£Èç¹ûеķ§ÖµÐ¡ÓÚ×Ö½Ú¼ÆÊýÆ÷£¬Lua½«Á¢¿ÌÔËÐÐÀ¬»øÊÕ¼¯Æ÷¡£ÌرðÊÇ lua_setgcthreshold(L,0) Ç¿ÆÈ½øÐÐÀ¬»øÊÕ¼¯¡£ÔÚÕâÖ®ºó£¬Ò»¸öÐÂÖµ¸ù¾ÝÏÈǰµÄ¹æÔò±»ÉèÖá£
[±à¼]
3.8 - Óû§Êý¾ÝÀàÐÍ
£¨Userdata£©
Óû§Êý¾Ý´ú±íÁËLuaÖÐʹÓõÄCÓïÑÔÖµ¡£LuaÖ§³ÖÁ½ÖÖÓû§Êý¾Ý£ºÍêÕûÓû§Êý¾Ý£¨full userdata£© ºÍ ÇáÁ¿Óû§Êý¾Ý£¨light userdata£©¡£
Ò»¸öÍêÕûÓû§Êý¾Ý´ú±íÁËÒ»¿éÄÚ´æ¡£ËüÊÇÒ»¸ö¶ÔÏó£¨ÏñÒ»¸ö±í£©£ºÄã±ØÐë´´½¨Ëü£¬ËüÓÐ×Ô¼ºµÄÔª±í£¬µ±Ëü±»»ØÊÕµÄʱºòÄã¿ÉÒÔ¼ì²âµ½¡£Ò»¸öÍêÕûÓû§Êý¾ÝÖ»ÄÜÓë×Ô¼ºÏàµÈ£¨»ùÓÚÔʼµÄÏàµÈ¹æÔò£©¡£
Ò»¸öÇáÁ¿Óû§Êý¾Ý´ú±íÒ»¸öÖ¸Õë¡£ËüÊÇÒ»¸öÖµ£¨ÏñÒ»¸öÊý×Ö£©£ºÄ㲢ûÓд´½¨Ëü£¬ËüҲûÓÐÔª±í¡¢£¬Ëü²»Äܱ»»ØÊÕ£¨ÒòΪËü´Óδ±»´´½¨£©¡£ÇáÁ¿Óû§Êý¾ÝÏàµÈµÄÌõ¼þÊÇÖ¸ÕëÖ¸ÏòµÄµØÖ·Ïàͬ¡£
ÔÚLua ´úÂëÀû°ì·¨²âÊÔÓû§Êý¾ÝÀàÐÍÊÇÍêÕûµÄ»¹ÊÇÇáÁ¿µÄ£»Á½Õß¶¼ÊÇ Óû§Êý¾ÝÀàÐÍ¡£ÔÚC ´úÂëÀÈç¹ûÊÇÍêÕûÓû§Êý¾Ý£¬lua_type ·µ»Ø LUA_TUSERDATA£¬·´Ö®£¬·µ»Ø LUA_TLIGHTUSERDATA¡£
Äã¿ÉÒÔͨ¹ýÏÂÃæµÄº¯Êý´´½¨ÍêÕûÓû§Êý¾Ý£º
void *lua_newuserdata (lua_State *L, size_t size);
Õâ¸öº¯Êý¸ù¾ÝÖ¸¶¨´óС·ÖÅäÒ»¸öÄÚ´æ¿é£¬½«Óû§Êý¾ÝµÄµØÖ·Ñ¹ÈëÕ»²¢ÇÒ·µ»ØÕâ¸öµØÖ·¡£
Òª½«ÇáÁ¿Óû§Êý¾ÝѹÈëÕ»£¬ÄãÐèҪʹÓà lua_pushlightuserdata£¨¼û 3.6£©¡£
lua_touserdata £¨¼û 3.5£©ÓÃÀ´È¡»ØÓû§Êý¾ÝµÄÖµ¡£µ±ÄãÓÃÔÚÍêÕûÓû§Êý¾ÝµÄʱºò£¬Ëü·µ»ØÕâ¸ö¿éµÄµØÖ·£¬µ±ÄãÓÃÔÚÇáÁ¿Óû§Êý¾ÝµÄʱºò£¬Ëü·µ»ØËüµÄÖ¸Õ룬µ±ÄãÓÃÔÚ·ÇÓÃÊý¾ÝµÄʱºò£¬·µ»Ø NULL¡£
µ±Lua»ØÊÕÒ»¸öÍêÕûÓû§Êý¾Ý£¬Ëüµ÷ÓøÃÓû§Êý¾ÝµÄ gc Ôª·½·¨£¬È»ºóÊͷŸÃÓû§Êý¾ÝÏàÓ¦µÄÄÚ´æ¡£
[±à¼]
3.9 - Ôª±í
£¨Metatables£©
ÏÂÃæµÄº¯ÊýÔÊÐíÄã²Ù×÷¶ÔÏóµÄÔª±í£º
int lua_getmetatable (lua_State *L, int index);
int lua_setmetatable (lua_State *L, int index);
lua_getmetatable ½«Ëù¸ø¶ÔÏóµÄÔª±íѹÈëÕ»¡£Èç¹ûË÷ÒýÎÞЧ£¬»òÕâ¸ö¶ÔÏ󲻺¬ÓÐÔª±í£¬¸Ãº¯Êý·µ»Ø 0 ²¢ÇÒ²»¶ÔÕ»½øÐÐÈκβÙ×÷¡£
lua_setmetatable ´ÓÕ»Öе¯³öÒ»ÕÅ±í²¢ÇÒΪËù¸ø¶ÔÏóÉèÖÃÒ»¸öеÄÔª±í¡£µ±ÎÞ·¨¸øËù¸ø¶ÔÏóÉèÖÃÔª±íµÄʱºò¸Ãº¯Êý·µ»Ø 0£¨Ò²¾ÍÊÇ˵£¬Õâ¸ö¶ÔÏó¼È²»ÊÇÒ»¸öÓû§Êý¾ÝÒ²²»ÊÇÒ»ÕÅ±í£©£»¾¡¹ÜÄÇÑù£¬ËüÈÔ´ÓÕ»Öе¯³öÕâÕÅ±í¡£
[±à¼]
3.10 - ¼ÓÔØLuaÓï¾ä¶Î
Äã¿ÉÒÔͨ¹ý lua_load ¼ÓÔØÒ»¸öLua¿é£º
typedef const char * (*lua_Chunkreader)
(lua_State *L, void *data, size_t *size);
int lua_load (lua_State *L, lua_Chunkreader reader, void *data,
const char *chunkname);
lua_load µÄ·µ»ØÖµÊÇ£º
* 0 --- ûÓдíÎó
* LUA_ERRSYNTAX --- Ô¤±àÒëʱ¾ä·¨´íÎó
* LUA_ERRMEM --- ÄÚ´æ·ÖÅä´íÎó
Èç¹ûûÓдíÎó£¬lua_load ½«±àÒë¹ýµÄÓï¾ä¶Î×÷ΪLua º¯ÊýѹÈëÕ»¶¥¡£·ñÔò£¬Ëü½«Ñ¹ÈëÒ»¸ö´íÎóÐÅÏ¢¡£
lua_load ×Ô¶¯¼ì²âÓï¾ä¶ÎµÄÀàÐÍÊÇÎı¾»¹ÊǶþ½øÖÆÊý¾Ý£¬²¢ÇÒ¸ù¾ÝÀàÐͽ«ÆäÔØÈ루¼û³ÌÐò luac£©¡£
lua_load ʹÓÃÒ»¸öÓû§ÌṩµÄ reader º¯Êý¶ÁÈ¡Óï¾ä¶ÎµÄÄÚÈÝ¡£µ±ÐèÒªµ÷ÓÃÆäËü¶Îʱ£¬lua_load µ÷Óà reader£¬´«µÝÆä data ²ÎÊý¡£±ØÐë·µ»ØÖ¸ÏòÓï¾ä¶ÎËùÔÚµÄÐÂÄÚ´æ¿éµÄÖ¸Õ룬²¢½«¶Î´óСÉèÖÃΪ 0¡£ÎªÁ˱êÖ¾¿é⣬reader ±ØÐë·µ»Ø NULL¡£reader º¯Êý¿ÉÒÔ·µ»ØÈκδóÓÚÁãµÄÖµ¡£
ÔÚµ±Ç°µÄʵÏÖÖУ¬reader º¯Êý²»Äܵ÷ÓÃÈκÎLua º¯Êý£»ÎªÁ˱£Ö¤ÕâÒ»µã£¬Ëü×ÜÊÇ»áµÃµ½Îª NULL µÄLua״̬¡£
Óï¾ä¶ÎÃû£¨chunkname£©ÓÃÓÚ´íÎóÐÅÏ¢ºÍµ÷ÊÔÐÅÏ¢£¨¼û 4£©¡£
²Î¿¼¸¨Öú¿â (lauxlib.c) Á˽âÈçºÎʹÓà lua_load ÒÔ¼°ÈçºÎʹÓÃÏֳɵĺ¯Êý´ÓÎļþºÍ×Ö·û´®ÖмÓÔØÓï¾ä¶Î¡£
[±à¼]
3.11 - ±í²Ù×÷
ͨ¹ýµ÷ÓÃÒÔϺ¯Êý¿ÉÒÔ´´½¨±í£º
void lua_newtable (lua_State *L);
Õâ¸öº¯Êý´´½¨Ò»ÕÅÐÂµÄ¿Õ±í£¬²¢½«ÆäѹÈëÕ»¡£
Òª´ÓÕ»ÖеıíÀï¶Áȡֵ£¬Ê¹Óãº
void lua_gettable (lua_State *L, int index);
index ´ú±í±íµÄλÖá£lua_gettable ´ÓÕ»Öе¯³öÒ»¸ö¼ü£¬²¢ÇÒ·µ»Ø¸Ã¼ü¶ÔÓ¦µÄÖµ£¬±íÈÔÈ»ÁôÔÚ¶ÑÕ»ÖС£ÔÚLuaÖУ¬Õâ¸öº¯Êý¿ÉÄÜ´¥·¢Ò»¸öÕë¶Ô index ʼþµÄÔª·½·¨£¨¼û 2.8£©¡£ÏëÒªÔÚ²»µ÷ÓÃÈκÎÔª·½·¨µÄÇé¿öϵõ½±íÖ÷¼üËù¶ÔÓ¦µÄÕæÊµÖµ£¬Ê¹ÓÃÕâ¸öÔʼ£¨raw£©°æ±¾£º
void lua_rawget (lua_State *L, int index);
Òª½«Ò»¸öÖµ´¢´æµ½Õ»ÖеÄÒ»ÕűíÖУ¬ÄãÐèÒª½«¼üѹÈëÕ»£¬ÔÙ½«ÖµÑ¹ÈëÕ»£¬µ÷Óãº
void lua_settable (lua_State *L, int index);
index ´ú±í±íµÄλÖá£lua_settable ´ÓÕ»Öе¯³öÖ÷¼üºÍÖµ¡£±íÈÔÈ»ÁôÔÚÕ»ÖС£ÔÚLuaÖУ¬Õâ¸ö²Ù×÷¿ÉÄÜ´¥·¢Õë¶Ô settable »òÕß newindex ʼþµÄÔª·½·¨¡£ÏëÒª²»ÊÜÕâЩԪ·½·¨µÄÓ°Ïì²¢ÇÒΪÈÎÒâ±íÉèÖÃÖµ£¬Ê¹ÓÃÕâ¸öÔʼ£¨raw£©°æ±¾£º
void lua_rawset (lua_State *L, int index);
Äã¿ÉÒÔͨ¹ýÕâ¸öº¯Êý±éÀúÒ»ÕÅ±í£º
int lua_next (lua_State *L, int index);
index Ö¸ÏòÐèÒª±»±éÀúµÄ±í¡£Õâ¸öº¯Êý´Ó¶ÑÕ»Öе¯³öÒ»¸ö¼ü£¬´Ó±íÖÐȡһ¶Ô¼ü-ֵѹÈëÕ»£¨Ëù¸ø¼üµÄÏÂÒ»¶Ô£©¡£Èç¹ûûÓиü¶àµÄÔªËØ£¬lua_next ·µ»Ø 0£¨Ö»µ¯³öÒ»¸ö¼ü£¬²»Ñ¹ÈëÈκμü-Öµ¶Ô£©¡£Ê¹ÓÃÒ»¸ö nil ¼ü±êʾ±éÀúµÄ¿ªÊ¼¡£
Ò»¸öµäÐ͵ıéÀú²Ù×÷¿´ÆðÀ´ÕâÑù£º
/* table is in the stack at index `t' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* `key' is at index -2 and `value' at index -1 */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */
}
µ±±éÀúÒ»ÕűíµÄʱºò£¬²»ÒªÔÚ¼üÉÏÖ±½Óµ÷Óà lua_tostring£¬³ý·ÇÄãÖªµÀÕâ¸ö¼üȷʵÊÇÒ»¸ö×Ö·û´®¡£Ôٴε÷Óà lua_tostring ¸Ä±äÁËËù¸øË÷ÒýÖ¸ÏòµÄÖµ£»Õâʹ lua_next µÄµ÷Ó÷¢Éú»ìÂÒ¡£
3.12 - »·¾³±äÁ¿²Ù×÷ £¨Mani***ting Environments£©
ËùÓеÄÈ«¾Ö±äÁ¿±£´æÔÚÆÕͨµÄLua ±íÖУ¬½Ð×ö»·¾³±äÁ¿¡£³õʼµÄ»·¾³±äÁ¿±»³Æ×÷È«¾Ö»·¾³±äÁ¿¡£ÕâÕűí×ÜÊÇÔÚ LUA_GLOBALSINDEX Õâ¸öαË÷Òý´¦¡£
Òª·ÃÎÊ»ò¸Ä±äÈ«¾Ö±äÁ¿µÄÖµ£¬Äã¿ÉÒÔ¶Ô»·¾³±äÁ¿±íʹÓ󣹿µÄ±í²Ù×÷¡£¾Ù¸öÀý×Ó£¬´æÈ¡Ò»¸öÈ«¾Ö±äÁ¿µÄÖµ£º
lua_pushstring(L, varname);
lua_gettable(L, LUA_GLOBALSINDEX);
Äã¿ÉÒԸıäÒ»¸öLua Ï̵߳ÄÈ«¾Ö»·¾³±äÁ¿Í¨¹ý lua_replace º¯Êý¡£
ÒÔϵĺ¯ÊýÌṩ»ñÈ¡¡¢ÉèÖÃLuaº¯ÊýµÄ»·¾³±äÁ¿µÄ¹¦ÄÜ£º
void lua_getfenv (lua_State *L, int index);
int lua_setfenv (lua_State *L, int index);
lua_getfenv ½«¶ÑÕ»ÖÐ index Ë÷ÒýÖ¸ÏòµÄº¯ÊýµÄ»·¾³±äÁ¿±íѹÈëÕ»¡£Èç¹ûº¯ÊýÊÇÒ»¸öC º¯Êý£¬lua_getfenv ½«È«¾Ö»·¾³±äÁ¿Ñ¹ÈëÕ»¡£lua_setfenv ´ÓÕ»Öе¯³öÒ»ÕÅ±í²¢ÇÒ½«ÆäÉèÖÃΪջÖÐ index Ë÷Òý´¦µÄº¯ÊýµÄл·¾³±äÁ¿¡£Èç¹û¸ø¶¨Ë÷Òý´¦µÄ¶ÔÏó²»ÊÇÒ»¸öLua º¯Êý£¬lua_setfenv ·µ»Ø 0¡£
[±à¼]
3.13 - ½«±í×÷ΪÊý×éʹÓÃ
Using Tables as Arrays
ÓÐһЩ API Äܹ»°ïÖúÎÒÃǽ«Lua ±í×÷ΪÊý×éʹÓã¬Ò²¾ÍÊÇ˵£¬±íÖ»ÓÉÊý×Ö×÷ΪË÷Òý£º
void lua_rawgeti (lua_State *L, int index, int n);
void lua_rawseti (lua_State *L, int index, int n);
lua_rawgeti ½«±íÖÐµÄµÚ n ¸öÔªËØ·ÅÈë¶ÑÕ»ÖеÄÖ¸¶¨Î»Öà index¡£lua_rawseti ½«¶ÑÕ»ÖÐÖ¸¶¨Î»Öà index ´¦µÄ±íÖÐµÄµÚ n ¸öÔªËØµÄÖµÉ趨Ϊջ¶¥µÄÖµ£¬²¢½«ÔÀ´µÄÖµ´ÓÕ»ÖÐɾ³ý¡£
[±à¼]
3.14 - µ÷Óú¯Êý
¶¨ÒåÔÚLua Öеĺ¯ÊýºÍCÓïÑÔº¯Êý¾¹ý×¢²á¾Í¿ÉÒÔ±»ËÞÖ÷³ÌÐòµ÷Óá£ÕâЩµ÷ÓñØÐë×ñÑÒÔÏÂÐÒ飺Ê×ÏÈ£¬±»µ÷Óõĺ¯Êý±»Ñ¹ÈëÕ»£»È»ºó£¬º¯ÊýµÄ²ÎÊý±ØÐë˳Ðò£¨direct order£©ÊäÈ룬Ҳ¾ÍÊÇ˵£¬µÚÒ»¸ö²ÎÊýÐèÒª±»µÚÒ»¸öÊäÈë¡£×îºó£¬º¯Êýͨ¹ýÏÂÃæµÄ·½·¨µ÷Óãº
void lua_call (lua_State *L, int nargs, int nresults);
nargs ÊÇÄãѹÈëÕ»µÄ²ÎÊýµÄÊýÁ¿¡£ËùÓвÎÊýºÍº¯ÊýÖµ´Ó¶ÑÕ»Öе¯³ö£¬²¢ÇÒº¯Êý½á¹û±»Ñ¹ÈëÕ»¡£·µ»ØÖµµÄÊýÁ¿±»µ÷ÕûΪ nresults£¬³ý·Ç nresults ÊÇ LUA_MULTRET¡£ÔÚÄÇÖÖÇé¿öÏ£¬ËùÓк¯Êý½á¹û¶¼±»Ñ¹ÈëÕ»¡£Lua »á¼ì²â·µ»ØÖµÊÇ·ñÊʺÏÕ»¿Õ¼ä¡£º¯Êý·µ»ØÖµ°´Ë³Ðò±»Ñ¹ÈëÕ»£¨µÚÒ»¸ö·µ»ØÖµÊ×ÏÈÈëÕ»£©£¬ËùÒÔµ÷ÓýáÊøºó×îºóÒ»¸ö·µ»ØÖµÔÚÕ»¶¥¡£
ÏÂÃæµÄÀý×ÓչʾËÞÖ÷³ÌÐòÈçºÎ¿ÉÒÔºÍÕâ¸öLua ´úÂëµÈЧ£º
a = f("how", t.x, 14)
ÕâÀïÊÇC ÓïÑÔÀïµÄ×ö·¨£º
lua_pushstring(L, "t");
lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */
lua_pushstring(L, "a"); /* var name */
lua_pushstring(L, "f"); /* function name */
lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
lua_pushstring(L, "how"); /* 1st argument */
lua_pushstring(L, "x"); /* push the string "x" */
lua_gettable(L, -5); /* push result of t.x (2nd arg) */
lua_pushnumber(L, 14); /* 3rd argument */
lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */
lua_pop(L, 1); /* remove `t' from the stack */
×¢ÒâÉÏÃæµÄ´úÂëÊÇ¡°Æ½ºâµÄ¡±£ºÔÚËü½áÊøÊ±£¬¶ÑÕ»·µ»ØÔÀ´µÄÅäÖá£Õâ¸ö±»ÈÏΪÊÇÁ¼ºÃµÄ±à³Ìʵ¼ù¡£
£¨ÎªÁËչʾϸ½Ú£¬ÎÒÃÇÖ»ÓÃLua ÌṩµÄÔʼ API Íê³ÉÕâ¸öÀý×Ó¡£Í¨³£³ÌÐòÔ±¶¨Ò岢ʹÓü¸¸öºêºÍ¸¨Öú¿âº¯ÊýÔÚLua ÖÐÌṩ¸ß¼¶´æÈ¡¹¦ÄÜ¡£Çë²Î¿¼Àý×ÓÖбê×¼¿âº¯ÊýµÄÔ´´úÂë¡££©
[±à¼]
3.15 - Êܱ£»¤µ÷ÓÃ
Protected Calls
µ±Äãͨ¹ý lua_call µ÷ÓÃÒ»¸öº¯Êý£¬Ëùµ÷Óú¯ÊýÄÚ²¿²úÉúµÄ´íÎó½«ÏòÉÏ´«µÝ£¨Í¨¹ýÒ»¸ö longjmp£©¡£Èç¹ûÄãÐèÒª´¦Àí´íÎó£¬ÄãÓ¦¸ÃʹÓà lua_pcall£º
int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
nargs ºÍ nresults ÔÚ lua_call ÖÐÓÐÏàͬµÄÒâÒå¡£Èç¹ûµ÷Óùý³ÌÖÐûÓдíÎó£¬lua_pcall µÄÐÐΪ·Ç³£Ïñ lua_call ¡£È»¶ø£¬Èç¹ûÓдíÎó£¬lua_call »á²¶»ñËü£¬½«Ò»¸öµ¥Ò»Öµ£¨´íÎóÐÅÏ¢£©Ñ¹ÈëÕ»£¬²¢ÇÒ·µ»Ø´íÎó´úÂë¡£Ïñ lua_call £¬lua_pcall ×ÜÊÇ´ÓÕ»ÖÐɾ³ýº¯ÊýºÍËüµÄ²ÎÊý¡£
Èç¹û errfunc ÊÇ 0£¬Ëù·µ»ØµÄ´íÎóÐÅÏ¢¾ÍÊÇÔʼµÄ´íÎóÐÅÏ¢¡£ÁíÍ⣬errfunc ¸ø³öÒ»¸öÖ¸Ïò´íÎó´¦Àíº¯Êý£¨error handler function£©µÄÕ»Ë÷Òý¡££¨ÔÚµ±Ç°µÄʵÏÖÖУ¬Ë÷Òý²»ÄÜΪαË÷Òý¡££©¼ÙÉèÔËÐÐʱ´íÎ󣬺¯Êý½«ºÍ´íÎóÐÅÏ¢Ò»Æð±»µ÷Ó㬲¢ÇÒËûµÄ·µ»ØÖµ½«ÊÇ lua_pcall ·µ»ØµÄÐÅÏ¢¡£
´íÎó´¦Àíº¯Êý±»ÓÃÀ´Îª´íÎóÐÅÏ¢Ôö¼Ó¸ü¶àµÄµ÷ÊÔÐÅÏ¢£¬ÀýÈçÕ»µÄ¼Ç¼¡£ÕâÑùµÄÐÅÏ¢ÔÚ lua_pcall µ÷Ó÷µ»Øºó½«²»Äܱ»ÊÕ¼¯£¬Òò´ËÕ»ÒѾ±»½â¿ªÁË¡£
Èç¹û lua_pcall º¯Êýµ÷Óóɹ¦·µ»Ø 0£¬·ñÔò·µ»ØÒÔϵÄÒ»¸ö´íÎó´úÂ루¶¨ÒåÔÚ lua.h£©£º
[±à¼]
3.16 - ¶¨ÒåC º¯Êý
Lua¿ÉÒÔͨ¹ýC ÓïÑÔдµÄº¯Êý½øÐÐÀ©Õ¹£¬ÕâЩº¯Êý±ØÐëÊÇ lua_CFunction ÀàÐ͵ģ¬×÷ΪÒÔ϶¨Ò壺
typedef int (*lua_CFunction) (lua_State *L);
Ò»¸öC º¯Êý½ÓÊÕÒ»¸öLua ״̬²¢ÇÒ·µ»ØÒ»¸öÕûÊý£¬ÊýÖµÐèÒª·µ»Ø¸øLua¡£
ΪÁËÕýÈ·µÄºÍLua ͨѶ£¬C º¯Êý±ØÐë×ñÑÒÔÏÂÐÒ飬Ëü¶¨ÒåÁ˲ÎÊýºÍ·µ»ØÖµ´«µÝµÄ·½·¨£ºÒ»¸öC º¯ÊýÔÚËüµÄ¶ÑÕ»ÖдÓLua»ñȡ˳Ðò£¨µÚÒ»¸ö²ÎÊýÊ×ÏÈÈëÕ»£©²ÎÊý¡£ËùÒÔ£¬µ±º¯Êý¿ªÊ¼Ê±£¬µÚÒ»¸ö²ÎÊýÔÚË÷ÒýλÖà 1¡£ÎªÁ˽«·µ»ØÖµ´«µÝ¸øLua£¬Ò»¸öC º¯Êý½«ËüÃÇ˳ÐòѹÈëÕ»£¬²¢ÇÒ·µ»ØËüÃǵÄÊýÁ¿¡£ÈκÎÔÚ¶ÑÕ»ÖÐλÓÚ·µ»ØÖµÒÔϵÄÖµ¶¼½«±»Lua Êʵ±µÄ½â³ý¡£¾ÍÏñLua º¯ÊýÒ»Ñù£¬Ò»¸öC º¯Êý±»Lua µ÷ÓÃÒ²¿ÉÒÔ·µ»ØºÜ¶à½á¹û¡£
×÷Ϊһ¸öÀý×Ó£¬ÏÂÃæµÄº¯Êý½ÓÊÕÒ»¸öÈÎÒâÊýÁ¿µÄÊý×Ö²ÎÊý²¢ÇÒ·µ»ØËüÃÇµÄÆ½¾ùÖµºÍ×ܺϣº
static int foo (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
lua_Number sum = 0;
int i;
for (i = 1; i <= n; i++) {
if (!lua_isnumber(L, i)) {
lua_pushstring(L, "incorrect argument to function `average'");
lua_error(L);
}
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum/n); /* first result */
lua_pushnumber(L, sum); /* second result */
return 2; /* number of results */
}
ÏÂÃæÊÇһЩ±ãÀûµÄºêÓÃÀ´ÔÚLuaÖÐ×¢²áÒ»¸öC º¯Êý£º
#define lua_register(L,n,f) \
(lua_pushstring(L, n), \
lua_pushcfunction(L, f), \
lua_settable(L, LUA_GLOBALSINDEX))
/* lua_State *L; */
/* const char *n; */
/* lua_CFunction f; */
Ëü½ÓÊÕLua Öеĺ¯ÊýÃûºÍÒ»¸öÖ¸Ïòº¯ÊýµÄÖ¸Õë¡£ÕâÑù£¬ÉÏÃæµÄC º¯Êýfoo¿ÉÒÔÔÚLuaÖб»×¢²áΪ average ²¢±»µ÷Óá£
lua_register(L, "average", foo);
[±à¼]
3.17 - ¶¨ÒåC º¯Êý±Õ°ü
Defining C Closures
µ±Ò»¸öC º¯Êý±»´´½¨ºó£¬Ëü¿ÉÒÔÓëһЩֵ¹ØÁª£¬ÕâÑù´´½¨ÁËÒ»¸ö C ±Õ°ü£¨C closure£©£»ÕâЩֵ¿ÉÒÔ±»ËæÊ±±»º¯Êý·ÃÎÊ¡£ÎªÁËʹֵºÍC º¯Êý¹ØÁª£¬Ê×ÏÈÕâЩֵҪ±»Ñ¹ÈëÕ»£¨Óжà¸öֵʱ£¬µÚÒ»¸öÖµÏÈÈ룩£¬È»ºóÕâ¸öº¯Êý
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
±»ÓÃÀ´½«C º¯ÊýѹÈëÕ»£¬Í¨¹ý²ÎÊý n ¸æÖªÓ¦¸ÃÓжàÉÙ¸öÖµºÍ¸Ãº¯Êý¹ØÁª£¨lua_pushcclosure ½«ÕâЩֵ´Ó¶ÑÕ»Öе¯³ö£©£»ÊÂʵÉÏ£¬Õâ¸öºê lua_pushcfunction ±»¶¨Òå×÷Ϊ lua_pushcfunction ½« n ÉèÖÃΪ 0¡£
È»ºó£¬ÎÞÂÛºÎʱC º¯Êý±»µ÷Óã¬ÄÇЩֵ±»¶¨ÎªÓÚÖ¸¶¨µÄαË÷Òý´¦¡£ÄÇЩαË÷ÒýÓÐÒ»¸öºê lua_upvalueindex ²úÉú¡£µÚÒ»¸öºÍº¯Êý¹ØÁªµÄÖµÔÚ lua_upvalueindex(1) ´¦£¬ÆäËûµÄÒÔ´ËÀàÍÆ¡£µ± n ±Èµ±Ç°º¯ÊýµÄÉÏÖµ´óʱ£¬lua_upvalueindex(n) »á²úÉúÒ»¸ö¿É½ÓÊܵÄË÷Òý£¨µ«ÊÇÎÞЧ£©¡£
CÓïÑÔº¯ÊýºÍ¹Ø±ÕµÄÀý×Ó£¬Çë²Î¿¼Lua¹Ù·½·¢ÐаæÖеıê×¼¿â£¨src/lib/*.c£©¡£
[±à¼]
3.18 - ×¢²á±í
Registry
LuaÌṩÁËÒ»¸ö×¢²á±í£¬Ò»ÕÅ¿ÉÒÔ±»ËùÓÐC ´úÂëÓÃÀ´´¢´æÈκÎÐèÒª´¢´æµÄLuaÖµµÄÔ¤¶¨Òå±í£¬ÌرðÊÇÈç¹ûC ´úÂëÐèҪά»¤C º¯ÊýÒÔÍâ´æ»îµÄLuaÖµ¡£ÕâÕűí×ÜÊÇλÓÚ LUA_REGISTRYINDEX Õâ¸öΪË÷Òý´¦¡£ÈκÎC ÓïÑÔ¿â¿ÉÒÔ½«Êý¾Ý´¢´æÔÚÕâÕűíÖУ¬Ö»ÒªËüÑ¡ÔñµÄ¼üºÍÆäËû¿â²»Í¬¡£µäÐ͵Ä×ö·¨ÊÇÄãÓ¦¸ÃʹÓÃ×Ö·û´®×÷ΪÖ÷¼ü°üº¬ÄãµÄ¿âÃû»òÕßÔÚÄãµÄ´úÂëÖÐʹÓÃÒ»¸ö°üº¬C ¶ÔÏóµØÖ·µÄÇáÁ¿Óû§Êý¾Ý¡£
ÔÚ×¢²á±íÖеÄÕûÊý¼ü±»ÒýÓûúÖÆËùʹÓã¬Óɸ¨Öú¿âʵÏÖ£¬Òò´Ë²»Ó¦¸Ã±»ÓÃ×÷ÆäËüÓÃ;¡£
[±à¼]
3.19 - C ÖеĴíÎó´¦Àí
Error Handling in C
×ܵÄÀ´Ëµ£¬LuaʹÓÃC longjmp »úÖÆÀ´´¦Àí´íÎó¡£µ±LuaÃæ¶ÔÈκδíÎó£¨ÀýÈçÄÚ´æ·ÖÅä´íÎó£¬ÀàÐÍ´íÎ󣬾䷨´íÎó£©Ëü Òý·¢£¨raises£©Ò»¸ö´íÎó£¬Ò²¾ÍÊÇ˵£¬Ëü×öÁËÒ»¸ö³¤Ìø×ª¡£Ò»¸öÊܱ£»¤µÄ»·¾³Ê¹Óà setjmp ÉèÖÃÒ»¸ö»Ö¸´µã£»ÈκδíÎóÌøÖÁ×î½ü×î»îÔ¾µÄ»Ö¸´µã¡£
Èç¹û´íÎó·¢ÉúÔÚÈκÎÊܱ£»¤µÄ»·¾³£¬Luaµ÷Óà panic º¯Êý ²¢ÇÒËæºóµ÷ÓÃexit(EXIT_FAILURE)¡£Äã¿ÉÒÔ½«panic º¯Êý±äΪÒÔÏÂÄÚÈÝ¡£
lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
ÄãµÄÐÂpanic º¯Êý¿ÉÒÔ±ÜÃâ³ÌÐòÒòΪûÓзµ»Ø£¨ÀýÈçͨ¹ýÒ»¸ö³¤Ìø×ª£©¶øÍ˳ö¡£·ñÔò£¬ÏàÓ¦µÄLua ״̬½«²»Ò»Ö£»Î¨Ò»°²È«µÄ²Ù×÷¾ÍÊǹرÕËü¡£
¼¸ºõËùÓеÄAPI º¯Êý¶¼¿ÉÄÜÒýÆð´íÎó£¬ÀýÈçµ¼ÖÂÒ»¸öÄÚ´æ·ÖÅä´íÎó¡££ºlua_open, lua_close, lua_load ºÍ lua_pcall ÕâЩµÄº¯ÊýÔËÐÐÔÚ±£»¤Ä£Ê½Ï£¨Ò²¾ÍÊÇ˵£¬ËüÃÇ´´½¨ÁËÒ»¸öÊܱ£»¤µÄ»·¾³²¢ÔÚÆäÖÐÔËÐУ©£¬ËùÒÔËüÃÇ´Ó²»»áÒýÆð´íÎó¡£
ÓÐÁíÍâÒ»¸öº¯Êý½«Ëù¸øµÄC º¯ÊýÔËÐÐÔÚ±£»¤Ä£Ê½Ï£º
int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
lua_cpcall ÔÚ±£»¤Ä£Ê½Ïµ÷Óà func¡£func ÓÉÒ»¸ö°üº¬ ud µÄÇáÁ¿Óû§Êý¾Ý¿ªÊ¼¡£ÔÚ´íÎóÎÊÌâÉÏ£¬lua_cpcall Ïñ lua_pcall Ò»Ñù·µ»ØÏàͬµÄ´íÎó´úÂ루¼û 3.15£©£¬¼ÓÉÏÔÚÕ»¶¥µÄÒ»¸ö´íÎó¶ÔÏó£»·ñÔò£¬·µ»Ø 0£¬²¢ÇÒ²»¶Ô¶ÑÕ»½øÐÐÈκβÙ×÷¡£ÈκÎÓÉ func ·µ»ØµÄÖµ¶¼±»¶ªÆú¡£
C ´úÂë¿ÉÒÔͨ¹ýµ÷ÓÃÏÂÃæµÄº¯Êý²úÉúÒ»¸öLua´íÎó£º
void lua_error (lua_State *L);
´íÎóÐÅÏ¢£¨Êµ¼ÊÉÏ¿ÉÒÔÊÇÈκÎÀàÐ͵ĶÔÏ󣩱ØÐëÔÚÕ»¶¥¡£Õâ¸öº¯Êý½øÐÐÒ»¸ö³¤Ìø×ª£¬Òò´Ë´ÓÀ´²»»á·µ»Ø¡£
[±à¼]
3.20 - Ïß³Ì
Lua ÌṩÁ˲Ù×÷Ï̵߳IJ¿·ÖÖ§³Ö¡£Èç¹ûÄãÓжàÏß²