Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8801 lines
249 KiB

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <title>Lua 5.1 Reference Manual</title>
  5. <link rel="stylesheet" type="text/css" href="lua.css">
  6. <link rel="stylesheet" type="text/css" href="manual.css">
  7. <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
  8. </head>
  9. <body>
  10. <hr>
  11. <h1>
  12. <a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
  13. Lua 5.1 Reference Manual
  14. </h1>
  15. by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
  16. <p>
  17. <small>
  18. Copyright &copy; 2006-2008 Lua.org, PUC-Rio.
  19. Freely available under the terms of the
  20. <a href="http://www.lua.org/license.html#5">Lua license</a>.
  21. </small>
  22. <hr>
  23. <p>
  24. <a href="contents.html#contents">contents</A>
  25. &middot;
  26. <a href="contents.html#index">index</A>
  27. <!-- ====================================================================== -->
  28. <p>
  29. <!-- $Id: manual.of,v 1.48 2008/08/18 15:24:20 roberto Exp $ -->
  30. <h1>1 - <a name="1">Introduction</a></h1>
  31. <p>
  32. Lua is an extension programming language designed to support
  33. general procedural programming with data description
  34. facilities.
  35. It also offers good support for object-oriented programming,
  36. functional programming, and data-driven programming.
  37. Lua is intended to be used as a powerful, light-weight
  38. scripting language for any program that needs one.
  39. Lua is implemented as a library, written in <em>clean</em> C
  40. (that is, in the common subset of ANSI&nbsp;C and C++).
  41. <p>
  42. Being an extension language, Lua has no notion of a "main" program:
  43. it only works <em>embedded</em> in a host client,
  44. called the <em>embedding program</em> or simply the <em>host</em>.
  45. This host program can invoke functions to execute a piece of Lua code,
  46. can write and read Lua variables,
  47. and can register C&nbsp;functions to be called by Lua code.
  48. Through the use of C&nbsp;functions, Lua can be augmented to cope with
  49. a wide range of different domains,
  50. thus creating customized programming languages sharing a syntactical framework.
  51. The Lua distribution includes a sample host program called <code>lua</code>,
  52. which uses the Lua library to offer a complete, stand-alone Lua interpreter.
  53. <p>
  54. Lua is free software,
  55. and is provided as usual with no guarantees,
  56. as stated in its license.
  57. The implementation described in this manual is available
  58. at Lua's official web site, <code>www.lua.org</code>.
  59. <p>
  60. Like any other reference manual,
  61. this document is dry in places.
  62. For a discussion of the decisions behind the design of Lua,
  63. see the technical papers available at Lua's web site.
  64. For a detailed introduction to programming in Lua,
  65. see Roberto's book, <em>Programming in Lua (Second Edition)</em>.
  66. <h1>2 - <a name="2">The Language</a></h1>
  67. <p>
  68. This section describes the lexis, the syntax, and the semantics of Lua.
  69. In other words,
  70. this section describes
  71. which tokens are valid,
  72. how they can be combined,
  73. and what their combinations mean.
  74. <p>
  75. The language constructs will be explained using the usual extended BNF notation,
  76. in which
  77. {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
  78. [<em>a</em>]&nbsp;means an optional <em>a</em>.
  79. Non-terminals are shown like non-terminal,
  80. keywords are shown like <b>kword</b>,
  81. and other terminal symbols are shown like `<b>=</b>&acute;.
  82. The complete syntax of Lua can be found in <a href="#8">&sect;8</a>
  83. at the end of this manual.
  84. <h2>2.1 - <a name="2.1">Lexical Conventions</a></h2>
  85. <p>
  86. <em>Names</em>
  87. (also called <em>identifiers</em>)
  88. in Lua can be any string of letters,
  89. digits, and underscores,
  90. not beginning with a digit.
  91. This coincides with the definition of names in most languages.
  92. (The definition of letter depends on the current locale:
  93. any character considered alphabetic by the current locale
  94. can be used in an identifier.)
  95. Identifiers are used to name variables and table fields.
  96. <p>
  97. The following <em>keywords</em> are reserved
  98. and cannot be used as names:
  99. <pre>
  100. and break do else elseif
  101. end false for function if
  102. in local nil not or
  103. repeat return then true until while
  104. </pre>
  105. <p>
  106. Lua is a case-sensitive language:
  107. <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
  108. are two different, valid names.
  109. As a convention, names starting with an underscore followed by
  110. uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
  111. are reserved for internal global variables used by Lua.
  112. <p>
  113. The following strings denote other tokens:
  114. <pre>
  115. + - * / % ^ #
  116. == ~= &lt;= &gt;= &lt; &gt; =
  117. ( ) { } [ ]
  118. ; : , . .. ...
  119. </pre>
  120. <p>
  121. <em>Literal strings</em>
  122. can be delimited by matching single or double quotes,
  123. and can contain the following C-like escape sequences:
  124. '<code>\a</code>' (bell),
  125. '<code>\b</code>' (backspace),
  126. '<code>\f</code>' (form feed),
  127. '<code>\n</code>' (newline),
  128. '<code>\r</code>' (carriage return),
  129. '<code>\t</code>' (horizontal tab),
  130. '<code>\v</code>' (vertical tab),
  131. '<code>\\</code>' (backslash),
  132. '<code>\"</code>' (quotation mark [double quote]),
  133. and '<code>\'</code>' (apostrophe [single quote]).
  134. Moreover, a backslash followed by a real newline
  135. results in a newline in the string.
  136. A character in a string can also be specified by its numerical value
  137. using the escape sequence <code>\<em>ddd</em></code>,
  138. where <em>ddd</em> is a sequence of up to three decimal digits.
  139. (Note that if a numerical escape is to be followed by a digit,
  140. it must be expressed using exactly three digits.)
  141. Strings in Lua can contain any 8-bit value, including embedded zeros,
  142. which can be specified as '<code>\0</code>'.
  143. <p>
  144. Literal strings can also be defined using a long format
  145. enclosed by <em>long brackets</em>.
  146. We define an <em>opening long bracket of level <em>n</em></em> as an opening
  147. square bracket followed by <em>n</em> equal signs followed by another
  148. opening square bracket.
  149. So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
  150. an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
  151. and so on.
  152. A <em>closing long bracket</em> is defined similarly;
  153. for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
  154. A long string starts with an opening long bracket of any level and
  155. ends at the first closing long bracket of the same level.
  156. Literals in this bracketed form can run for several lines,
  157. do not interpret any escape sequences,
  158. and ignore long brackets of any other level.
  159. They can contain anything except a closing bracket of the proper level.
  160. <p>
  161. For convenience,
  162. when the opening long bracket is immediately followed by a newline,
  163. the newline is not included in the string.
  164. As an example, in a system using ASCII
  165. (in which '<code>a</code>' is coded as&nbsp;97,
  166. newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
  167. the five literal strings below denote the same string:
  168. <pre>
  169. a = 'alo\n123"'
  170. a = "alo\n123\""
  171. a = '\97lo\10\04923"'
  172. a = [[alo
  173. 123"]]
  174. a = [==[
  175. alo
  176. 123"]==]
  177. </pre>
  178. <p>
  179. A <em>numerical constant</em> can be written with an optional decimal part
  180. and an optional decimal exponent.
  181. Lua also accepts integer hexadecimal constants,
  182. by prefixing them with <code>0x</code>.
  183. Examples of valid numerical constants are
  184. <pre>
  185. 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
  186. </pre>
  187. <p>
  188. A <em>comment</em> starts with a double hyphen (<code>--</code>)
  189. anywhere outside a string.
  190. If the text immediately after <code>--</code> is not an opening long bracket,
  191. the comment is a <em>short comment</em>,
  192. which runs until the end of the line.
  193. Otherwise, it is a <em>long comment</em>,
  194. which runs until the corresponding closing long bracket.
  195. Long comments are frequently used to disable code temporarily.
  196. <h2>2.2 - <a name="2.2">Values and Types</a></h2>
  197. <p>
  198. Lua is a <em>dynamically typed language</em>.
  199. This means that
  200. variables do not have types; only values do.
  201. There are no type definitions in the language.
  202. All values carry their own type.
  203. <p>
  204. All values in Lua are <em>first-class values</em>.
  205. This means that all values can be stored in variables,
  206. passed as arguments to other functions, and returned as results.
  207. <p>
  208. There are eight basic types in Lua:
  209. <em>nil</em>, <em>boolean</em>, <em>number</em>,
  210. <em>string</em>, <em>function</em>, <em>userdata</em>,
  211. <em>thread</em>, and <em>table</em>.
  212. <em>Nil</em> is the type of the value <b>nil</b>,
  213. whose main property is to be different from any other value;
  214. it usually represents the absence of a useful value.
  215. <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
  216. Both <b>nil</b> and <b>false</b> make a condition false;
  217. any other value makes it true.
  218. <em>Number</em> represents real (double-precision floating-point) numbers.
  219. (It is easy to build Lua interpreters that use other
  220. internal representations for numbers,
  221. such as single-precision float or long integers;
  222. see file <code>luaconf.h</code>.)
  223. <em>String</em> represents arrays of characters.
  224. Lua is 8-bit clean:
  225. strings can contain any 8-bit character,
  226. including embedded zeros ('<code>\0</code>') (see <a href="#2.1">&sect;2.1</a>).
  227. <p>
  228. Lua can call (and manipulate) functions written in Lua and
  229. functions written in C
  230. (see <a href="#2.5.8">&sect;2.5.8</a>).
  231. <p>
  232. The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
  233. be stored in Lua variables.
  234. This type corresponds to a block of raw memory
  235. and has no pre-defined operations in Lua,
  236. except assignment and identity test.
  237. However, by using <em>metatables</em>,
  238. the programmer can define operations for userdata values
  239. (see <a href="#2.8">&sect;2.8</a>).
  240. Userdata values cannot be created or modified in Lua,
  241. only through the C&nbsp;API.
  242. This guarantees the integrity of data owned by the host program.
  243. <p>
  244. The type <em>thread</em> represents independent threads of execution
  245. and it is used to implement coroutines (see <a href="#2.11">&sect;2.11</a>).
  246. Do not confuse Lua threads with operating-system threads.
  247. Lua supports coroutines on all systems,
  248. even those that do not support threads.
  249. <p>
  250. The type <em>table</em> implements associative arrays,
  251. that is, arrays that can be indexed not only with numbers,
  252. but with any value (except <b>nil</b>).
  253. Tables can be <em>heterogeneous</em>;
  254. that is, they can contain values of all types (except <b>nil</b>).
  255. Tables are the sole data structuring mechanism in Lua;
  256. they can be used to represent ordinary arrays,
  257. symbol tables, sets, records, graphs, trees, etc.
  258. To represent records, Lua uses the field name as an index.
  259. The language supports this representation by
  260. providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
  261. There are several convenient ways to create tables in Lua
  262. (see <a href="#2.5.7">&sect;2.5.7</a>).
  263. <p>
  264. Like indices,
  265. the value of a table field can be of any type (except <b>nil</b>).
  266. In particular,
  267. because functions are first-class values,
  268. table fields can contain functions.
  269. Thus tables can also carry <em>methods</em> (see <a href="#2.5.9">&sect;2.5.9</a>).
  270. <p>
  271. Tables, functions, threads, and (full) userdata values are <em>objects</em>:
  272. variables do not actually <em>contain</em> these values,
  273. only <em>references</em> to them.
  274. Assignment, parameter passing, and function returns
  275. always manipulate references to such values;
  276. these operations do not imply any kind of copy.
  277. <p>
  278. The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
  279. of a given value.
  280. <h3>2.2.1 - <a name="2.2.1">Coercion</a></h3>
  281. <p>
  282. Lua provides automatic conversion between
  283. string and number values at run time.
  284. Any arithmetic operation applied to a string tries to convert
  285. this string to a number, following the usual conversion rules.
  286. Conversely, whenever a number is used where a string is expected,
  287. the number is converted to a string, in a reasonable format.
  288. For complete control over how numbers are converted to strings,
  289. use the <code>format</code> function from the string library
  290. (see <a href="#pdf-string.format"><code>string.format</code></a>).
  291. <h2>2.3 - <a name="2.3">Variables</a></h2>
  292. <p>
  293. Variables are places that store values.
  294. There are three kinds of variables in Lua:
  295. global variables, local variables, and table fields.
  296. <p>
  297. A single name can denote a global variable or a local variable
  298. (or a function's formal parameter,
  299. which is a particular kind of local variable):
  300. <pre>
  301. var ::= Name
  302. </pre><p>
  303. Name denotes identifiers, as defined in <a href="#2.1">&sect;2.1</a>.
  304. <p>
  305. Any variable is assumed to be global unless explicitly declared
  306. as a local (see <a href="#2.4.7">&sect;2.4.7</a>).
  307. Local variables are <em>lexically scoped</em>:
  308. local variables can be freely accessed by functions
  309. defined inside their scope (see <a href="#2.6">&sect;2.6</a>).
  310. <p>
  311. Before the first assignment to a variable, its value is <b>nil</b>.
  312. <p>
  313. Square brackets are used to index a table:
  314. <pre>
  315. var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
  316. </pre><p>
  317. The meaning of accesses to global variables
  318. and table fields can be changed via metatables.
  319. An access to an indexed variable <code>t[i]</code> is equivalent to
  320. a call <code>gettable_event(t,i)</code>.
  321. (See <a href="#2.8">&sect;2.8</a> for a complete description of the
  322. <code>gettable_event</code> function.
  323. This function is not defined or callable in Lua.
  324. We use it here only for explanatory purposes.)
  325. <p>
  326. The syntax <code>var.Name</code> is just syntactic sugar for
  327. <code>var["Name"]</code>:
  328. <pre>
  329. var ::= prefixexp `<b>.</b>&acute; Name
  330. </pre>
  331. <p>
  332. All global variables live as fields in ordinary Lua tables,
  333. called <em>environment tables</em> or simply
  334. <em>environments</em> (see <a href="#2.9">&sect;2.9</a>).
  335. Each function has its own reference to an environment,
  336. so that all global variables in this function
  337. will refer to this environment table.
  338. When a function is created,
  339. it inherits the environment from the function that created it.
  340. To get the environment table of a Lua function,
  341. you call <a href="#pdf-getfenv"><code>getfenv</code></a>.
  342. To replace it,
  343. you call <a href="#pdf-setfenv"><code>setfenv</code></a>.
  344. (You can only manipulate the environment of C&nbsp;functions
  345. through the debug library; (see <a href="#5.9">&sect;5.9</a>).)
  346. <p>
  347. An access to a global variable <code>x</code>
  348. is equivalent to <code>_env.x</code>,
  349. which in turn is equivalent to
  350. <pre>
  351. gettable_event(_env, "x")
  352. </pre><p>
  353. where <code>_env</code> is the environment of the running function.
  354. (See <a href="#2.8">&sect;2.8</a> for a complete description of the
  355. <code>gettable_event</code> function.
  356. This function is not defined or callable in Lua.
  357. Similarly, the <code>_env</code> variable is not defined in Lua.
  358. We use them here only for explanatory purposes.)
  359. <h2>2.4 - <a name="2.4">Statements</a></h2>
  360. <p>
  361. Lua supports an almost conventional set of statements,
  362. similar to those in Pascal or C.
  363. This set includes
  364. assignments, control structures, function calls,
  365. and variable declarations.
  366. <h3>2.4.1 - <a name="2.4.1">Chunks</a></h3>
  367. <p>
  368. The unit of execution of Lua is called a <em>chunk</em>.
  369. A chunk is simply a sequence of statements,
  370. which are executed sequentially.
  371. Each statement can be optionally followed by a semicolon:
  372. <pre>
  373. chunk ::= {stat [`<b>;</b>&acute;]}
  374. </pre><p>
  375. There are no empty statements and thus '<code>;;</code>' is not legal.
  376. <p>
  377. Lua handles a chunk as the body of an anonymous function
  378. with a variable number of arguments
  379. (see <a href="#2.5.9">&sect;2.5.9</a>).
  380. As such, chunks can define local variables,
  381. receive arguments, and return values.
  382. <p>
  383. A chunk can be stored in a file or in a string inside the host program.
  384. To execute a chunk,
  385. Lua first pre-compiles the chunk into instructions for a virtual machine,
  386. and then it executes the compiled code
  387. with an interpreter for the virtual machine.
  388. <p>
  389. Chunks can also be pre-compiled into binary form;
  390. see program <code>luac</code> for details.
  391. Programs in source and compiled forms are interchangeable;
  392. Lua automatically detects the file type and acts accordingly.
  393. <h3>2.4.2 - <a name="2.4.2">Blocks</a></h3><p>
  394. A block is a list of statements;
  395. syntactically, a block is the same as a chunk:
  396. <pre>
  397. block ::= chunk
  398. </pre>
  399. <p>
  400. A block can be explicitly delimited to produce a single statement:
  401. <pre>
  402. stat ::= <b>do</b> block <b>end</b>
  403. </pre><p>
  404. Explicit blocks are useful
  405. to control the scope of variable declarations.
  406. Explicit blocks are also sometimes used to
  407. add a <b>return</b> or <b>break</b> statement in the middle
  408. of another block (see <a href="#2.4.4">&sect;2.4.4</a>).
  409. <h3>2.4.3 - <a name="2.4.3">Assignment</a></h3>
  410. <p>
  411. Lua allows multiple assignments.
  412. Therefore, the syntax for assignment
  413. defines a list of variables on the left side
  414. and a list of expressions on the right side.
  415. The elements in both lists are separated by commas:
  416. <pre>
  417. stat ::= varlist `<b>=</b>&acute; explist
  418. varlist ::= var {`<b>,</b>&acute; var}
  419. explist ::= exp {`<b>,</b>&acute; exp}
  420. </pre><p>
  421. Expressions are discussed in <a href="#2.5">&sect;2.5</a>.
  422. <p>
  423. Before the assignment,
  424. the list of values is <em>adjusted</em> to the length of
  425. the list of variables.
  426. If there are more values than needed,
  427. the excess values are thrown away.
  428. If there are fewer values than needed,
  429. the list is extended with as many <b>nil</b>'s as needed.
  430. If the list of expressions ends with a function call,
  431. then all values returned by that call enter the list of values,
  432. before the adjustment
  433. (except when the call is enclosed in parentheses; see <a href="#2.5">&sect;2.5</a>).
  434. <p>
  435. The assignment statement first evaluates all its expressions
  436. and only then are the assignments performed.
  437. Thus the code
  438. <pre>
  439. i = 3
  440. i, a[i] = i+1, 20
  441. </pre><p>
  442. sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
  443. because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
  444. before it is assigned&nbsp;4.
  445. Similarly, the line
  446. <pre>
  447. x, y = y, x
  448. </pre><p>
  449. exchanges the values of <code>x</code> and <code>y</code>,
  450. and
  451. <pre>
  452. x, y, z = y, z, x
  453. </pre><p>
  454. cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
  455. <p>
  456. The meaning of assignments to global variables
  457. and table fields can be changed via metatables.
  458. An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
  459. <code>settable_event(t,i,val)</code>.
  460. (See <a href="#2.8">&sect;2.8</a> for a complete description of the
  461. <code>settable_event</code> function.
  462. This function is not defined or callable in Lua.
  463. We use it here only for explanatory purposes.)
  464. <p>
  465. An assignment to a global variable <code>x = val</code>
  466. is equivalent to the assignment
  467. <code>_env.x = val</code>,
  468. which in turn is equivalent to
  469. <pre>
  470. settable_event(_env, "x", val)
  471. </pre><p>
  472. where <code>_env</code> is the environment of the running function.
  473. (The <code>_env</code> variable is not defined in Lua.
  474. We use it here only for explanatory purposes.)
  475. <h3>2.4.4 - <a name="2.4.4">Control Structures</a></h3><p>
  476. The control structures
  477. <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
  478. familiar syntax:
  479. <pre>
  480. stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
  481. stat ::= <b>repeat</b> block <b>until</b> exp
  482. stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
  483. </pre><p>
  484. Lua also has a <b>for</b> statement, in two flavors (see <a href="#2.4.5">&sect;2.4.5</a>).
  485. <p>
  486. The condition expression of a
  487. control structure can return any value.
  488. Both <b>false</b> and <b>nil</b> are considered false.
  489. All values different from <b>nil</b> and <b>false</b> are considered true
  490. (in particular, the number 0 and the empty string are also true).
  491. <p>
  492. In the <b>repeat</b>&ndash;<b>until</b> loop,
  493. the inner block does not end at the <b>until</b> keyword,
  494. but only after the condition.
  495. So, the condition can refer to local variables
  496. declared inside the loop block.
  497. <p>
  498. The <b>return</b> statement is used to return values
  499. from a function or a chunk (which is just a function).
  500. Functions and chunks can return more than one value,
  501. and so the syntax for the <b>return</b> statement is
  502. <pre>
  503. stat ::= <b>return</b> [explist]
  504. </pre>
  505. <p>
  506. The <b>break</b> statement is used to terminate the execution of a
  507. <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
  508. skipping to the next statement after the loop:
  509. <pre>
  510. stat ::= <b>break</b>
  511. </pre><p>
  512. A <b>break</b> ends the innermost enclosing loop.
  513. <p>
  514. The <b>return</b> and <b>break</b>
  515. statements can only be written as the <em>last</em> statement of a block.
  516. If it is really necessary to <b>return</b> or <b>break</b> in the
  517. middle of a block,
  518. then an explicit inner block can be used,
  519. as in the idioms
  520. <code>do return end</code> and <code>do break end</code>,
  521. because now <b>return</b> and <b>break</b> are the last statements in
  522. their (inner) blocks.
  523. <h3>2.4.5 - <a name="2.4.5">For Statement</a></h3>
  524. <p>
  525. The <b>for</b> statement has two forms:
  526. one numeric and one generic.
  527. <p>
  528. The numeric <b>for</b> loop repeats a block of code while a
  529. control variable runs through an arithmetic progression.
  530. It has the following syntax:
  531. <pre>
  532. stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
  533. </pre><p>
  534. The <em>block</em> is repeated for <em>name</em> starting at the value of
  535. the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
  536. third <em>exp</em>.
  537. More precisely, a <b>for</b> statement like
  538. <pre>
  539. for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
  540. </pre><p>
  541. is equivalent to the code:
  542. <pre>
  543. do
  544. local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
  545. if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
  546. while (<em>step</em> &gt; 0 and <em>var</em> &lt;= <em>limit</em>) or (<em>step</em> &lt;= 0 and <em>var</em> &gt;= <em>limit</em>) do
  547. local v = <em>var</em>
  548. <em>block</em>
  549. <em>var</em> = <em>var</em> + <em>step</em>
  550. end
  551. end
  552. </pre><p>
  553. Note the following:
  554. <ul>
  555. <li>
  556. All three control expressions are evaluated only once,
  557. before the loop starts.
  558. They must all result in numbers.
  559. </li>
  560. <li>
  561. <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
  562. The names shown here are for explanatory purposes only.
  563. </li>
  564. <li>
  565. If the third expression (the step) is absent,
  566. then a step of&nbsp;1 is used.
  567. </li>
  568. <li>
  569. You can use <b>break</b> to exit a <b>for</b> loop.
  570. </li>
  571. <li>
  572. The loop variable <code>v</code> is local to the loop;
  573. you cannot use its value after the <b>for</b> ends or is broken.
  574. If you need this value,
  575. assign it to another variable before breaking or exiting the loop.
  576. </li>
  577. </ul>
  578. <p>
  579. The generic <b>for</b> statement works over functions,
  580. called <em>iterators</em>.
  581. On each iteration, the iterator function is called to produce a new value,
  582. stopping when this new value is <b>nil</b>.
  583. The generic <b>for</b> loop has the following syntax:
  584. <pre>
  585. stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
  586. namelist ::= Name {`<b>,</b>&acute; Name}
  587. </pre><p>
  588. A <b>for</b> statement like
  589. <pre>
  590. for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
  591. </pre><p>
  592. is equivalent to the code:
  593. <pre>
  594. do
  595. local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
  596. while true do
  597. local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
  598. <em>var</em> = <em>var_1</em>
  599. if <em>var</em> == nil then break end
  600. <em>block</em>
  601. end
  602. end
  603. </pre><p>
  604. Note the following:
  605. <ul>
  606. <li>
  607. <code><em>explist</em></code> is evaluated only once.
  608. Its results are an <em>iterator</em> function,
  609. a <em>state</em>,
  610. and an initial value for the first <em>iterator variable</em>.
  611. </li>
  612. <li>
  613. <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
  614. The names are here for explanatory purposes only.
  615. </li>
  616. <li>
  617. You can use <b>break</b> to exit a <b>for</b> loop.
  618. </li>
  619. <li>
  620. The loop variables <code><em>var_i</em></code> are local to the loop;
  621. you cannot use their values after the <b>for</b> ends.
  622. If you need these values,
  623. then assign them to other variables before breaking or exiting the loop.
  624. </li>
  625. </ul>
  626. <h3>2.4.6 - <a name="2.4.6">Function Calls as Statements</a></h3><p>
  627. To allow possible side-effects,
  628. function calls can be executed as statements:
  629. <pre>
  630. stat ::= functioncall
  631. </pre><p>
  632. In this case, all returned values are thrown away.
  633. Function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>.
  634. <h3>2.4.7 - <a name="2.4.7">Local Declarations</a></h3><p>
  635. Local variables can be declared anywhere inside a block.
  636. The declaration can include an initial assignment:
  637. <pre>
  638. stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist]
  639. </pre><p>
  640. If present, an initial assignment has the same semantics
  641. of a multiple assignment (see <a href="#2.4.3">&sect;2.4.3</a>).
  642. Otherwise, all variables are initialized with <b>nil</b>.
  643. <p>
  644. A chunk is also a block (see <a href="#2.4.1">&sect;2.4.1</a>),
  645. and so local variables can be declared in a chunk outside any explicit block.
  646. The scope of such local variables extends until the end of the chunk.
  647. <p>
  648. The visibility rules for local variables are explained in <a href="#2.6">&sect;2.6</a>.
  649. <h2>2.5 - <a name="2.5">Expressions</a></h2>
  650. <p>
  651. The basic expressions in Lua are the following:
  652. <pre>
  653. exp ::= prefixexp
  654. exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
  655. exp ::= Number
  656. exp ::= String
  657. exp ::= function
  658. exp ::= tableconstructor
  659. exp ::= `<b>...</b>&acute;
  660. exp ::= exp binop exp
  661. exp ::= unop exp
  662. prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
  663. </pre>
  664. <p>
  665. Numbers and literal strings are explained in <a href="#2.1">&sect;2.1</a>;
  666. variables are explained in <a href="#2.3">&sect;2.3</a>;
  667. function definitions are explained in <a href="#2.5.9">&sect;2.5.9</a>;
  668. function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>;
  669. table constructors are explained in <a href="#2.5.7">&sect;2.5.7</a>.
  670. Vararg expressions,
  671. denoted by three dots ('<code>...</code>'), can only be used when
  672. directly inside a vararg function;
  673. they are explained in <a href="#2.5.9">&sect;2.5.9</a>.
  674. <p>
  675. Binary operators comprise arithmetic operators (see <a href="#2.5.1">&sect;2.5.1</a>),
  676. relational operators (see <a href="#2.5.2">&sect;2.5.2</a>), logical operators (see <a href="#2.5.3">&sect;2.5.3</a>),
  677. and the concatenation operator (see <a href="#2.5.4">&sect;2.5.4</a>).
  678. Unary operators comprise the unary minus (see <a href="#2.5.1">&sect;2.5.1</a>),
  679. the unary <b>not</b> (see <a href="#2.5.3">&sect;2.5.3</a>),
  680. and the unary <em>length operator</em> (see <a href="#2.5.5">&sect;2.5.5</a>).
  681. <p>
  682. Both function calls and vararg expressions can result in multiple values.
  683. If an expression is used as a statement
  684. (only possible for function calls (see <a href="#2.4.6">&sect;2.4.6</a>)),
  685. then its return list is adjusted to zero elements,
  686. thus discarding all returned values.
  687. If an expression is used as the last (or the only) element
  688. of a list of expressions,
  689. then no adjustment is made
  690. (unless the call is enclosed in parentheses).
  691. In all other contexts,
  692. Lua adjusts the result list to one element,
  693. discarding all values except the first one.
  694. <p>
  695. Here are some examples:
  696. <pre>
  697. f() -- adjusted to 0 results
  698. g(f(), x) -- f() is adjusted to 1 result
  699. g(x, f()) -- g gets x plus all results from f()
  700. a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
  701. a,b = ... -- a gets the first vararg parameter, b gets
  702. -- the second (both a and b can get nil if there
  703. -- is no corresponding vararg parameter)
  704. a,b,c = x, f() -- f() is adjusted to 2 results
  705. a,b,c = f() -- f() is adjusted to 3 results
  706. return f() -- returns all results from f()
  707. return ... -- returns all received vararg parameters
  708. return x,y,f() -- returns x, y, and all results from f()
  709. {f()} -- creates a list with all results from f()
  710. {...} -- creates a list with all vararg parameters
  711. {f(), nil} -- f() is adjusted to 1 result
  712. </pre>
  713. <p>
  714. Any expression enclosed in parentheses always results in only one value.
  715. Thus,
  716. <code>(f(x,y,z))</code> is always a single value,
  717. even if <code>f</code> returns several values.
  718. (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
  719. or <b>nil</b> if <code>f</code> does not return any values.)
  720. <h3>2.5.1 - <a name="2.5.1">Arithmetic Operators</a></h3><p>
  721. Lua supports the usual arithmetic operators:
  722. the binary <code>+</code> (addition),
  723. <code>-</code> (subtraction), <code>*</code> (multiplication),
  724. <code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
  725. and unary <code>-</code> (negation).
  726. If the operands are numbers, or strings that can be converted to
  727. numbers (see <a href="#2.2.1">&sect;2.2.1</a>),
  728. then all operations have the usual meaning.
  729. Exponentiation works for any exponent.
  730. For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
  731. Modulo is defined as
  732. <pre>
  733. a % b == a - math.floor(a/b)*b
  734. </pre><p>
  735. That is, it is the remainder of a division that rounds
  736. the quotient towards minus infinity.
  737. <h3>2.5.2 - <a name="2.5.2">Relational Operators</a></h3><p>
  738. The relational operators in Lua are
  739. <pre>
  740. == ~= &lt; &gt; &lt;= &gt;=
  741. </pre><p>
  742. These operators always result in <b>false</b> or <b>true</b>.
  743. <p>
  744. Equality (<code>==</code>) first compares the type of its operands.
  745. If the types are different, then the result is <b>false</b>.
  746. Otherwise, the values of the operands are compared.
  747. Numbers and strings are compared in the usual way.
  748. Objects (tables, userdata, threads, and functions)
  749. are compared by <em>reference</em>:
  750. two objects are considered equal only if they are the <em>same</em> object.
  751. Every time you create a new object
  752. (a table, userdata, thread, or function),
  753. this new object is different from any previously existing object.
  754. <p>
  755. You can change the way that Lua compares tables and userdata
  756. by using the "eq" metamethod (see <a href="#2.8">&sect;2.8</a>).
  757. <p>
  758. The conversion rules of <a href="#2.2.1">&sect;2.2.1</a>
  759. <em>do not</em> apply to equality comparisons.
  760. Thus, <code>"0"==0</code> evaluates to <b>false</b>,
  761. and <code>t[0]</code> and <code>t["0"]</code> denote different
  762. entries in a table.
  763. <p>
  764. The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
  765. <p>
  766. The order operators work as follows.
  767. If both arguments are numbers, then they are compared as such.
  768. Otherwise, if both arguments are strings,
  769. then their values are compared according to the current locale.
  770. Otherwise, Lua tries to call the "lt" or the "le"
  771. metamethod (see <a href="#2.8">&sect;2.8</a>).
  772. A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
  773. and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
  774. <h3>2.5.3 - <a name="2.5.3">Logical Operators</a></h3><p>
  775. The logical operators in Lua are
  776. <b>and</b>, <b>or</b>, and <b>not</b>.
  777. Like the control structures (see <a href="#2.4.4">&sect;2.4.4</a>),
  778. all logical operators consider both <b>false</b> and <b>nil</b> as false
  779. and anything else as true.
  780. <p>
  781. The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
  782. The conjunction operator <b>and</b> returns its first argument
  783. if this value is <b>false</b> or <b>nil</b>;
  784. otherwise, <b>and</b> returns its second argument.
  785. The disjunction operator <b>or</b> returns its first argument
  786. if this value is different from <b>nil</b> and <b>false</b>;
  787. otherwise, <b>or</b> returns its second argument.
  788. Both <b>and</b> and <b>or</b> use short-cut evaluation;
  789. that is,
  790. the second operand is evaluated only if necessary.
  791. Here are some examples:
  792. <pre>
  793. 10 or 20 --&gt; 10
  794. 10 or error() --&gt; 10
  795. nil or "a" --&gt; "a"
  796. nil and 10 --&gt; nil
  797. false and error() --&gt; false
  798. false and nil --&gt; false
  799. false or nil --&gt; nil
  800. 10 and 20 --&gt; 20
  801. </pre><p>
  802. (In this manual,
  803. <code>--&gt;</code> indicates the result of the preceding expression.)
  804. <h3>2.5.4 - <a name="2.5.4">Concatenation</a></h3><p>
  805. The string concatenation operator in Lua is
  806. denoted by two dots ('<code>..</code>').
  807. If both operands are strings or numbers, then they are converted to
  808. strings according to the rules mentioned in <a href="#2.2.1">&sect;2.2.1</a>.
  809. Otherwise, the "concat" metamethod is called (see <a href="#2.8">&sect;2.8</a>).
  810. <h3>2.5.5 - <a name="2.5.5">The Length Operator</a></h3>
  811. <p>
  812. The length operator is denoted by the unary operator <code>#</code>.
  813. The length of a string is its number of bytes
  814. (that is, the usual meaning of string length when each
  815. character is one byte).
  816. <p>
  817. The length of a table <code>t</code> is defined to be any
  818. integer index <code>n</code>
  819. such that <code>t[n]</code> is not <b>nil</b> and <code>t[n+1]</code> is <b>nil</b>;
  820. moreover, if <code>t[1]</code> is <b>nil</b>, <code>n</code> can be zero.
  821. For a regular array, with non-nil values from 1 to a given <code>n</code>,
  822. its length is exactly that <code>n</code>,
  823. the index of its last value.
  824. If the array has "holes"
  825. (that is, <b>nil</b> values between other non-nil values),
  826. then <code>#t</code> can be any of the indices that
  827. directly precedes a <b>nil</b> value
  828. (that is, it may consider any such <b>nil</b> value as the end of
  829. the array).
  830. <h3>2.5.6 - <a name="2.5.6">Precedence</a></h3><p>
  831. Operator precedence in Lua follows the table below,
  832. from lower to higher priority:
  833. <pre>
  834. or
  835. and
  836. &lt; &gt; &lt;= &gt;= ~= ==
  837. ..
  838. + -
  839. * / %
  840. not # - (unary)
  841. ^
  842. </pre><p>
  843. As usual,
  844. you can use parentheses to change the precedences of an expression.
  845. The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
  846. operators are right associative.
  847. All other binary operators are left associative.
  848. <h3>2.5.7 - <a name="2.5.7">Table Constructors</a></h3><p>
  849. Table constructors are expressions that create tables.
  850. Every time a constructor is evaluated, a new table is created.
  851. A constructor can be used to create an empty table
  852. or to create a table and initialize some of its fields.
  853. The general syntax for constructors is
  854. <pre>
  855. tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
  856. fieldlist ::= field {fieldsep field} [fieldsep]
  857. field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
  858. fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
  859. </pre>
  860. <p>
  861. Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
  862. with key <code>exp1</code> and value <code>exp2</code>.
  863. A field of the form <code>name = exp</code> is equivalent to
  864. <code>["name"] = exp</code>.
  865. Finally, fields of the form <code>exp</code> are equivalent to
  866. <code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
  867. starting with 1.
  868. Fields in the other formats do not affect this counting.
  869. For example,
  870. <pre>
  871. a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
  872. </pre><p>
  873. is equivalent to
  874. <pre>
  875. do
  876. local t = {}
  877. t[f(1)] = g
  878. t[1] = "x" -- 1st exp
  879. t[2] = "y" -- 2nd exp
  880. t.x = 1 -- t["x"] = 1
  881. t[3] = f(x) -- 3rd exp
  882. t[30] = 23
  883. t[4] = 45 -- 4th exp
  884. a = t
  885. end
  886. </pre>
  887. <p>
  888. If the last field in the list has the form <code>exp</code>
  889. and the expression is a function call or a vararg expression,
  890. then all values returned by this expression enter the list consecutively
  891. (see <a href="#2.5.8">&sect;2.5.8</a>).
  892. To avoid this,
  893. enclose the function call or the vararg expression
  894. in parentheses (see <a href="#2.5">&sect;2.5</a>).
  895. <p>
  896. The field list can have an optional trailing separator,
  897. as a convenience for machine-generated code.
  898. <h3>2.5.8 - <a name="2.5.8">Function Calls</a></h3><p>
  899. A function call in Lua has the following syntax:
  900. <pre>
  901. functioncall ::= prefixexp args
  902. </pre><p>
  903. In a function call,
  904. first prefixexp and args are evaluated.
  905. If the value of prefixexp has type <em>function</em>,
  906. then this function is called
  907. with the given arguments.
  908. Otherwise, the prefixexp "call" metamethod is called,
  909. having as first parameter the value of prefixexp,
  910. followed by the original call arguments
  911. (see <a href="#2.8">&sect;2.8</a>).
  912. <p>
  913. The form
  914. <pre>
  915. functioncall ::= prefixexp `<b>:</b>&acute; Name args
  916. </pre><p>
  917. can be used to call "methods".
  918. A call <code>v:name(<em>args</em>)</code>
  919. is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
  920. except that <code>v</code> is evaluated only once.
  921. <p>
  922. Arguments have the following syntax:
  923. <pre>
  924. args ::= `<b>(</b>&acute; [explist] `<b>)</b>&acute;
  925. args ::= tableconstructor
  926. args ::= String
  927. </pre><p>
  928. All argument expressions are evaluated before the call.
  929. A call of the form <code>f{<em>fields</em>}</code> is
  930. syntactic sugar for <code>f({<em>fields</em>})</code>;
  931. that is, the argument list is a single new table.
  932. A call of the form <code>f'<em>string</em>'</code>
  933. (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
  934. is syntactic sugar for <code>f('<em>string</em>')</code>;
  935. that is, the argument list is a single literal string.
  936. <p>
  937. As an exception to the free-format syntax of Lua,
  938. you cannot put a line break before the '<code>(</code>' in a function call.
  939. This restriction avoids some ambiguities in the language.
  940. If you write
  941. <pre>
  942. a = f
  943. (g).x(a)
  944. </pre><p>
  945. Lua would see that as a single statement, <code>a = f(g).x(a)</code>.
  946. So, if you want two statements, you must add a semi-colon between them.
  947. If you actually want to call <code>f</code>,
  948. you must remove the line break before <code>(g)</code>.
  949. <p>
  950. A call of the form <code>return</code> <em>functioncall</em> is called
  951. a <em>tail call</em>.
  952. Lua implements <em>proper tail calls</em>
  953. (or <em>proper tail recursion</em>):
  954. in a tail call,
  955. the called function reuses the stack entry of the calling function.
  956. Therefore, there is no limit on the number of nested tail calls that
  957. a program can execute.
  958. However, a tail call erases any debug information about the
  959. calling function.
  960. Note that a tail call only happens with a particular syntax,
  961. where the <b>return</b> has one single function call as argument;
  962. this syntax makes the calling function return exactly
  963. the returns of the called function.
  964. So, none of the following examples are tail calls:
  965. <pre>
  966. return (f(x)) -- results adjusted to 1
  967. return 2 * f(x)
  968. return x, f(x) -- additional results
  969. f(x); return -- results discarded
  970. return x or f(x) -- results adjusted to 1
  971. </pre>
  972. <h3>2.5.9 - <a name="2.5.9">Function Definitions</a></h3>
  973. <p>
  974. The syntax for function definition is
  975. <pre>
  976. function ::= <b>function</b> funcbody
  977. funcbody ::= `<b>(</b>&acute; [parlist] `<b>)</b>&acute; block <b>end</b>
  978. </pre>
  979. <p>
  980. The following syntactic sugar simplifies function definitions:
  981. <pre>
  982. stat ::= <b>function</b> funcname funcbody
  983. stat ::= <b>local</b> <b>function</b> Name funcbody
  984. funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
  985. </pre><p>
  986. The statement
  987. <pre>
  988. function f () <em>body</em> end
  989. </pre><p>
  990. translates to
  991. <pre>
  992. f = function () <em>body</em> end
  993. </pre><p>
  994. The statement
  995. <pre>
  996. function t.a.b.c.f () <em>body</em> end
  997. </pre><p>
  998. translates to
  999. <pre>
  1000. t.a.b.c.f = function () <em>body</em> end
  1001. </pre><p>
  1002. The statement
  1003. <pre>
  1004. local function f () <em>body</em> end
  1005. </pre><p>
  1006. translates to
  1007. <pre>
  1008. local f; f = function () <em>body</em> end
  1009. </pre><p>
  1010. <em>not</em> to
  1011. <pre>
  1012. local f = function () <em>body</em> end
  1013. </pre><p>
  1014. (This only makes a difference when the body of the function
  1015. contains references to <code>f</code>.)
  1016. <p>
  1017. A function definition is an executable expression,
  1018. whose value has type <em>function</em>.
  1019. When Lua pre-compiles a chunk,
  1020. all its function bodies are pre-compiled too.
  1021. Then, whenever Lua executes the function definition,
  1022. the function is <em>instantiated</em> (or <em>closed</em>).
  1023. This function instance (or <em>closure</em>)
  1024. is the final value of the expression.
  1025. Different instances of the same function
  1026. can refer to different external local variables
  1027. and can have different environment tables.
  1028. <p>
  1029. Parameters act as local variables that are
  1030. initialized with the argument values:
  1031. <pre>
  1032. parlist ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
  1033. </pre><p>
  1034. When a function is called,
  1035. the list of arguments is adjusted to
  1036. the length of the list of parameters,
  1037. unless the function is a variadic or <em>vararg function</em>,
  1038. which is
  1039. indicated by three dots ('<code>...</code>') at the end of its parameter list.
  1040. A vararg function does not adjust its argument list;
  1041. instead, it collects all extra arguments and supplies them
  1042. to the function through a <em>vararg expression</em>,
  1043. which is also written as three dots.
  1044. The value of this expression is a list of all actual extra arguments,
  1045. similar to a function with multiple results.
  1046. If a vararg expression is used inside another expression
  1047. or in the middle of a list of expressions,
  1048. then its return list is adjusted to one element.
  1049. If the expression is used as the last element of a list of expressions,
  1050. then no adjustment is made
  1051. (unless that last expression is enclosed in parentheses).
  1052. <p>
  1053. As an example, consider the following definitions:
  1054. <pre>
  1055. function f(a, b) end
  1056. function g(a, b, ...) end
  1057. function r() return 1,2,3 end
  1058. </pre><p>
  1059. Then, we have the following mapping from arguments to parameters and
  1060. to the vararg expression:
  1061. <pre>
  1062. CALL PARAMETERS
  1063. f(3) a=3, b=nil
  1064. f(3, 4) a=3, b=4
  1065. f(3, 4, 5) a=3, b=4
  1066. f(r(), 10) a=1, b=10
  1067. f(r()) a=1, b=2
  1068. g(3) a=3, b=nil, ... --&gt; (nothing)
  1069. g(3, 4) a=3, b=4, ... --&gt; (nothing)
  1070. g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
  1071. g(5, r()) a=5, b=1, ... --&gt; 2 3
  1072. </pre>
  1073. <p>
  1074. Results are returned using the <b>return</b> statement (see <a href="#2.4.4">&sect;2.4.4</a>).
  1075. If control reaches the end of a function
  1076. without encountering a <b>return</b> statement,
  1077. then the function returns with no results.
  1078. <p>
  1079. The <em>colon</em> syntax
  1080. is used for defining <em>methods</em>,
  1081. that is, functions that have an implicit extra parameter <code>self</code>.
  1082. Thus, the statement
  1083. <pre>
  1084. function t.a.b.c:f (<em>params</em>) <em>body</em> end
  1085. </pre><p>
  1086. is syntactic sugar for
  1087. <pre>
  1088. t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
  1089. </pre>
  1090. <h2>2.6 - <a name="2.6">Visibility Rules</a></h2>
  1091. <p>
  1092. Lua is a lexically scoped language.
  1093. The scope of variables begins at the first statement <em>after</em>
  1094. their declaration and lasts until the end of the innermost block that
  1095. includes the declaration.
  1096. Consider the following example:
  1097. <pre>
  1098. x = 10 -- global variable
  1099. do -- new block
  1100. local x = x -- new 'x', with value 10
  1101. print(x) --&gt; 10
  1102. x = x+1
  1103. do -- another block
  1104. local x = x+1 -- another 'x'
  1105. print(x) --&gt; 12
  1106. end
  1107. print(x) --&gt; 11
  1108. end
  1109. print(x) --&gt; 10 (the global one)
  1110. </pre>
  1111. <p>
  1112. Notice that, in a declaration like <code>local x = x</code>,
  1113. the new <code>x</code> being declared is not in scope yet,
  1114. and so the second <code>x</code> refers to the outside variable.
  1115. <p>
  1116. Because of the lexical scoping rules,
  1117. local variables can be freely accessed by functions
  1118. defined inside their scope.
  1119. A local variable used by an inner function is called
  1120. an <em>upvalue</em>, or <em>external local variable</em>,
  1121. inside the inner function.
  1122. <p>
  1123. Notice that each execution of a <b>local</b> statement
  1124. defines new local variables.
  1125. Consider the following example:
  1126. <pre>
  1127. a = {}
  1128. local x = 20
  1129. for i=1,10 do
  1130. local y = 0
  1131. a[i] = function () y=y+1; return x+y end
  1132. end
  1133. </pre><p>
  1134. The loop creates ten closures
  1135. (that is, ten instances of the anonymous function).
  1136. Each of these closures uses a different <code>y</code> variable,
  1137. while all of them share the same <code>x</code>.
  1138. <h2>2.7 - <a name="2.7">Error Handling</a></h2>
  1139. <p>
  1140. Because Lua is an embedded extension language,
  1141. all Lua actions start from C&nbsp;code in the host program
  1142. calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
  1143. Whenever an error occurs during Lua compilation or execution,
  1144. control returns to C,
  1145. which can take appropriate measures
  1146. (such as printing an error message).
  1147. <p>
  1148. Lua code can explicitly generate an error by calling the
  1149. <a href="#pdf-error"><code>error</code></a> function.
  1150. If you need to catch errors in Lua,
  1151. you can use the <a href="#pdf-pcall"><code>pcall</code></a> function.
  1152. <h2>2.8 - <a name="2.8">Metatables</a></h2>
  1153. <p>
  1154. Every value in Lua can have a <em>metatable</em>.
  1155. This <em>metatable</em> is an ordinary Lua table
  1156. that defines the behavior of the original value
  1157. under certain special operations.
  1158. You can change several aspects of the behavior
  1159. of operations over a value by setting specific fields in its metatable.
  1160. For instance, when a non-numeric value is the operand of an addition,
  1161. Lua checks for a function in the field <code>"__add"</code> in its metatable.
  1162. If it finds one,
  1163. Lua calls this function to perform the addition.
  1164. <p>
  1165. We call the keys in a metatable <em>events</em>
  1166. and the values <em>metamethods</em>.
  1167. In the previous example, the event is <code>"add"</code>
  1168. and the metamethod is the function that performs the addition.
  1169. <p>
  1170. You can query the metatable of any value
  1171. through the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
  1172. <p>
  1173. You can replace the metatable of tables
  1174. through the <a href="#pdf-setmetatable"><code>setmetatable</code></a>
  1175. function.
  1176. You cannot change the metatable of other types from Lua
  1177. (except by using the debug library);
  1178. you must use the C&nbsp;API for that.
  1179. <p>
  1180. Tables and full userdata have individual metatables
  1181. (although multiple tables and userdata can share their metatables).
  1182. Values of all other types share one single metatable per type;
  1183. that is, there is one single metatable for all numbers,
  1184. one for all strings, etc.
  1185. <p>
  1186. A metatable controls how an object behaves in arithmetic operations,
  1187. order comparisons, concatenation, length operation, and indexing.
  1188. A metatable also can define a function to be called when a userdata
  1189. is garbage collected.
  1190. For each of these operations Lua associates a specific key
  1191. called an <em>event</em>.
  1192. When Lua performs one of these operations over a value,
  1193. it checks whether this value has a metatable with the corresponding event.
  1194. If so, the value associated with that key (the metamethod)
  1195. controls how Lua will perform the operation.
  1196. <p>
  1197. Metatables control the operations listed next.
  1198. Each operation is identified by its corresponding name.
  1199. The key for each operation is a string with its name prefixed by
  1200. two underscores, '<code>__</code>';
  1201. for instance, the key for operation "add" is the
  1202. string <code>"__add"</code>.
  1203. The semantics of these operations is better explained by a Lua function
  1204. describing how the interpreter executes the operation.
  1205. <p>
  1206. The code shown here in Lua is only illustrative;
  1207. the real behavior is hard coded in the interpreter
  1208. and it is much more efficient than this simulation.
  1209. All functions used in these descriptions
  1210. (<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
  1211. are described in <a href="#5.1">&sect;5.1</a>.
  1212. In particular, to retrieve the metamethod of a given object,
  1213. we use the expression
  1214. <pre>
  1215. metatable(obj)[event]
  1216. </pre><p>
  1217. This should be read as
  1218. <pre>
  1219. rawget(getmetatable(obj) or {}, event)
  1220. </pre><p>
  1221. That is, the access to a metamethod does not invoke other metamethods,
  1222. and the access to objects with no metatables does not fail
  1223. (it simply results in <b>nil</b>).
  1224. <ul>
  1225. <li><b>"add":</b>
  1226. the <code>+</code> operation.
  1227. <p>
  1228. The function <code>getbinhandler</code> below defines how Lua chooses a handler
  1229. for a binary operation.
  1230. First, Lua tries the first operand.
  1231. If its type does not define a handler for the operation,
  1232. then Lua tries the second operand.
  1233. <pre>
  1234. function getbinhandler (op1, op2, event)
  1235. return metatable(op1)[event] or metatable(op2)[event]
  1236. end
  1237. </pre><p>
  1238. By using this function,
  1239. the behavior of the <code>op1 + op2</code> is
  1240. <pre>
  1241. function add_event (op1, op2)
  1242. local o1, o2 = tonumber(op1), tonumber(op2)
  1243. if o1 and o2 then -- both operands are numeric?
  1244. return o1 + o2 -- '+' here is the primitive 'add'
  1245. else -- at least one of the operands is not numeric
  1246. local h = getbinhandler(op1, op2, "__add")
  1247. if h then
  1248. -- call the handler with both operands
  1249. return (h(op1, op2))
  1250. else -- no handler available: default behavior
  1251. error(&middot;&middot;&middot;)
  1252. end
  1253. end
  1254. end
  1255. </pre><p>
  1256. </li>
  1257. <li><b>"sub":</b>
  1258. the <code>-</code> operation.
  1259. Behavior similar to the "add" operation.
  1260. </li>
  1261. <li><b>"mul":</b>
  1262. the <code>*</code> operation.
  1263. Behavior similar to the "add" operation.
  1264. </li>
  1265. <li><b>"div":</b>
  1266. the <code>/</code> operation.
  1267. Behavior similar to the "add" operation.
  1268. </li>
  1269. <li><b>"mod":</b>
  1270. the <code>%</code> operation.
  1271. Behavior similar to the "add" operation,
  1272. with the operation
  1273. <code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
  1274. </li>
  1275. <li><b>"pow":</b>
  1276. the <code>^</code> (exponentiation) operation.
  1277. Behavior similar to the "add" operation,
  1278. with the function <code>pow</code> (from the C&nbsp;math library)
  1279. as the primitive operation.
  1280. </li>
  1281. <li><b>"unm":</b>
  1282. the unary <code>-</code> operation.
  1283. <pre>
  1284. function unm_event (op)
  1285. local o = tonumber(op)
  1286. if o then -- operand is numeric?
  1287. return -o -- '-' here is the primitive 'unm'
  1288. else -- the operand is not numeric.
  1289. -- Try to get a handler from the operand
  1290. local h = metatable(op).__unm
  1291. if h then
  1292. -- call the handler with the operand
  1293. return (h(op))
  1294. else -- no handler available: default behavior
  1295. error(&middot;&middot;&middot;)
  1296. end
  1297. end
  1298. end
  1299. </pre><p>
  1300. </li>
  1301. <li><b>"concat":</b>
  1302. the <code>..</code> (concatenation) operation.
  1303. <pre>
  1304. function concat_event (op1, op2)
  1305. if (type(op1) == "string" or type(op1) == "number") and
  1306. (type(op2) == "string" or type(op2) == "number") then
  1307. return op1 .. op2 -- primitive string concatenation
  1308. else
  1309. local h = getbinhandler(op1, op2, "__concat")
  1310. if h then
  1311. return (h(op1, op2))
  1312. else
  1313. error(&middot;&middot;&middot;)
  1314. end
  1315. end
  1316. end
  1317. </pre><p>
  1318. </li>
  1319. <li><b>"len":</b>
  1320. the <code>#</code> operation.
  1321. <pre>
  1322. function len_event (op)
  1323. if type(op) == "string" then
  1324. return strlen(op) -- primitive string length
  1325. elseif type(op) == "table" then
  1326. return #op -- primitive table length
  1327. else
  1328. local h = metatable(op).__len
  1329. if h then
  1330. -- call the handler with the operand
  1331. return (h(op))
  1332. else -- no handler available: default behavior
  1333. error(&middot;&middot;&middot;)
  1334. end
  1335. end
  1336. end
  1337. </pre><p>
  1338. See <a href="#2.5.5">&sect;2.5.5</a> for a description of the length of a table.
  1339. </li>
  1340. <li><b>"eq":</b>
  1341. the <code>==</code> operation.
  1342. The function <code>getcomphandler</code> defines how Lua chooses a metamethod
  1343. for comparison operators.
  1344. A metamethod only is selected when both objects
  1345. being compared have the same type
  1346. and the same metamethod for the selected operation.
  1347. <pre>
  1348. function getcomphandler (op1, op2, event)
  1349. if type(op1) ~= type(op2) then return nil end
  1350. local mm1 = metatable(op1)[event]
  1351. local mm2 = metatable(op2)[event]
  1352. if mm1 == mm2 then return mm1 else return nil end
  1353. end
  1354. </pre><p>
  1355. The "eq" event is defined as follows:
  1356. <pre>
  1357. function eq_event (op1, op2)
  1358. if type(op1) ~= type(op2) then -- different types?
  1359. return false -- different objects
  1360. end
  1361. if op1 == op2 then -- primitive equal?
  1362. return true -- objects are equal
  1363. end
  1364. -- try metamethod
  1365. local h = getcomphandler(op1, op2, "__eq")
  1366. if h then
  1367. return (h(op1, op2))
  1368. else
  1369. return false
  1370. end
  1371. end
  1372. </pre><p>
  1373. <code>a ~= b</code> is equivalent to <code>not (a == b)</code>.
  1374. </li>
  1375. <li><b>"lt":</b>
  1376. the <code>&lt;</code> operation.
  1377. <pre>
  1378. function lt_event (op1, op2)
  1379. if type(op1) == "number" and type(op2) == "number" then
  1380. return op1 &lt; op2 -- numeric comparison
  1381. elseif type(op1) == "string" and type(op2) == "string" then
  1382. return op1 &lt; op2 -- lexicographic comparison
  1383. else
  1384. local h = getcomphandler(op1, op2, "__lt")
  1385. if h then
  1386. return (h(op1, op2))
  1387. else
  1388. error(&middot;&middot;&middot;)
  1389. end
  1390. end
  1391. end
  1392. </pre><p>
  1393. <code>a &gt; b</code> is equivalent to <code>b &lt; a</code>.
  1394. </li>
  1395. <li><b>"le":</b>
  1396. the <code>&lt;=</code> operation.
  1397. <pre>
  1398. function le_event (op1, op2)
  1399. if type(op1) == "number" and type(op2) == "number" then
  1400. return op1 &lt;= op2 -- numeric comparison
  1401. elseif type(op1) == "string" and type(op2) == "string" then
  1402. return op1 &lt;= op2 -- lexicographic comparison
  1403. else
  1404. local h = getcomphandler(op1, op2, "__le")
  1405. if h then
  1406. return (h(op1, op2))
  1407. else
  1408. h = getcomphandler(op1, op2, "__lt")
  1409. if h then
  1410. return not h(op2, op1)
  1411. else
  1412. error(&middot;&middot;&middot;)
  1413. end
  1414. end
  1415. end
  1416. end
  1417. </pre><p>
  1418. <code>a &gt;= b</code> is equivalent to <code>b &lt;= a</code>.
  1419. Note that, in the absence of a "le" metamethod,
  1420. Lua tries the "lt", assuming that <code>a &lt;= b</code> is
  1421. equivalent to <code>not (b &lt; a)</code>.
  1422. </li>
  1423. <li><b>"index":</b>
  1424. The indexing access <code>table[key]</code>.
  1425. <pre>
  1426. function gettable_event (table, key)
  1427. local h
  1428. if type(table) == "table" then
  1429. local v = rawget(table, key)
  1430. if v ~= nil then return v end
  1431. h = metatable(table).__index
  1432. if h == nil then return nil end
  1433. else
  1434. h = metatable(table).__index
  1435. if h == nil then
  1436. error(&middot;&middot;&middot;)
  1437. end
  1438. end
  1439. if type(h) == "function" then
  1440. return (h(table, key)) -- call the handler
  1441. else return h[key] -- or repeat operation on it
  1442. end
  1443. end
  1444. </pre><p>
  1445. </li>
  1446. <li><b>"newindex":</b>
  1447. The indexing assignment <code>table[key] = value</code>.
  1448. <pre>
  1449. function settable_event (table, key, value)
  1450. local h
  1451. if type(table) == "table" then
  1452. local v = rawget(table, key)
  1453. if v ~= nil then rawset(table, key, value); return end
  1454. h = metatable(table).__newindex
  1455. if h == nil then rawset(table, key, value); return end
  1456. else
  1457. h = metatable(table).__newindex
  1458. if h == nil then
  1459. error(&middot;&middot;&middot;)
  1460. end
  1461. end
  1462. if type(h) == "function" then
  1463. h(table, key,value) -- call the handler
  1464. else h[key] = value -- or repeat operation on it
  1465. end
  1466. end
  1467. </pre><p>
  1468. </li>
  1469. <li><b>"call":</b>
  1470. called when Lua calls a value.
  1471. <pre>
  1472. function function_event (func, ...)
  1473. if type(func) == "function" then
  1474. return func(...) -- primitive call
  1475. else
  1476. local h = metatable(func).__call
  1477. if h then
  1478. return h(func, ...)
  1479. else
  1480. error(&middot;&middot;&middot;)
  1481. end
  1482. end
  1483. end
  1484. </pre><p>
  1485. </li>
  1486. </ul>
  1487. <h2>2.9 - <a name="2.9">Environments</a></h2>
  1488. <p>
  1489. Besides metatables,
  1490. objects of types thread, function, and userdata
  1491. have another table associated with them,
  1492. called their <em>environment</em>.
  1493. Like metatables, environments are regular tables and
  1494. multiple objects can share the same environment.
  1495. <p>
  1496. Threads are created sharing the environment of the creating thread.
  1497. Userdata and C&nbsp;functions are created sharing the environment
  1498. of the creating C&nbsp;function.
  1499. Non-nested Lua functions
  1500. (created by <a href="#pdf-loadfile"><code>loadfile</code></a>, <a href="#pdf-loadstring"><code>loadstring</code></a> or <a href="#pdf-load"><code>load</code></a>)
  1501. are created sharing the environment of the creating thread.
  1502. Nested Lua functions are created sharing the environment of
  1503. the creating Lua function.
  1504. <p>
  1505. Environments associated with userdata have no meaning for Lua.
  1506. It is only a convenience feature for programmers to associate a table to
  1507. a userdata.
  1508. <p>
  1509. Environments associated with threads are called
  1510. <em>global environments</em>.
  1511. They are used as the default environment for threads and
  1512. non-nested Lua functions created by the thread
  1513. and can be directly accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
  1514. <p>
  1515. The environment associated with a C&nbsp;function can be directly
  1516. accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
  1517. It is used as the default environment for other C&nbsp;functions
  1518. and userdata created by the function.
  1519. <p>
  1520. Environments associated with Lua functions are used to resolve
  1521. all accesses to global variables within the function (see <a href="#2.3">&sect;2.3</a>).
  1522. They are used as the default environment for nested Lua functions
  1523. created by the function.
  1524. <p>
  1525. You can change the environment of a Lua function or the
  1526. running thread by calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
  1527. You can get the environment of a Lua function or the running thread
  1528. by calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
  1529. To manipulate the environment of other objects
  1530. (userdata, C&nbsp;functions, other threads) you must
  1531. use the C&nbsp;API.
  1532. <h2>2.10 - <a name="2.10">Garbage Collection</a></h2>
  1533. <p>
  1534. Lua performs automatic memory management.
  1535. This means that
  1536. you have to worry neither about allocating memory for new objects
  1537. nor about freeing it when the objects are no longer needed.
  1538. Lua manages memory automatically by running
  1539. a <em>garbage collector</em> from time to time
  1540. to collect all <em>dead objects</em>
  1541. (that is, objects that are no longer accessible from Lua).
  1542. All memory used by Lua is subject to automatic management:
  1543. tables, userdata, functions, threads, strings, etc.
  1544. <p>
  1545. Lua implements an incremental mark-and-sweep collector.
  1546. It uses two numbers to control its garbage-collection cycles:
  1547. the <em>garbage-collector pause</em> and
  1548. the <em>garbage-collector step multiplier</em>.
  1549. Both use percentage points as units
  1550. (so that a value of 100 means an internal value of 1).
  1551. <p>
  1552. The garbage-collector pause
  1553. controls how long the collector waits before starting a new cycle.
  1554. Larger values make the collector less aggressive.
  1555. Values smaller than 100 mean the collector will not wait to
  1556. start a new cycle.
  1557. A value of 200 means that the collector waits for the total memory in use
  1558. to double before starting a new cycle.
  1559. <p>
  1560. The step multiplier
  1561. controls the relative speed of the collector relative to
  1562. memory allocation.
  1563. Larger values make the collector more aggressive but also increase
  1564. the size of each incremental step.
  1565. Values smaller than 100 make the collector too slow and
  1566. can result in the collector never finishing a cycle.
  1567. The default, 200, means that the collector runs at "twice"
  1568. the speed of memory allocation.
  1569. <p>
  1570. You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
  1571. or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
  1572. With these functions you can also control
  1573. the collector directly (e.g., stop and restart it).
  1574. <h3>2.10.1 - <a name="2.10.1">Garbage-Collection Metamethods</a></h3>
  1575. <p>
  1576. Using the C&nbsp;API,
  1577. you can set garbage-collector metamethods for userdata (see <a href="#2.8">&sect;2.8</a>).
  1578. These metamethods are also called <em>finalizers</em>.
  1579. Finalizers allow you to coordinate Lua's garbage collection
  1580. with external resource management
  1581. (such as closing files, network or database connections,
  1582. or freeing your own memory).
  1583. <p>
  1584. Garbage userdata with a field <code>__gc</code> in their metatables are not
  1585. collected immediately by the garbage collector.
  1586. Instead, Lua puts them in a list.
  1587. After the collection,
  1588. Lua does the equivalent of the following function
  1589. for each userdata in that list:
  1590. <pre>
  1591. function gc_event (udata)
  1592. local h = metatable(udata).__gc
  1593. if h then
  1594. h(udata)
  1595. end
  1596. end
  1597. </pre>
  1598. <p>
  1599. At the end of each garbage-collection cycle,
  1600. the finalizers for userdata are called in <em>reverse</em>
  1601. order of their creation,
  1602. among those collected in that cycle.
  1603. That is, the first finalizer to be called is the one associated
  1604. with the userdata created last in the program.
  1605. The userdata itself is freed only in the next garbage-collection cycle.
  1606. <h3>2.10.2 - <a name="2.10.2">Weak Tables</a></h3>
  1607. <p>
  1608. A <em>weak table</em> is a table whose elements are
  1609. <em>weak references</em>.
  1610. A weak reference is ignored by the garbage collector.
  1611. In other words,
  1612. if the only references to an object are weak references,
  1613. then the garbage collector will collect this object.
  1614. <p>
  1615. A weak table can have weak keys, weak values, or both.
  1616. A table with weak keys allows the collection of its keys,
  1617. but prevents the collection of its values.
  1618. A table with both weak keys and weak values allows the collection of
  1619. both keys and values.
  1620. In any case, if either the key or the value is collected,
  1621. the whole pair is removed from the table.
  1622. The weakness of a table is controlled by the
  1623. <code>__mode</code> field of its metatable.
  1624. If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
  1625. the keys in the table are weak.
  1626. If <code>__mode</code> contains '<code>v</code>',
  1627. the values in the table are weak.
  1628. <p>
  1629. After you use a table as a metatable,
  1630. you should not change the value of its <code>__mode</code> field.
  1631. Otherwise, the weak behavior of the tables controlled by this
  1632. metatable is undefined.
  1633. <h2>2.11 - <a name="2.11">Coroutines</a></h2>
  1634. <p>
  1635. Lua supports coroutines,
  1636. also called <em>collaborative multithreading</em>.
  1637. A coroutine in Lua represents an independent thread of execution.
  1638. Unlike threads in multithread systems, however,
  1639. a coroutine only suspends its execution by explicitly calling
  1640. a yield function.
  1641. <p>
  1642. You create a coroutine with a call to <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
  1643. Its sole argument is a function
  1644. that is the main function of the coroutine.
  1645. The <code>create</code> function only creates a new coroutine and
  1646. returns a handle to it (an object of type <em>thread</em>);
  1647. it does not start the coroutine execution.
  1648. <p>
  1649. When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
  1650. passing as its first argument
  1651. a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
  1652. the coroutine starts its execution,
  1653. at the first line of its main function.
  1654. Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
  1655. to the coroutine main function.
  1656. After the coroutine starts running,
  1657. it runs until it terminates or <em>yields</em>.
  1658. <p>
  1659. A coroutine can terminate its execution in two ways:
  1660. normally, when its main function returns
  1661. (explicitly or implicitly, after the last instruction);
  1662. and abnormally, if there is an unprotected error.
  1663. In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
  1664. plus any values returned by the coroutine main function.
  1665. In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
  1666. plus an error message.
  1667. <p>
  1668. A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
  1669. When a coroutine yields,
  1670. the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
  1671. even if the yield happens inside nested function calls
  1672. (that is, not in the main function,
  1673. but in a function directly or indirectly called by the main function).
  1674. In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
  1675. plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
  1676. The next time you resume the same coroutine,
  1677. it continues its execution from the point where it yielded,
  1678. with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
  1679. arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
  1680. <p>
  1681. Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
  1682. the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
  1683. but instead of returning the coroutine itself,
  1684. it returns a function that, when called, resumes the coroutine.
  1685. Any arguments passed to this function
  1686. go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
  1687. <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
  1688. except the first one (the boolean error code).
  1689. Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
  1690. <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
  1691. any error is propagated to the caller.
  1692. <p>
  1693. As an example,
  1694. consider the following code:
  1695. <pre>
  1696. function foo (a)
  1697. print("foo", a)
  1698. return coroutine.yield(2*a)
  1699. end
  1700. co = coroutine.create(function (a,b)
  1701. print("co-body", a, b)
  1702. local r = foo(a+1)
  1703. print("co-body", r)
  1704. local r, s = coroutine.yield(a+b, a-b)
  1705. print("co-body", r, s)
  1706. return b, "end"
  1707. end)
  1708. print("main", coroutine.resume(co, 1, 10))
  1709. print("main", coroutine.resume(co, "r"))
  1710. print("main", coroutine.resume(co, "x", "y"))
  1711. print("main", coroutine.resume(co, "x", "y"))
  1712. </pre><p>
  1713. When you run it, it produces the following output:
  1714. <pre>
  1715. co-body 1 10
  1716. foo 2
  1717. main true 4
  1718. co-body r
  1719. main true 11 -9
  1720. co-body x y
  1721. main true 10 end
  1722. main false cannot resume dead coroutine
  1723. </pre>
  1724. <h1>3 - <a name="3">The Application Program Interface</a></h1>
  1725. <p>
  1726. This section describes the C&nbsp;API for Lua, that is,
  1727. the set of C&nbsp;functions available to the host program to communicate
  1728. with Lua.
  1729. All API functions and related types and constants
  1730. are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
  1731. <p>
  1732. Even when we use the term "function",
  1733. any facility in the API may be provided as a macro instead.
  1734. All such macros use each of their arguments exactly once
  1735. (except for the first argument, which is always a Lua state),
  1736. and so do not generate any hidden side-effects.
  1737. <p>
  1738. As in most C&nbsp;libraries,
  1739. the Lua API functions do not check their arguments for validity or consistency.
  1740. However, you can change this behavior by compiling Lua
  1741. with a proper definition for the macro <a name="pdf-luai_apicheck"><code>luai_apicheck</code></a>,
  1742. in file <code>luaconf.h</code>.
  1743. <h2>3.1 - <a name="3.1">The Stack</a></h2>
  1744. <p>
  1745. Lua uses a <em>virtual stack</em> to pass values to and from C.
  1746. Each element in this stack represents a Lua value
  1747. (<b>nil</b>, number, string, etc.).
  1748. <p>
  1749. Whenever Lua calls C, the called function gets a new stack,
  1750. which is independent of previous stacks and of stacks of
  1751. C&nbsp;functions that are still active.
  1752. This stack initially contains any arguments to the C&nbsp;function
  1753. and it is where the C&nbsp;function pushes its results
  1754. to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
  1755. <p>
  1756. For convenience,
  1757. most query operations in the API do not follow a strict stack discipline.
  1758. Instead, they can refer to any element in the stack
  1759. by using an <em>index</em>:
  1760. A positive index represents an <em>absolute</em> stack position
  1761. (starting at&nbsp;1);
  1762. a negative index represents an <em>offset</em> relative to the top of the stack.
  1763. More specifically, if the stack has <em>n</em> elements,
  1764. then index&nbsp;1 represents the first element
  1765. (that is, the element that was pushed onto the stack first)
  1766. and
  1767. index&nbsp;<em>n</em> represents the last element;
  1768. index&nbsp;-1 also represents the last element
  1769. (that is, the element at the&nbsp;top)
  1770. and index <em>-n</em> represents the first element.
  1771. We say that an index is <em>valid</em>
  1772. if it lies between&nbsp;1 and the stack top
  1773. (that is, if <code>1 &le; abs(index) &le; top</code>).
  1774. <h2>3.2 - <a name="3.2">Stack Size</a></h2>
  1775. <p>
  1776. When you interact with Lua API,
  1777. you are responsible for ensuring consistency.
  1778. In particular,
  1779. <em>you are responsible for controlling stack overflow</em>.
  1780. You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
  1781. to grow the stack size.
  1782. <p>
  1783. Whenever Lua calls C,
  1784. it ensures that at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> stack positions are available.
  1785. <code>LUA_MINSTACK</code> is defined as 20,
  1786. so that usually you do not have to worry about stack space
  1787. unless your code has loops pushing elements onto the stack.
  1788. <p>
  1789. Most query functions accept as indices any value inside the
  1790. available stack space, that is, indices up to the maximum stack size
  1791. you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
  1792. Such indices are called <em>acceptable indices</em>.
  1793. More formally, we define an <em>acceptable index</em>
  1794. as follows:
  1795. <pre>
  1796. (index &lt; 0 &amp;&amp; abs(index) &lt;= top) ||
  1797. (index &gt; 0 &amp;&amp; index &lt;= stackspace)
  1798. </pre><p>
  1799. Note that 0 is never an acceptable index.
  1800. <h2>3.3 - <a name="3.3">Pseudo-Indices</a></h2>
  1801. <p>
  1802. Unless otherwise noted,
  1803. any function that accepts valid indices can also be called with
  1804. <em>pseudo-indices</em>,
  1805. which represent some Lua values that are accessible to C&nbsp;code
  1806. but which are not in the stack.
  1807. Pseudo-indices are used to access the thread environment,
  1808. the function environment,
  1809. the registry,
  1810. and the upvalues of a C&nbsp;function (see <a href="#3.4">&sect;3.4</a>).
  1811. <p>
  1812. The thread environment (where global variables live) is
  1813. always at pseudo-index <a name="pdf-LUA_GLOBALSINDEX"><code>LUA_GLOBALSINDEX</code></a>.
  1814. The environment of the running C&nbsp;function is always
  1815. at pseudo-index <a name="pdf-LUA_ENVIRONINDEX"><code>LUA_ENVIRONINDEX</code></a>.
  1816. <p>
  1817. To access and change the value of global variables,
  1818. you can use regular table operations over an environment table.
  1819. For instance, to access the value of a global variable, do
  1820. <pre>
  1821. lua_getfield(L, LUA_GLOBALSINDEX, varname);
  1822. </pre>
  1823. <h2>3.4 - <a name="3.4">C Closures</a></h2>
  1824. <p>
  1825. When a C&nbsp;function is created,
  1826. it is possible to associate some values with it,
  1827. thus creating a <em>C&nbsp;closure</em>;
  1828. these values are called <em>upvalues</em> and are
  1829. accessible to the function whenever it is called
  1830. (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
  1831. <p>
  1832. Whenever a C&nbsp;function is called,
  1833. its upvalues are located at specific pseudo-indices.
  1834. These pseudo-indices are produced by the macro
  1835. <a name="lua_upvalueindex"><code>lua_upvalueindex</code></a>.
  1836. The first value associated with a function is at position
  1837. <code>lua_upvalueindex(1)</code>, and so on.
  1838. Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
  1839. where <em>n</em> is greater than the number of upvalues of the
  1840. current function (but not greater than 256),
  1841. produces an acceptable (but invalid) index.
  1842. <h2>3.5 - <a name="3.5">Registry</a></h2>
  1843. <p>
  1844. Lua provides a <em>registry</em>,
  1845. a pre-defined table that can be used by any C&nbsp;code to
  1846. store whatever Lua value it needs to store.
  1847. This table is always located at pseudo-index
  1848. <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
  1849. Any C&nbsp;library can store data into this table,
  1850. but it should take care to choose keys different from those used
  1851. by other libraries, to avoid collisions.
  1852. Typically, you should use as key a string containing your library name
  1853. or a light userdata with the address of a C&nbsp;object in your code.
  1854. <p>
  1855. The integer keys in the registry are used by the reference mechanism,
  1856. implemented by the auxiliary library,
  1857. and therefore should not be used for other purposes.
  1858. <h2>3.6 - <a name="3.6">Error Handling in C</a></h2>
  1859. <p>
  1860. Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
  1861. (You can also choose to use exceptions if you use C++;
  1862. see file <code>luaconf.h</code>.)
  1863. When Lua faces any error
  1864. (such as memory allocation errors, type errors, syntax errors,
  1865. and runtime errors)
  1866. it <em>raises</em> an error;
  1867. that is, it does a long jump.
  1868. A <em>protected environment</em> uses <code>setjmp</code>
  1869. to set a recover point;
  1870. any error jumps to the most recent active recover point.
  1871. <p>
  1872. Most functions in the API can throw an error,
  1873. for instance due to a memory allocation error.
  1874. The documentation for each function indicates whether
  1875. it can throw errors.
  1876. <p>
  1877. Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
  1878. <h2>3.7 - <a name="3.7">Functions and Types</a></h2>
  1879. <p>
  1880. Here we list all functions and types from the C&nbsp;API in
  1881. alphabetical order.
  1882. Each function has an indicator like this:
  1883. <span class="apii">[-o, +p, <em>x</em>]</span>
  1884. <p>
  1885. The first field, <code>o</code>,
  1886. is how many elements the function pops from the stack.
  1887. The second field, <code>p</code>,
  1888. is how many elements the function pushes onto the stack.
  1889. (Any function always pushes its results after popping its arguments.)
  1890. A field in the form <code>x|y</code> means the function can push (or pop)
  1891. <code>x</code> or <code>y</code> elements,
  1892. depending on the situation;
  1893. an interrogation mark '<code>?</code>' means that
  1894. we cannot know how many elements the function pops/pushes
  1895. by looking only at its arguments
  1896. (e.g., they may depend on what is on the stack).
  1897. The third field, <code>x</code>,
  1898. tells whether the function may throw errors:
  1899. '<code>-</code>' means the function never throws any error;
  1900. '<code>m</code>' means the function may throw an error
  1901. only due to not enough memory;
  1902. '<code>e</code>' means the function may throw other kinds of errors;
  1903. '<code>v</code>' means the function may throw an error on purpose.
  1904. <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
  1905. <pre>typedef void * (*lua_Alloc) (void *ud,
  1906. void *ptr,
  1907. size_t osize,
  1908. size_t nsize);</pre>
  1909. <p>
  1910. The type of the memory-allocation function used by Lua states.
  1911. The allocator function must provide a
  1912. functionality similar to <code>realloc</code>,
  1913. but not exactly the same.
  1914. Its arguments are
  1915. <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
  1916. <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
  1917. <code>osize</code>, the original size of the block;
  1918. <code>nsize</code>, the new size of the block.
  1919. <code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
  1920. When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
  1921. if <code>osize</code> is not zero,
  1922. it should free the block pointed to by <code>ptr</code>.
  1923. When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
  1924. if and only if it cannot fill the request.
  1925. When <code>nsize</code> is not zero and <code>osize</code> is zero,
  1926. the allocator should behave like <code>malloc</code>.
  1927. When <code>nsize</code> and <code>osize</code> are not zero,
  1928. the allocator behaves like <code>realloc</code>.
  1929. Lua assumes that the allocator never fails when
  1930. <code>osize &gt;= nsize</code>.
  1931. <p>
  1932. Here is a simple implementation for the allocator function.
  1933. It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
  1934. <pre>
  1935. static void *l_alloc (void *ud, void *ptr, size_t osize,
  1936. size_t nsize) {
  1937. (void)ud; (void)osize; /* not used */
  1938. if (nsize == 0) {
  1939. free(ptr);
  1940. return NULL;
  1941. }
  1942. else
  1943. return realloc(ptr, nsize);
  1944. }
  1945. </pre><p>
  1946. This code assumes
  1947. that <code>free(NULL)</code> has no effect and that
  1948. <code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
  1949. ANSI&nbsp;C ensures both behaviors.
  1950. <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
  1951. <span class="apii">[-0, +0, <em>-</em>]</span>
  1952. <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
  1953. <p>
  1954. Sets a new panic function and returns the old one.
  1955. <p>
  1956. If an error happens outside any protected environment,
  1957. Lua calls a <em>panic function</em>
  1958. and then calls <code>exit(EXIT_FAILURE)</code>,
  1959. thus exiting the host application.
  1960. Your panic function can avoid this exit by
  1961. never returning (e.g., doing a long jump).
  1962. <p>
  1963. The panic function can access the error message at the top of the stack.
  1964. <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
  1965. <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
  1966. <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
  1967. <p>
  1968. Calls a function.
  1969. <p>
  1970. To call a function you must use the following protocol:
  1971. first, the function to be called is pushed onto the stack;
  1972. then, the arguments to the function are pushed
  1973. in direct order;
  1974. that is, the first argument is pushed first.
  1975. Finally you call <a href="#lua_call"><code>lua_call</code></a>;
  1976. <code>nargs</code> is the number of arguments that you pushed onto the stack.
  1977. All arguments and the function value are popped from the stack
  1978. when the function is called.
  1979. The function results are pushed onto the stack when the function returns.
  1980. The number of results is adjusted to <code>nresults</code>,
  1981. unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
  1982. In this case, <em>all</em> results from the function are pushed.
  1983. Lua takes care that the returned values fit into the stack space.
  1984. The function results are pushed onto the stack in direct order
  1985. (the first result is pushed first),
  1986. so that after the call the last result is on the top of the stack.
  1987. <p>
  1988. Any error inside the called function is propagated upwards
  1989. (with a <code>longjmp</code>).
  1990. <p>
  1991. The following example shows how the host program can do the
  1992. equivalent to this Lua code:
  1993. <pre>
  1994. a = f("how", t.x, 14)
  1995. </pre><p>
  1996. Here it is in&nbsp;C:
  1997. <pre>
  1998. lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
  1999. lua_pushstring(L, "how"); /* 1st argument */
  2000. lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */
  2001. lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
  2002. lua_remove(L, -2); /* remove 't' from the stack */
  2003. lua_pushinteger(L, 14); /* 3rd argument */
  2004. lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
  2005. lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global 'a' */
  2006. </pre><p>
  2007. Note that the code above is "balanced":
  2008. at its end, the stack is back to its original configuration.
  2009. This is considered good programming practice.
  2010. <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
  2011. <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
  2012. <p>
  2013. Type for C&nbsp;functions.
  2014. <p>
  2015. In order to communicate properly with Lua,
  2016. a C&nbsp;function must use the following protocol,
  2017. which defines the way parameters and results are passed:
  2018. a C&nbsp;function receives its arguments from Lua in its stack
  2019. in direct order (the first argument is pushed first).
  2020. So, when the function starts,
  2021. <code>lua_gettop(L)</code> returns the number of arguments received by the function.
  2022. The first argument (if any) is at index 1
  2023. and its last argument is at index <code>lua_gettop(L)</code>.
  2024. To return values to Lua, a C&nbsp;function just pushes them onto the stack,
  2025. in direct order (the first result is pushed first),
  2026. and returns the number of results.
  2027. Any other value in the stack below the results will be properly
  2028. discarded by Lua.
  2029. Like a Lua function, a C&nbsp;function called by Lua can also return
  2030. many results.
  2031. <p>
  2032. As an example, the following function receives a variable number
  2033. of numerical arguments and returns their average and sum:
  2034. <pre>
  2035. static int foo (lua_State *L) {
  2036. int n = lua_gettop(L); /* number of arguments */
  2037. lua_Number sum = 0;
  2038. int i;
  2039. for (i = 1; i &lt;= n; i++) {
  2040. if (!lua_isnumber(L, i)) {
  2041. lua_pushstring(L, "incorrect argument");
  2042. lua_error(L);
  2043. }
  2044. sum += lua_tonumber(L, i);
  2045. }
  2046. lua_pushnumber(L, sum/n); /* first result */
  2047. lua_pushnumber(L, sum); /* second result */
  2048. return 2; /* number of results */
  2049. }
  2050. </pre>
  2051. <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
  2052. <span class="apii">[-0, +0, <em>m</em>]</span>
  2053. <pre>int lua_checkstack (lua_State *L, int extra);</pre>
  2054. <p>
  2055. Ensures that there are at least <code>extra</code> free stack slots in the stack.
  2056. It returns false if it cannot grow the stack to that size.
  2057. This function never shrinks the stack;
  2058. if the stack is already larger than the new size,
  2059. it is left unchanged.
  2060. <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
  2061. <span class="apii">[-0, +0, <em>-</em>]</span>
  2062. <pre>void lua_close (lua_State *L);</pre>
  2063. <p>
  2064. Destroys all objects in the given Lua state
  2065. (calling the corresponding garbage-collection metamethods, if any)
  2066. and frees all dynamic memory used by this state.
  2067. On several platforms, you may not need to call this function,
  2068. because all resources are naturally released when the host program ends.
  2069. On the other hand, long-running programs,
  2070. such as a daemon or a web server,
  2071. might need to release states as soon as they are not needed,
  2072. to avoid growing too large.
  2073. <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
  2074. <span class="apii">[-n, +1, <em>e</em>]</span>
  2075. <pre>void lua_concat (lua_State *L, int n);</pre>
  2076. <p>
  2077. Concatenates the <code>n</code> values at the top of the stack,
  2078. pops them, and leaves the result at the top.
  2079. If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
  2080. (that is, the function does nothing);
  2081. if <code>n</code> is 0, the result is the empty string.
  2082. Concatenation is performed following the usual semantics of Lua
  2083. (see <a href="#2.5.4">&sect;2.5.4</a>).
  2084. <hr><h3><a name="lua_cpcall"><code>lua_cpcall</code></a></h3><p>
  2085. <span class="apii">[-0, +(0|1), <em>-</em>]</span>
  2086. <pre>int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);</pre>
  2087. <p>
  2088. Calls the C&nbsp;function <code>func</code> in protected mode.
  2089. <code>func</code> starts with only one element in its stack,
  2090. a light userdata containing <code>ud</code>.
  2091. In case of errors,
  2092. <a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
  2093. plus the error object on the top of the stack;
  2094. otherwise, it returns zero, and does not change the stack.
  2095. All values returned by <code>func</code> are discarded.
  2096. <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
  2097. <span class="apii">[-0, +1, <em>m</em>]</span>
  2098. <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
  2099. <p>
  2100. Creates a new empty table and pushes it onto the stack.
  2101. The new table has space pre-allocated
  2102. for <code>narr</code> array elements and <code>nrec</code> non-array elements.
  2103. This pre-allocation is useful when you know exactly how many elements
  2104. the table will have.
  2105. Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
  2106. <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
  2107. <span class="apii">[-0, +0, <em>m</em>]</span>
  2108. <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
  2109. <p>
  2110. Dumps a function as a binary chunk.
  2111. Receives a Lua function on the top of the stack
  2112. and produces a binary chunk that,
  2113. if loaded again,
  2114. results in a function equivalent to the one dumped.
  2115. As it produces parts of the chunk,
  2116. <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
  2117. with the given <code>data</code>
  2118. to write them.
  2119. <p>
  2120. The value returned is the error code returned by the last
  2121. call to the writer;
  2122. 0&nbsp;means no errors.
  2123. <p>
  2124. This function does not pop the Lua function from the stack.
  2125. <hr><h3><a name="lua_equal"><code>lua_equal</code></a></h3><p>
  2126. <span class="apii">[-0, +0, <em>e</em>]</span>
  2127. <pre>int lua_equal (lua_State *L, int index1, int index2);</pre>
  2128. <p>
  2129. Returns 1 if the two values in acceptable indices <code>index1</code> and
  2130. <code>index2</code> are equal,
  2131. following the semantics of the Lua <code>==</code> operator
  2132. (that is, may call metamethods).
  2133. Otherwise returns&nbsp;0.
  2134. Also returns&nbsp;0 if any of the indices is non valid.
  2135. <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
  2136. <span class="apii">[-1, +0, <em>v</em>]</span>
  2137. <pre>int lua_error (lua_State *L);</pre>
  2138. <p>
  2139. Generates a Lua error.
  2140. The error message (which can actually be a Lua value of any type)
  2141. must be on the stack top.
  2142. This function does a long jump,
  2143. and therefore never returns.
  2144. (see <a href="#luaL_error"><code>luaL_error</code></a>).
  2145. <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
  2146. <span class="apii">[-0, +0, <em>e</em>]</span>
  2147. <pre>int lua_gc (lua_State *L, int what, int data);</pre>
  2148. <p>
  2149. Controls the garbage collector.
  2150. <p>
  2151. This function performs several tasks,
  2152. according to the value of the parameter <code>what</code>:
  2153. <ul>
  2154. <li><b><code>LUA_GCSTOP</code>:</b>
  2155. stops the garbage collector.
  2156. </li>
  2157. <li><b><code>LUA_GCRESTART</code>:</b>
  2158. restarts the garbage collector.
  2159. </li>
  2160. <li><b><code>LUA_GCCOLLECT</code>:</b>
  2161. performs a full garbage-collection cycle.
  2162. </li>
  2163. <li><b><code>LUA_GCCOUNT</code>:</b>
  2164. returns the current amount of memory (in Kbytes) in use by Lua.
  2165. </li>
  2166. <li><b><code>LUA_GCCOUNTB</code>:</b>
  2167. returns the remainder of dividing the current amount of bytes of
  2168. memory in use by Lua by 1024.
  2169. </li>
  2170. <li><b><code>LUA_GCSTEP</code>:</b>
  2171. performs an incremental step of garbage collection.
  2172. The step "size" is controlled by <code>data</code>
  2173. (larger values mean more steps) in a non-specified way.
  2174. If you want to control the step size
  2175. you must experimentally tune the value of <code>data</code>.
  2176. The function returns 1 if the step finished a
  2177. garbage-collection cycle.
  2178. </li>
  2179. <li><b><code>LUA_GCSETPAUSE</code>:</b>
  2180. sets <code>data</code> as the new value
  2181. for the <em>pause</em> of the collector (see <a href="#2.10">&sect;2.10</a>).
  2182. The function returns the previous value of the pause.
  2183. </li>
  2184. <li><b><code>LUA_GCSETSTEPMUL</code>:</b>
  2185. sets <code>data</code> as the new value for the <em>step multiplier</em> of
  2186. the collector (see <a href="#2.10">&sect;2.10</a>).
  2187. The function returns the previous value of the step multiplier.
  2188. </li>
  2189. </ul>
  2190. <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
  2191. <span class="apii">[-0, +0, <em>-</em>]</span>
  2192. <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
  2193. <p>
  2194. Returns the memory-allocation function of a given state.
  2195. If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
  2196. opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
  2197. <hr><h3><a name="lua_getfenv"><code>lua_getfenv</code></a></h3><p>
  2198. <span class="apii">[-0, +1, <em>-</em>]</span>
  2199. <pre>void lua_getfenv (lua_State *L, int index);</pre>
  2200. <p>
  2201. Pushes onto the stack the environment table of
  2202. the value at the given index.
  2203. <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
  2204. <span class="apii">[-0, +1, <em>e</em>]</span>
  2205. <pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
  2206. <p>
  2207. Pushes onto the stack the value <code>t[k]</code>,
  2208. where <code>t</code> is the value at the given valid index.
  2209. As in Lua, this function may trigger a metamethod
  2210. for the "index" event (see <a href="#2.8">&sect;2.8</a>).
  2211. <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
  2212. <span class="apii">[-0, +1, <em>e</em>]</span>
  2213. <pre>void lua_getglobal (lua_State *L, const char *name);</pre>
  2214. <p>
  2215. Pushes onto the stack the value of the global <code>name</code>.
  2216. It is defined as a macro:
  2217. <pre>
  2218. #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
  2219. </pre>
  2220. <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
  2221. <span class="apii">[-0, +(0|1), <em>-</em>]</span>
  2222. <pre>int lua_getmetatable (lua_State *L, int index);</pre>
  2223. <p>
  2224. Pushes onto the stack the metatable of the value at the given
  2225. acceptable index.
  2226. If the index is not valid,
  2227. or if the value does not have a metatable,
  2228. the function returns&nbsp;0 and pushes nothing on the stack.
  2229. <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
  2230. <span class="apii">[-1, +1, <em>e</em>]</span>
  2231. <pre>void lua_gettable (lua_State *L, int index);</pre>
  2232. <p>
  2233. Pushes onto the stack the value <code>t[k]</code>,
  2234. where <code>t</code> is the value at the given valid index
  2235. and <code>k</code> is the value at the top of the stack.
  2236. <p>
  2237. This function pops the key from the stack
  2238. (putting the resulting value in its place).
  2239. As in Lua, this function may trigger a metamethod
  2240. for the "index" event (see <a href="#2.8">&sect;2.8</a>).
  2241. <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
  2242. <span class="apii">[-0, +0, <em>-</em>]</span>
  2243. <pre>int lua_gettop (lua_State *L);</pre>
  2244. <p>
  2245. Returns the index of the top element in the stack.
  2246. Because indices start at&nbsp;1,
  2247. this result is equal to the number of elements in the stack
  2248. (and so 0&nbsp;means an empty stack).
  2249. <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
  2250. <span class="apii">[-1, +1, <em>-</em>]</span>
  2251. <pre>void lua_insert (lua_State *L, int index);</pre>
  2252. <p>
  2253. Moves the top element into the given valid index,
  2254. shifting up the elements above this index to open space.
  2255. Cannot be called with a pseudo-index,
  2256. because a pseudo-index is not an actual stack position.
  2257. <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
  2258. <pre>typedef ptrdiff_t lua_Integer;</pre>
  2259. <p>
  2260. The type used by the Lua API to represent integral values.
  2261. <p>
  2262. By default it is a <code>ptrdiff_t</code>,
  2263. which is usually the largest signed integral type the machine handles
  2264. "comfortably".
  2265. <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
  2266. <span class="apii">[-0, +0, <em>-</em>]</span>
  2267. <pre>int lua_isboolean (lua_State *L, int index);</pre>
  2268. <p>
  2269. Returns 1 if the value at the given acceptable index has type boolean,
  2270. and 0&nbsp;otherwise.
  2271. <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
  2272. <span class="apii">[-0, +0, <em>-</em>]</span>
  2273. <pre>int lua_iscfunction (lua_State *L, int index);</pre>
  2274. <p>
  2275. Returns 1 if the value at the given acceptable index is a C&nbsp;function,
  2276. and 0&nbsp;otherwise.
  2277. <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
  2278. <span class="apii">[-0, +0, <em>-</em>]</span>
  2279. <pre>int lua_isfunction (lua_State *L, int index);</pre>
  2280. <p>
  2281. Returns 1 if the value at the given acceptable index is a function
  2282. (either C or Lua), and 0&nbsp;otherwise.
  2283. <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
  2284. <span class="apii">[-0, +0, <em>-</em>]</span>
  2285. <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
  2286. <p>
  2287. Returns 1 if the value at the given acceptable index is a light userdata,
  2288. and 0&nbsp;otherwise.
  2289. <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
  2290. <span class="apii">[-0, +0, <em>-</em>]</span>
  2291. <pre>int lua_isnil (lua_State *L, int index);</pre>
  2292. <p>
  2293. Returns 1 if the value at the given acceptable index is <b>nil</b>,
  2294. and 0&nbsp;otherwise.
  2295. <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
  2296. <span class="apii">[-0, +0, <em>-</em>]</span>
  2297. <pre>int lua_isnone (lua_State *L, int index);</pre>
  2298. <p>
  2299. Returns 1 if the given acceptable index is not valid
  2300. (that is, it refers to an element outside the current stack),
  2301. and 0&nbsp;otherwise.
  2302. <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
  2303. <span class="apii">[-0, +0, <em>-</em>]</span>
  2304. <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
  2305. <p>
  2306. Returns 1 if the given acceptable index is not valid
  2307. (that is, it refers to an element outside the current stack)
  2308. or if the value at this index is <b>nil</b>,
  2309. and 0&nbsp;otherwise.
  2310. <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
  2311. <span class="apii">[-0, +0, <em>-</em>]</span>
  2312. <pre>int lua_isnumber (lua_State *L, int index);</pre>
  2313. <p>
  2314. Returns 1 if the value at the given acceptable index is a number
  2315. or a string convertible to a number,
  2316. and 0&nbsp;otherwise.
  2317. <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
  2318. <span class="apii">[-0, +0, <em>-</em>]</span>
  2319. <pre>int lua_isstring (lua_State *L, int index);</pre>
  2320. <p>
  2321. Returns 1 if the value at the given acceptable index is a string
  2322. or a number (which is always convertible to a string),
  2323. and 0&nbsp;otherwise.
  2324. <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
  2325. <span class="apii">[-0, +0, <em>-</em>]</span>
  2326. <pre>int lua_istable (lua_State *L, int index);</pre>
  2327. <p>
  2328. Returns 1 if the value at the given acceptable index is a table,
  2329. and 0&nbsp;otherwise.
  2330. <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
  2331. <span class="apii">[-0, +0, <em>-</em>]</span>
  2332. <pre>int lua_isthread (lua_State *L, int index);</pre>
  2333. <p>
  2334. Returns 1 if the value at the given acceptable index is a thread,
  2335. and 0&nbsp;otherwise.
  2336. <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
  2337. <span class="apii">[-0, +0, <em>-</em>]</span>
  2338. <pre>int lua_isuserdata (lua_State *L, int index);</pre>
  2339. <p>
  2340. Returns 1 if the value at the given acceptable index is a userdata
  2341. (either full or light), and 0&nbsp;otherwise.
  2342. <hr><h3><a name="lua_lessthan"><code>lua_lessthan</code></a></h3><p>
  2343. <span class="apii">[-0, +0, <em>e</em>]</span>
  2344. <pre>int lua_lessthan (lua_State *L, int index1, int index2);</pre>
  2345. <p>
  2346. Returns 1 if the value at acceptable index <code>index1</code> is smaller
  2347. than the value at acceptable index <code>index2</code>,
  2348. following the semantics of the Lua <code>&lt;</code> operator
  2349. (that is, may call metamethods).
  2350. Otherwise returns&nbsp;0.
  2351. Also returns&nbsp;0 if any of the indices is non valid.
  2352. <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
  2353. <span class="apii">[-0, +1, <em>-</em>]</span>
  2354. <pre>int lua_load (lua_State *L,
  2355. lua_Reader reader,
  2356. void *data,
  2357. const char *chunkname);</pre>
  2358. <p>
  2359. Loads a Lua chunk.
  2360. If there are no errors,
  2361. <a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
  2362. function on top of the stack.
  2363. Otherwise, it pushes an error message.
  2364. The return values of <a href="#lua_load"><code>lua_load</code></a> are:
  2365. <ul>
  2366. <li><b>0:</b> no errors;</li>
  2367. <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
  2368. syntax error during pre-compilation;</li>
  2369. <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
  2370. memory allocation error.</li>
  2371. </ul>
  2372. <p>
  2373. This function only loads a chunk;
  2374. it does not run it.
  2375. <p>
  2376. <a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
  2377. and loads it accordingly (see program <code>luac</code>).
  2378. <p>
  2379. The <a href="#lua_load"><code>lua_load</code></a> function uses a user-supplied <code>reader</code> function
  2380. to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
  2381. The <code>data</code> argument is an opaque value passed to the reader function.
  2382. <p>
  2383. The <code>chunkname</code> argument gives a name to the chunk,
  2384. which is used for error messages and in debug information (see <a href="#3.8">&sect;3.8</a>).
  2385. <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
  2386. <span class="apii">[-0, +0, <em>-</em>]</span>
  2387. <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
  2388. <p>
  2389. Creates a new, independent state.
  2390. Returns <code>NULL</code> if cannot create the state
  2391. (due to lack of memory).
  2392. The argument <code>f</code> is the allocator function;
  2393. Lua does all memory allocation for this state through this function.
  2394. The second argument, <code>ud</code>, is an opaque pointer that Lua
  2395. simply passes to the allocator in every call.
  2396. <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
  2397. <span class="apii">[-0, +1, <em>m</em>]</span>
  2398. <pre>void lua_newtable (lua_State *L);</pre>
  2399. <p>
  2400. Creates a new empty table and pushes it onto the stack.
  2401. It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
  2402. <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
  2403. <span class="apii">[-0, +1, <em>m</em>]</span>
  2404. <pre>lua_State *lua_newthread (lua_State *L);</pre>
  2405. <p>
  2406. Creates a new thread, pushes it on the stack,
  2407. and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
  2408. The new state returned by this function shares with the original state
  2409. all global objects (such as tables),
  2410. but has an independent execution stack.
  2411. <p>
  2412. There is no explicit function to close or to destroy a thread.
  2413. Threads are subject to garbage collection,
  2414. like any Lua object.
  2415. <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
  2416. <span class="apii">[-0, +1, <em>m</em>]</span>
  2417. <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
  2418. <p>
  2419. This function allocates a new block of memory with the given size,
  2420. pushes onto the stack a new full userdata with the block address,
  2421. and returns this address.
  2422. <p>
  2423. Userdata represent C&nbsp;values in Lua.
  2424. A <em>full userdata</em> represents a block of memory.
  2425. It is an object (like a table):
  2426. you must create it, it can have its own metatable,
  2427. and you can detect when it is being collected.
  2428. A full userdata is only equal to itself (under raw equality).
  2429. <p>
  2430. When Lua collects a full userdata with a <code>gc</code> metamethod,
  2431. Lua calls the metamethod and marks the userdata as finalized.
  2432. When this userdata is collected again then
  2433. Lua frees its corresponding memory.
  2434. <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
  2435. <span class="apii">[-1, +(2|0), <em>e</em>]</span>
  2436. <pre>int lua_next (lua_State *L, int index);</pre>
  2437. <p>
  2438. Pops a key from the stack,
  2439. and pushes a key-value pair from the table at the given index
  2440. (the "next" pair after the given key).
  2441. If there are no more elements in the table,
  2442. then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
  2443. <p>
  2444. A typical traversal looks like this:
  2445. <pre>
  2446. /* table is in the stack at index 't' */
  2447. lua_pushnil(L); /* first key */
  2448. while (lua_next(L, t) != 0) {
  2449. /* uses 'key' (at index -2) and 'value' (at index -1) */
  2450. printf("%s - %s\n",
  2451. lua_typename(L, lua_type(L, -2)),
  2452. lua_typename(L, lua_type(L, -1)));
  2453. /* removes 'value'; keeps 'key' for next iteration */
  2454. lua_pop(L, 1);
  2455. }
  2456. </pre>
  2457. <p>
  2458. While traversing a table,
  2459. do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
  2460. unless you know that the key is actually a string.
  2461. Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
  2462. the value at the given index;
  2463. this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
  2464. <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
  2465. <pre>typedef double lua_Number;</pre>
  2466. <p>
  2467. The type of numbers in Lua.
  2468. By default, it is double, but that can be changed in <code>luaconf.h</code>.
  2469. <p>
  2470. Through the configuration file you can change
  2471. Lua to operate with another type for numbers (e.g., float or long).
  2472. <hr><h3><a name="lua_objlen"><code>lua_objlen</code></a></h3><p>
  2473. <span class="apii">[-0, +0, <em>-</em>]</span>
  2474. <pre>size_t lua_objlen (lua_State *L, int index);</pre>
  2475. <p>
  2476. Returns the "length" of the value at the given acceptable index:
  2477. for strings, this is the string length;
  2478. for tables, this is the result of the length operator ('<code>#</code>');
  2479. for userdata, this is the size of the block of memory allocated
  2480. for the userdata;
  2481. for other values, it is&nbsp;0.
  2482. <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
  2483. <span class="apii">[-(nargs + 1), +(nresults|1), <em>-</em>]</span>
  2484. <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);</pre>
  2485. <p>
  2486. Calls a function in protected mode.
  2487. <p>
  2488. Both <code>nargs</code> and <code>nresults</code> have the same meaning as
  2489. in <a href="#lua_call"><code>lua_call</code></a>.
  2490. If there are no errors during the call,
  2491. <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
  2492. However, if there is any error,
  2493. <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
  2494. pushes a single value on the stack (the error message),
  2495. and returns an error code.
  2496. Like <a href="#lua_call"><code>lua_call</code></a>,
  2497. <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
  2498. and its arguments from the stack.
  2499. <p>
  2500. If <code>errfunc</code> is 0,
  2501. then the error message returned on the stack
  2502. is exactly the original error message.
  2503. Otherwise, <code>errfunc</code> is the stack index of an
  2504. <em>error handler function</em>.
  2505. (In the current implementation, this index cannot be a pseudo-index.)
  2506. In case of runtime errors,
  2507. this function will be called with the error message
  2508. and its return value will be the message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
  2509. <p>
  2510. Typically, the error handler function is used to add more debug
  2511. information to the error message, such as a stack traceback.
  2512. Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
  2513. since by then the stack has unwound.
  2514. <p>
  2515. The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
  2516. or one of the following error codes
  2517. (defined in <code>lua.h</code>):
  2518. <ul>
  2519. <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b>
  2520. a runtime error.
  2521. </li>
  2522. <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
  2523. memory allocation error.
  2524. For such errors, Lua does not call the error handler function.
  2525. </li>
  2526. <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
  2527. error while running the error handler function.
  2528. </li>
  2529. </ul>
  2530. <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
  2531. <span class="apii">[-n, +0, <em>-</em>]</span>
  2532. <pre>void lua_pop (lua_State *L, int n);</pre>
  2533. <p>
  2534. Pops <code>n</code> elements from the stack.
  2535. <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
  2536. <span class="apii">[-0, +1, <em>-</em>]</span>
  2537. <pre>void lua_pushboolean (lua_State *L, int b);</pre>
  2538. <p>
  2539. Pushes a boolean value with value <code>b</code> onto the stack.
  2540. <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
  2541. <span class="apii">[-n, +1, <em>m</em>]</span>
  2542. <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
  2543. <p>
  2544. Pushes a new C&nbsp;closure onto the stack.
  2545. <p>
  2546. When a C&nbsp;function is created,
  2547. it is possible to associate some values with it,
  2548. thus creating a C&nbsp;closure (see <a href="#3.4">&sect;3.4</a>);
  2549. these values are then accessible to the function whenever it is called.
  2550. To associate values with a C&nbsp;function,
  2551. first these values should be pushed onto the stack
  2552. (when there are multiple values, the first value is pushed first).
  2553. Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
  2554. is called to create and push the C&nbsp;function onto the stack,
  2555. with the argument <code>n</code> telling how many values should be
  2556. associated with the function.
  2557. <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
  2558. <p>
  2559. The maximum value for <code>n</code> is 255.
  2560. <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
  2561. <span class="apii">[-0, +1, <em>m</em>]</span>
  2562. <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
  2563. <p>
  2564. Pushes a C&nbsp;function onto the stack.
  2565. This function receives a pointer to a C function
  2566. and pushes onto the stack a Lua value of type <code>function</code> that,
  2567. when called, invokes the corresponding C&nbsp;function.
  2568. <p>
  2569. Any function to be registered in Lua must
  2570. follow the correct protocol to receive its parameters
  2571. and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
  2572. <p>
  2573. <code>lua_pushcfunction</code> is defined as a macro:
  2574. <pre>
  2575. #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
  2576. </pre>
  2577. <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
  2578. <span class="apii">[-0, +1, <em>m</em>]</span>
  2579. <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
  2580. <p>
  2581. Pushes onto the stack a formatted string
  2582. and returns a pointer to this string.
  2583. It is similar to the C&nbsp;function <code>sprintf</code>,
  2584. but has some important differences:
  2585. <ul>
  2586. <li>
  2587. You do not have to allocate space for the result:
  2588. the result is a Lua string and Lua takes care of memory allocation
  2589. (and deallocation, through garbage collection).
  2590. </li>
  2591. <li>
  2592. The conversion specifiers are quite restricted.
  2593. There are no flags, widths, or precisions.
  2594. The conversion specifiers can only be
  2595. '<code>%%</code>' (inserts a '<code>%</code>' in the string),
  2596. '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
  2597. '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
  2598. '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
  2599. '<code>%d</code>' (inserts an <code>int</code>), and
  2600. '<code>%c</code>' (inserts an <code>int</code> as a character).
  2601. </li>
  2602. </ul>
  2603. <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
  2604. <span class="apii">[-0, +1, <em>-</em>]</span>
  2605. <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
  2606. <p>
  2607. Pushes a number with value <code>n</code> onto the stack.
  2608. <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
  2609. <span class="apii">[-0, +1, <em>-</em>]</span>
  2610. <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
  2611. <p>
  2612. Pushes a light userdata onto the stack.
  2613. <p>
  2614. Userdata represent C&nbsp;values in Lua.
  2615. A <em>light userdata</em> represents a pointer.
  2616. It is a value (like a number):
  2617. you do not create it, it has no individual metatable,
  2618. and it is not collected (as it was never created).
  2619. A light userdata is equal to "any"
  2620. light userdata with the same C&nbsp;address.
  2621. <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
  2622. <span class="apii">[-0, +1, <em>m</em>]</span>
  2623. <pre>void lua_pushliteral (lua_State *L, const char *s);</pre>
  2624. <p>
  2625. This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
  2626. but can be used only when <code>s</code> is a literal string.
  2627. In these cases, it automatically provides the string length.
  2628. <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
  2629. <span class="apii">[-0, +1, <em>m</em>]</span>
  2630. <pre>void lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
  2631. <p>
  2632. Pushes the string pointed to by <code>s</code> with size <code>len</code>
  2633. onto the stack.
  2634. Lua makes (or reuses) an internal copy of the given string,
  2635. so the memory at <code>s</code> can be freed or reused immediately after
  2636. the function returns.
  2637. The string can contain embedded zeros.
  2638. <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
  2639. <span class="apii">[-0, +1, <em>-</em>]</span>
  2640. <pre>void lua_pushnil (lua_State *L);</pre>
  2641. <p>
  2642. Pushes a nil value onto the stack.
  2643. <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
  2644. <span class="apii">[-0, +1, <em>-</em>]</span>
  2645. <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
  2646. <p>
  2647. Pushes a number with value <code>n</code> onto the stack.
  2648. <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
  2649. <span class="apii">[-0, +1, <em>m</em>]</span>
  2650. <pre>void lua_pushstring (lua_State *L, const char *s);</pre>
  2651. <p>
  2652. Pushes the zero-terminated string pointed to by <code>s</code>
  2653. onto the stack.
  2654. Lua makes (or reuses) an internal copy of the given string,
  2655. so the memory at <code>s</code> can be freed or reused immediately after
  2656. the function returns.
  2657. The string cannot contain embedded zeros;
  2658. it is assumed to end at the first zero.
  2659. <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
  2660. <span class="apii">[-0, +1, <em>-</em>]</span>
  2661. <pre>int lua_pushthread (lua_State *L);</pre>
  2662. <p>
  2663. Pushes the thread represented by <code>L</code> onto the stack.
  2664. Returns 1 if this thread is the main thread of its state.
  2665. <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
  2666. <span class="apii">[-0, +1, <em>-</em>]</span>
  2667. <pre>void lua_pushvalue (lua_State *L, int index);</pre>
  2668. <p>
  2669. Pushes a copy of the element at the given valid index
  2670. onto the stack.
  2671. <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
  2672. <span class="apii">[-0, +1, <em>m</em>]</span>
  2673. <pre>const char *lua_pushvfstring (lua_State *L,
  2674. const char *fmt,
  2675. va_list argp);</pre>
  2676. <p>
  2677. Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
  2678. instead of a variable number of arguments.
  2679. <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
  2680. <span class="apii">[-0, +0, <em>-</em>]</span>
  2681. <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
  2682. <p>
  2683. Returns 1 if the two values in acceptable indices <code>index1</code> and
  2684. <code>index2</code> are primitively equal
  2685. (that is, without calling metamethods).
  2686. Otherwise returns&nbsp;0.
  2687. Also returns&nbsp;0 if any of the indices are non valid.
  2688. <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
  2689. <span class="apii">[-1, +1, <em>-</em>]</span>
  2690. <pre>void lua_rawget (lua_State *L, int index);</pre>
  2691. <p>
  2692. Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
  2693. (i.e., without metamethods).
  2694. <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
  2695. <span class="apii">[-0, +1, <em>-</em>]</span>
  2696. <pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
  2697. <p>
  2698. Pushes onto the stack the value <code>t[n]</code>,
  2699. where <code>t</code> is the value at the given valid index.
  2700. The access is raw;
  2701. that is, it does not invoke metamethods.
  2702. <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
  2703. <span class="apii">[-2, +0, <em>m</em>]</span>
  2704. <pre>void lua_rawset (lua_State *L, int index);</pre>
  2705. <p>
  2706. Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
  2707. (i.e., without metamethods).
  2708. <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
  2709. <span class="apii">[-1, +0, <em>m</em>]</span>
  2710. <pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
  2711. <p>
  2712. Does the equivalent of <code>t[n] = v</code>,
  2713. where <code>t</code> is the value at the given valid index
  2714. and <code>v</code> is the value at the top of the stack.
  2715. <p>
  2716. This function pops the value from the stack.
  2717. The assignment is raw;
  2718. that is, it does not invoke metamethods.
  2719. <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
  2720. <pre>typedef const char * (*lua_Reader) (lua_State *L,
  2721. void *data,
  2722. size_t *size);</pre>
  2723. <p>
  2724. The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
  2725. Every time it needs another piece of the chunk,
  2726. <a href="#lua_load"><code>lua_load</code></a> calls the reader,
  2727. passing along its <code>data</code> parameter.
  2728. The reader must return a pointer to a block of memory
  2729. with a new piece of the chunk
  2730. and set <code>size</code> to the block size.
  2731. The block must exist until the reader function is called again.
  2732. To signal the end of the chunk,
  2733. the reader must return <code>NULL</code> or set <code>size</code> to zero.
  2734. The reader function may return pieces of any size greater than zero.
  2735. <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
  2736. <span class="apii">[-0, +0, <em>e</em>]</span>
  2737. <pre>void lua_register (lua_State *L,
  2738. const char *name,
  2739. lua_CFunction f);</pre>
  2740. <p>
  2741. Sets the C function <code>f</code> as the new value of global <code>name</code>.
  2742. It is defined as a macro:
  2743. <pre>
  2744. #define lua_register(L,n,f) \
  2745. (lua_pushcfunction(L, f), lua_setglobal(L, n))
  2746. </pre>
  2747. <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
  2748. <span class="apii">[-1, +0, <em>-</em>]</span>
  2749. <pre>void lua_remove (lua_State *L, int index);</pre>
  2750. <p>
  2751. Removes the element at the given valid index,
  2752. shifting down the elements above this index to fill the gap.
  2753. Cannot be called with a pseudo-index,
  2754. because a pseudo-index is not an actual stack position.
  2755. <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
  2756. <span class="apii">[-1, +0, <em>-</em>]</span>
  2757. <pre>void lua_replace (lua_State *L, int index);</pre>
  2758. <p>
  2759. Moves the top element into the given position (and pops it),
  2760. without shifting any element
  2761. (therefore replacing the value at the given position).
  2762. <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
  2763. <span class="apii">[-?, +?, <em>-</em>]</span>
  2764. <pre>int lua_resume (lua_State *L, int narg);</pre>
  2765. <p>
  2766. Starts and resumes a coroutine in a given thread.
  2767. <p>
  2768. To start a coroutine, you first create a new thread
  2769. (see <a href="#lua_newthread"><code>lua_newthread</code></a>);
  2770. then you push onto its stack the main function plus any arguments;
  2771. then you call <a href="#lua_resume"><code>lua_resume</code></a>,
  2772. with <code>narg</code> being the number of arguments.
  2773. This call returns when the coroutine suspends or finishes its execution.
  2774. When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
  2775. or all values returned by the body function.
  2776. <a href="#lua_resume"><code>lua_resume</code></a> returns
  2777. <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
  2778. 0 if the coroutine finishes its execution
  2779. without errors,
  2780. or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
  2781. In case of errors,
  2782. the stack is not unwound,
  2783. so you can use the debug API over it.
  2784. The error message is on the top of the stack.
  2785. To restart a coroutine, you put on its stack only the values to
  2786. be passed as results from <code>yield</code>,
  2787. and then call <a href="#lua_resume"><code>lua_resume</code></a>.
  2788. <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
  2789. <span class="apii">[-0, +0, <em>-</em>]</span>
  2790. <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
  2791. <p>
  2792. Changes the allocator function of a given state to <code>f</code>
  2793. with user data <code>ud</code>.
  2794. <hr><h3><a name="lua_setfenv"><code>lua_setfenv</code></a></h3><p>
  2795. <span class="apii">[-1, +0, <em>-</em>]</span>
  2796. <pre>int lua_setfenv (lua_State *L, int index);</pre>
  2797. <p>
  2798. Pops a table from the stack and sets it as
  2799. the new environment for the value at the given index.
  2800. If the value at the given index is
  2801. neither a function nor a thread nor a userdata,
  2802. <a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0.
  2803. Otherwise it returns 1.
  2804. <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
  2805. <span class="apii">[-1, +0, <em>e</em>]</span>
  2806. <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
  2807. <p>
  2808. Does the equivalent to <code>t[k] = v</code>,
  2809. where <code>t</code> is the value at the given valid index
  2810. and <code>v</code> is the value at the top of the stack.
  2811. <p>
  2812. This function pops the value from the stack.
  2813. As in Lua, this function may trigger a metamethod
  2814. for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
  2815. <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
  2816. <span class="apii">[-1, +0, <em>e</em>]</span>
  2817. <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
  2818. <p>
  2819. Pops a value from the stack and
  2820. sets it as the new value of global <code>name</code>.
  2821. It is defined as a macro:
  2822. <pre>
  2823. #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
  2824. </pre>
  2825. <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
  2826. <span class="apii">[-1, +0, <em>-</em>]</span>
  2827. <pre>int lua_setmetatable (lua_State *L, int index);</pre>
  2828. <p>
  2829. Pops a table from the stack and
  2830. sets it as the new metatable for the value at the given
  2831. acceptable index.
  2832. <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
  2833. <span class="apii">[-2, +0, <em>e</em>]</span>
  2834. <pre>void lua_settable (lua_State *L, int index);</pre>
  2835. <p>
  2836. Does the equivalent to <code>t[k] = v</code>,
  2837. where <code>t</code> is the value at the given valid index,
  2838. <code>v</code> is the value at the top of the stack,
  2839. and <code>k</code> is the value just below the top.
  2840. <p>
  2841. This function pops both the key and the value from the stack.
  2842. As in Lua, this function may trigger a metamethod
  2843. for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
  2844. <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
  2845. <span class="apii">[-?, +?, <em>-</em>]</span>
  2846. <pre>void lua_settop (lua_State *L, int index);</pre>
  2847. <p>
  2848. Accepts any acceptable index, or&nbsp;0,
  2849. and sets the stack top to this index.
  2850. If the new top is larger than the old one,
  2851. then the new elements are filled with <b>nil</b>.
  2852. If <code>index</code> is&nbsp;0, then all stack elements are removed.
  2853. <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
  2854. <pre>typedef struct lua_State lua_State;</pre>
  2855. <p>
  2856. Opaque structure that keeps the whole state of a Lua interpreter.
  2857. The Lua library is fully reentrant:
  2858. it has no global variables.
  2859. All information about a state is kept in this structure.
  2860. <p>
  2861. A pointer to this state must be passed as the first argument to
  2862. every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
  2863. which creates a Lua state from scratch.
  2864. <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
  2865. <span class="apii">[-0, +0, <em>-</em>]</span>
  2866. <pre>int lua_status (lua_State *L);</pre>
  2867. <p>
  2868. Returns the status of the thread <code>L</code>.
  2869. <p>
  2870. The status can be 0 for a normal thread,
  2871. an error code if the thread finished its execution with an error,
  2872. or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
  2873. <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
  2874. <span class="apii">[-0, +0, <em>-</em>]</span>
  2875. <pre>int lua_toboolean (lua_State *L, int index);</pre>
  2876. <p>
  2877. Converts the Lua value at the given acceptable index to a C&nbsp;boolean
  2878. value (0&nbsp;or&nbsp;1).
  2879. Like all tests in Lua,
  2880. <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
  2881. different from <b>false</b> and <b>nil</b>;
  2882. otherwise it returns 0.
  2883. It also returns 0 when called with a non-valid index.
  2884. (If you want to accept only actual boolean values,
  2885. use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
  2886. <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
  2887. <span class="apii">[-0, +0, <em>-</em>]</span>
  2888. <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
  2889. <p>
  2890. Converts a value at the given acceptable index to a C&nbsp;function.
  2891. That value must be a C&nbsp;function;
  2892. otherwise, returns <code>NULL</code>.
  2893. <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
  2894. <span class="apii">[-0, +0, <em>-</em>]</span>
  2895. <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
  2896. <p>
  2897. Converts the Lua value at the given acceptable index
  2898. to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
  2899. The Lua value must be a number or a string convertible to a number
  2900. (see <a href="#2.2.1">&sect;2.2.1</a>);
  2901. otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns&nbsp;0.
  2902. <p>
  2903. If the number is not an integer,
  2904. it is truncated in some non-specified way.
  2905. <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
  2906. <span class="apii">[-0, +0, <em>m</em>]</span>
  2907. <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
  2908. <p>
  2909. Converts the Lua value at the given acceptable index to a C&nbsp;string.
  2910. If <code>len</code> is not <code>NULL</code>,
  2911. it also sets <code>*len</code> with the string length.
  2912. The Lua value must be a string or a number;
  2913. otherwise, the function returns <code>NULL</code>.
  2914. If the value is a number,
  2915. then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
  2916. <em>changes the actual value in the stack to a string</em>.
  2917. (This change confuses <a href="#lua_next"><code>lua_next</code></a>
  2918. when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys during a table traversal.)
  2919. <p>
  2920. <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
  2921. to a string inside the Lua state.
  2922. This string always has a zero ('<code>\0</code>')
  2923. after its last character (as in&nbsp;C),
  2924. but can contain other zeros in its body.
  2925. Because Lua has garbage collection,
  2926. there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
  2927. will be valid after the corresponding value is removed from the stack.
  2928. <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
  2929. <span class="apii">[-0, +0, <em>-</em>]</span>
  2930. <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
  2931. <p>
  2932. Converts the Lua value at the given acceptable index
  2933. to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
  2934. The Lua value must be a number or a string convertible to a number
  2935. (see <a href="#2.2.1">&sect;2.2.1</a>);
  2936. otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns&nbsp;0.
  2937. <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
  2938. <span class="apii">[-0, +0, <em>-</em>]</span>
  2939. <pre>const void *lua_topointer (lua_State *L, int index);</pre>
  2940. <p>
  2941. Converts the value at the given acceptable index to a generic
  2942. C&nbsp;pointer (<code>void*</code>).
  2943. The value can be a userdata, a table, a thread, or a function;
  2944. otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
  2945. Different objects will give different pointers.
  2946. There is no way to convert the pointer back to its original value.
  2947. <p>
  2948. Typically this function is used only for debug information.
  2949. <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
  2950. <span class="apii">[-0, +0, <em>m</em>]</span>
  2951. <pre>const char *lua_tostring (lua_State *L, int index);</pre>
  2952. <p>
  2953. Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
  2954. <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
  2955. <span class="apii">[-0, +0, <em>-</em>]</span>
  2956. <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
  2957. <p>
  2958. Converts the value at the given acceptable index to a Lua thread
  2959. (represented as <code>lua_State*</code>).
  2960. This value must be a thread;
  2961. otherwise, the function returns <code>NULL</code>.
  2962. <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
  2963. <span class="apii">[-0, +0, <em>-</em>]</span>
  2964. <pre>void *lua_touserdata (lua_State *L, int index);</pre>
  2965. <p>
  2966. If the value at the given acceptable index is a full userdata,
  2967. returns its block address.
  2968. If the value is a light userdata,
  2969. returns its pointer.
  2970. Otherwise, returns <code>NULL</code>.
  2971. <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
  2972. <span class="apii">[-0, +0, <em>-</em>]</span>
  2973. <pre>int lua_type (lua_State *L, int index);</pre>
  2974. <p>
  2975. Returns the type of the value in the given acceptable index,
  2976. or <code>LUA_TNONE</code> for a non-valid index
  2977. (that is, an index to an "empty" stack position).
  2978. The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
  2979. defined in <code>lua.h</code>:
  2980. <code>LUA_TNIL</code>,
  2981. <code>LUA_TNUMBER</code>,
  2982. <code>LUA_TBOOLEAN</code>,
  2983. <code>LUA_TSTRING</code>,
  2984. <code>LUA_TTABLE</code>,
  2985. <code>LUA_TFUNCTION</code>,
  2986. <code>LUA_TUSERDATA</code>,
  2987. <code>LUA_TTHREAD</code>,
  2988. and
  2989. <code>LUA_TLIGHTUSERDATA</code>.
  2990. <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
  2991. <span class="apii">[-0, +0, <em>-</em>]</span>
  2992. <pre>const char *lua_typename (lua_State *L, int tp);</pre>
  2993. <p>
  2994. Returns the name of the type encoded by the value <code>tp</code>,
  2995. which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
  2996. <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
  2997. <pre>typedef int (*lua_Writer) (lua_State *L,
  2998. const void* p,
  2999. size_t sz,
  3000. void* ud);</pre>
  3001. <p>
  3002. The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
  3003. Every time it produces another piece of chunk,
  3004. <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
  3005. passing along the buffer to be written (<code>p</code>),
  3006. its size (<code>sz</code>),
  3007. and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
  3008. <p>
  3009. The writer returns an error code:
  3010. 0&nbsp;means no errors;
  3011. any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
  3012. calling the writer again.
  3013. <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
  3014. <span class="apii">[-?, +?, <em>-</em>]</span>
  3015. <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
  3016. <p>
  3017. Exchange values between different threads of the <em>same</em> global state.
  3018. <p>
  3019. This function pops <code>n</code> values from the stack <code>from</code>,
  3020. and pushes them onto the stack <code>to</code>.
  3021. <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
  3022. <span class="apii">[-?, +?, <em>-</em>]</span>
  3023. <pre>int lua_yield (lua_State *L, int nresults);</pre>
  3024. <p>
  3025. Yields a coroutine.
  3026. <p>
  3027. This function should only be called as the
  3028. return expression of a C&nbsp;function, as follows:
  3029. <pre>
  3030. return lua_yield (L, nresults);
  3031. </pre><p>
  3032. When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
  3033. the running coroutine suspends its execution,
  3034. and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
  3035. The parameter <code>nresults</code> is the number of values from the stack
  3036. that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
  3037. <h2>3.8 - <a name="3.8">The Debug Interface</a></h2>
  3038. <p>
  3039. Lua has no built-in debugging facilities.
  3040. Instead, it offers a special interface
  3041. by means of functions and <em>hooks</em>.
  3042. This interface allows the construction of different
  3043. kinds of debuggers, profilers, and other tools
  3044. that need "inside information" from the interpreter.
  3045. <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
  3046. <pre>typedef struct lua_Debug {
  3047. int event;
  3048. const char *name; /* (n) */
  3049. const char *namewhat; /* (n) */
  3050. const char *what; /* (S) */
  3051. const char *source; /* (S) */
  3052. int currentline; /* (l) */
  3053. int nups; /* (u) number of upvalues */
  3054. int linedefined; /* (S) */
  3055. int lastlinedefined; /* (S) */
  3056. char short_src[LUA_IDSIZE]; /* (S) */
  3057. /* private part */
  3058. <em>other fields</em>
  3059. } lua_Debug;</pre>
  3060. <p>
  3061. A structure used to carry different pieces of
  3062. information about an active function.
  3063. <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
  3064. of this structure, for later use.
  3065. To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
  3066. call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
  3067. <p>
  3068. The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
  3069. <ul>
  3070. <li><b><code>source</code>:</b>
  3071. If the function was defined in a string,
  3072. then <code>source</code> is that string.
  3073. If the function was defined in a file,
  3074. then <code>source</code> starts with a '<code>@</code>' followed by the file name.
  3075. </li>
  3076. <li><b><code>short_src</code>:</b>
  3077. a "printable" version of <code>source</code>, to be used in error messages.
  3078. </li>
  3079. <li><b><code>linedefined</code>:</b>
  3080. the line number where the definition of the function starts.
  3081. </li>
  3082. <li><b><code>lastlinedefined</code>:</b>
  3083. the line number where the definition of the function ends.
  3084. </li>
  3085. <li><b><code>what</code>:</b>
  3086. the string <code>"Lua"</code> if the function is a Lua function,
  3087. <code>"C"</code> if it is a C&nbsp;function,
  3088. <code>"main"</code> if it is the main part of a chunk,
  3089. and <code>"tail"</code> if it was a function that did a tail call.
  3090. In the latter case,
  3091. Lua has no other information about the function.
  3092. </li>
  3093. <li><b><code>currentline</code>:</b>
  3094. the current line where the given function is executing.
  3095. When no line information is available,
  3096. <code>currentline</code> is set to -1.
  3097. </li>
  3098. <li><b><code>name</code>:</b>
  3099. a reasonable name for the given function.
  3100. Because functions in Lua are first-class values,
  3101. they do not have a fixed name:
  3102. some functions can be the value of multiple global variables,
  3103. while others can be stored only in a table field.
  3104. The <code>lua_getinfo</code> function checks how the function was
  3105. called to find a suitable name.
  3106. If it cannot find a name,
  3107. then <code>name</code> is set to <code>NULL</code>.
  3108. </li>
  3109. <li><b><code>namewhat</code>:</b>
  3110. explains the <code>name</code> field.
  3111. The value of <code>namewhat</code> can be
  3112. <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
  3113. <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
  3114. according to how the function was called.
  3115. (Lua uses the empty string when no other option seems to apply.)
  3116. </li>
  3117. <li><b><code>nups</code>:</b>
  3118. the number of upvalues of the function.
  3119. </li>
  3120. </ul>
  3121. <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
  3122. <span class="apii">[-0, +0, <em>-</em>]</span>
  3123. <pre>lua_Hook lua_gethook (lua_State *L);</pre>
  3124. <p>
  3125. Returns the current hook function.
  3126. <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
  3127. <span class="apii">[-0, +0, <em>-</em>]</span>
  3128. <pre>int lua_gethookcount (lua_State *L);</pre>
  3129. <p>
  3130. Returns the current hook count.
  3131. <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
  3132. <span class="apii">[-0, +0, <em>-</em>]</span>
  3133. <pre>int lua_gethookmask (lua_State *L);</pre>
  3134. <p>
  3135. Returns the current hook mask.
  3136. <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
  3137. <span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
  3138. <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
  3139. <p>
  3140. Returns information about a specific function or function invocation.
  3141. <p>
  3142. To get information about a function invocation,
  3143. the parameter <code>ar</code> must be a valid activation record that was
  3144. filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
  3145. given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
  3146. <p>
  3147. To get information about a function you push it onto the stack
  3148. and start the <code>what</code> string with the character '<code>&gt;</code>'.
  3149. (In that case,
  3150. <code>lua_getinfo</code> pops the function in the top of the stack.)
  3151. For instance, to know in which line a function <code>f</code> was defined,
  3152. you can write the following code:
  3153. <pre>
  3154. lua_Debug ar;
  3155. lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
  3156. lua_getinfo(L, "&gt;S", &amp;ar);
  3157. printf("%d\n", ar.linedefined);
  3158. </pre>
  3159. <p>
  3160. Each character in the string <code>what</code>
  3161. selects some fields of the structure <code>ar</code> to be filled or
  3162. a value to be pushed on the stack:
  3163. <ul>
  3164. <li><b>'<code>n</code>':</b> fills in the field <code>name</code> and <code>namewhat</code>;
  3165. </li>
  3166. <li><b>'<code>S</code>':</b>
  3167. fills in the fields <code>source</code>, <code>short_src</code>,
  3168. <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
  3169. </li>
  3170. <li><b>'<code>l</code>':</b> fills in the field <code>currentline</code>;
  3171. </li>
  3172. <li><b>'<code>u</code>':</b> fills in the field <code>nups</code>;
  3173. </li>
  3174. <li><b>'<code>f</code>':</b>
  3175. pushes onto the stack the function that is
  3176. running at the given level;
  3177. </li>
  3178. <li><b>'<code>L</code>':</b>
  3179. pushes onto the stack a table whose indices are the
  3180. numbers of the lines that are valid on the function.
  3181. (A <em>valid line</em> is a line with some associated code,
  3182. that is, a line where you can put a break point.
  3183. Non-valid lines include empty lines and comments.)
  3184. </li>
  3185. </ul>
  3186. <p>
  3187. This function returns 0 on error
  3188. (for instance, an invalid option in <code>what</code>).
  3189. <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
  3190. <span class="apii">[-0, +(0|1), <em>-</em>]</span>
  3191. <pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
  3192. <p>
  3193. Gets information about a local variable of a given activation record.
  3194. The parameter <code>ar</code> must be a valid activation record that was
  3195. filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
  3196. given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
  3197. The index <code>n</code> selects which local variable to inspect
  3198. (1 is the first parameter or active local variable, and so on,
  3199. until the last active local variable).
  3200. <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
  3201. and returns its name.
  3202. <p>
  3203. Variable names starting with '<code>(</code>' (open parentheses)
  3204. represent internal variables
  3205. (loop control variables, temporaries, and C&nbsp;function locals).
  3206. <p>
  3207. Returns <code>NULL</code> (and pushes nothing)
  3208. when the index is greater than
  3209. the number of active local variables.
  3210. <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
  3211. <span class="apii">[-0, +0, <em>-</em>]</span>
  3212. <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
  3213. <p>
  3214. Get information about the interpreter runtime stack.
  3215. <p>
  3216. This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
  3217. an identification of the <em>activation record</em>
  3218. of the function executing at a given level.
  3219. Level&nbsp;0 is the current running function,
  3220. whereas level <em>n+1</em> is the function that has called level <em>n</em>.
  3221. When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
  3222. when called with a level greater than the stack depth,
  3223. it returns 0.
  3224. <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
  3225. <span class="apii">[-0, +(0|1), <em>-</em>]</span>
  3226. <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
  3227. <p>
  3228. Gets information about a closure's upvalue.
  3229. (For Lua functions,
  3230. upvalues are the external local variables that the function uses,
  3231. and that are consequently included in its closure.)
  3232. <a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
  3233. pushes the upvalue's value onto the stack,
  3234. and returns its name.
  3235. <code>funcindex</code> points to the closure in the stack.
  3236. (Upvalues have no particular order,
  3237. as they are active through the whole function.
  3238. So, they are numbered in an arbitrary order.)
  3239. <p>
  3240. Returns <code>NULL</code> (and pushes nothing)
  3241. when the index is greater than the number of upvalues.
  3242. For C&nbsp;functions, this function uses the empty string <code>""</code>
  3243. as a name for all upvalues.
  3244. <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
  3245. <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
  3246. <p>
  3247. Type for debugging hook functions.
  3248. <p>
  3249. Whenever a hook is called, its <code>ar</code> argument has its field
  3250. <code>event</code> set to the specific event that triggered the hook.
  3251. Lua identifies these events with the following constants:
  3252. <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
  3253. <a name="pdf-LUA_HOOKTAILRET"><code>LUA_HOOKTAILRET</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
  3254. and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
  3255. Moreover, for line events, the field <code>currentline</code> is also set.
  3256. To get the value of any other field in <code>ar</code>,
  3257. the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
  3258. For return events, <code>event</code> can be <code>LUA_HOOKRET</code>,
  3259. the normal value, or <code>LUA_HOOKTAILRET</code>.
  3260. In the latter case, Lua is simulating a return from
  3261. a function that did a tail call;
  3262. in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
  3263. <p>
  3264. While Lua is running a hook, it disables other calls to hooks.
  3265. Therefore, if a hook calls back Lua to execute a function or a chunk,
  3266. this execution occurs without any calls to hooks.
  3267. <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
  3268. <span class="apii">[-0, +0, <em>-</em>]</span>
  3269. <pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
  3270. <p>
  3271. Sets the debugging hook function.
  3272. <p>
  3273. Argument <code>f</code> is the hook function.
  3274. <code>mask</code> specifies on which events the hook will be called:
  3275. it is formed by a bitwise or of the constants
  3276. <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
  3277. <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
  3278. <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
  3279. and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
  3280. The <code>count</code> argument is only meaningful when the mask
  3281. includes <code>LUA_MASKCOUNT</code>.
  3282. For each event, the hook is called as explained below:
  3283. <ul>
  3284. <li><b>The call hook:</b> is called when the interpreter calls a function.
  3285. The hook is called just after Lua enters the new function,
  3286. before the function gets its arguments.
  3287. </li>
  3288. <li><b>The return hook:</b> is called when the interpreter returns from a function.
  3289. The hook is called just before Lua leaves the function.
  3290. You have no access to the values to be returned by the function.
  3291. </li>
  3292. <li><b>The line hook:</b> is called when the interpreter is about to
  3293. start the execution of a new line of code,
  3294. or when it jumps back in the code (even to the same line).
  3295. (This event only happens while Lua is executing a Lua function.)
  3296. </li>
  3297. <li><b>The count hook:</b> is called after the interpreter executes every
  3298. <code>count</code> instructions.
  3299. (This event only happens while Lua is executing a Lua function.)
  3300. </li>
  3301. </ul>
  3302. <p>
  3303. A hook is disabled by setting <code>mask</code> to zero.
  3304. <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
  3305. <span class="apii">[-(0|1), +0, <em>-</em>]</span>
  3306. <pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
  3307. <p>
  3308. Sets the value of a local variable of a given activation record.
  3309. Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
  3310. (see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
  3311. <a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
  3312. to the variable and returns its name.
  3313. It also pops the value from the stack.
  3314. <p>
  3315. Returns <code>NULL</code> (and pops nothing)
  3316. when the index is greater than
  3317. the number of active local variables.
  3318. <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
  3319. <span class="apii">[-(0|1), +0, <em>-</em>]</span>
  3320. <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
  3321. <p>
  3322. Sets the value of a closure's upvalue.
  3323. It assigns the value at the top of the stack
  3324. to the upvalue and returns its name.
  3325. It also pops the value from the stack.
  3326. Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
  3327. (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
  3328. <p>
  3329. Returns <code>NULL</code> (and pops nothing)
  3330. when the index is greater than the number of upvalues.
  3331. <h1>4 - <a name="4">The Auxiliary Library</a></h1>
  3332. <p>
  3333. The <em>auxiliary library</em> provides several convenient functions
  3334. to interface C with Lua.
  3335. While the basic API provides the primitive functions for all
  3336. interactions between C and Lua,
  3337. the auxiliary library provides higher-level functions for some
  3338. common tasks.
  3339. <p>
  3340. All functions from the auxiliary library
  3341. are defined in header file <code>lauxlib.h</code> and
  3342. have a prefix <code>luaL_</code>.
  3343. <p>
  3344. All functions in the auxiliary library are built on
  3345. top of the basic API,
  3346. and so they provide nothing that cannot be done with this API.
  3347. <p>
  3348. Several functions in the auxiliary library are used to
  3349. check C&nbsp;function arguments.
  3350. Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
  3351. All of these functions throw an error if the check is not satisfied.
  3352. Because the error message is formatted for arguments
  3353. (e.g., "<code>bad argument #1</code>"),
  3354. you should not use these functions for other stack values.
  3355. <h2>4.1 - <a name="4.1">Functions and Types</a></h2>
  3356. <p>
  3357. Here we list all functions and types from the auxiliary library
  3358. in alphabetical order.
  3359. <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
  3360. <span class="apii">[-0, +0, <em>m</em>]</span>
  3361. <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
  3362. <p>
  3363. Adds the character <code>c</code> to the buffer <code>B</code>
  3364. (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
  3365. <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
  3366. <span class="apii">[-0, +0, <em>m</em>]</span>
  3367. <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
  3368. <p>
  3369. Adds the string pointed to by <code>s</code> with length <code>l</code> to
  3370. the buffer <code>B</code>
  3371. (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
  3372. The string may contain embedded zeros.
  3373. <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
  3374. <span class="apii">[-0, +0, <em>m</em>]</span>
  3375. <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
  3376. <p>
  3377. Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
  3378. a string of length <code>n</code> previously copied to the
  3379. buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
  3380. <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
  3381. <span class="apii">[-0, +0, <em>m</em>]</span>
  3382. <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
  3383. <p>
  3384. Adds the zero-terminated string pointed to by <code>s</code>
  3385. to the buffer <code>B</code>
  3386. (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
  3387. The string may not contain embedded zeros.
  3388. <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
  3389. <span class="apii">[-1, +0, <em>m</em>]</span>
  3390. <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
  3391. <p>
  3392. Adds the value at the top of the stack
  3393. to the buffer <code>B</code>
  3394. (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
  3395. Pops the value.
  3396. <p>
  3397. This is the only function on string buffers that can (and must)
  3398. be called with an extra element on the stack,
  3399. which is the value to be added to the buffer.
  3400. <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
  3401. <span class="apii">[-0, +0, <em>v</em>]</span>
  3402. <pre>void luaL_argcheck (lua_State *L,
  3403. int cond,
  3404. int narg,
  3405. const char *extramsg);</pre>
  3406. <p>
  3407. Checks whether <code>cond</code> is true.
  3408. If not, raises an error with the following message,
  3409. where <code>func</code> is retrieved from the call stack:
  3410. <pre>
  3411. bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
  3412. </pre>
  3413. <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
  3414. <span class="apii">[-0, +0, <em>v</em>]</span>
  3415. <pre>int luaL_argerror (lua_State *L, int narg, const char *extramsg);</pre>
  3416. <p>
  3417. Raises an error with the following message,
  3418. where <code>func</code> is retrieved from the call stack:
  3419. <pre>
  3420. bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
  3421. </pre>
  3422. <p>
  3423. This function never returns,
  3424. but it is an idiom to use it in C&nbsp;functions
  3425. as <code>return luaL_argerror(<em>args</em>)</code>.
  3426. <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
  3427. <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
  3428. <p>
  3429. Type for a <em>string buffer</em>.
  3430. <p>
  3431. A string buffer allows C&nbsp;code to build Lua strings piecemeal.
  3432. Its pattern of use is as follows:
  3433. <ul>
  3434. <li>First you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
  3435. <li>Then you initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
  3436. <li>
  3437. Then you add string pieces to the buffer calling any of
  3438. the <code>luaL_add*</code> functions.
  3439. </li>
  3440. <li>
  3441. You finish by calling <code>luaL_pushresult(&amp;b)</code>.
  3442. This call leaves the final string on the top of the stack.
  3443. </li>
  3444. </ul>
  3445. <p>
  3446. During its normal operation,
  3447. a string buffer uses a variable number of stack slots.
  3448. So, while using a buffer, you cannot assume that you know where
  3449. the top of the stack is.
  3450. You can use the stack between successive calls to buffer operations
  3451. as long as that use is balanced;
  3452. that is,
  3453. when you call a buffer operation,
  3454. the stack is at the same level
  3455. it was immediately after the previous buffer operation.
  3456. (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
  3457. After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
  3458. level when the buffer was initialized,
  3459. plus the final string on its top.
  3460. <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
  3461. <span class="apii">[-0, +0, <em>-</em>]</span>
  3462. <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
  3463. <p>
  3464. Initializes a buffer <code>B</code>.
  3465. This function does not allocate any space;
  3466. the buffer must be declared as a variable
  3467. (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
  3468. <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
  3469. <span class="apii">[-0, +(0|1), <em>e</em>]</span>
  3470. <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
  3471. <p>
  3472. Calls a metamethod.
  3473. <p>
  3474. If the object at index <code>obj</code> has a metatable and this
  3475. metatable has a field <code>e</code>,
  3476. this function calls this field and passes the object as its only argument.
  3477. In this case this function returns 1 and pushes onto the
  3478. stack the value returned by the call.
  3479. If there is no metatable or no metamethod,
  3480. this function returns 0 (without pushing any value on the stack).
  3481. <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
  3482. <span class="apii">[-0, +0, <em>v</em>]</span>
  3483. <pre>void luaL_checkany (lua_State *L, int narg);</pre>
  3484. <p>
  3485. Checks whether the function has an argument
  3486. of any type (including <b>nil</b>) at position <code>narg</code>.
  3487. <hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
  3488. <span class="apii">[-0, +0, <em>v</em>]</span>
  3489. <pre>int luaL_checkint (lua_State *L, int narg);</pre>
  3490. <p>
  3491. Checks whether the function argument <code>narg</code> is a number
  3492. and returns this number cast to an <code>int</code>.
  3493. <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
  3494. <span class="apii">[-0, +0, <em>v</em>]</span>
  3495. <pre>lua_Integer luaL_checkinteger (lua_State *L, int narg);</pre>
  3496. <p>
  3497. Checks whether the function argument <code>narg</code> is a number
  3498. and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
  3499. <hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
  3500. <span class="apii">[-0, +0, <em>v</em>]</span>
  3501. <pre>long luaL_checklong (lua_State *L, int narg);</pre>
  3502. <p>
  3503. Checks whether the function argument <code>narg</code> is a number
  3504. and returns this number cast to a <code>long</code>.
  3505. <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
  3506. <span class="apii">[-0, +0, <em>v</em>]</span>
  3507. <pre>const char *luaL_checklstring (lua_State *L, int narg, size_t *l);</pre>
  3508. <p>
  3509. Checks whether the function argument <code>narg</code> is a string
  3510. and returns this string;
  3511. if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
  3512. with the string's length.
  3513. <p>
  3514. This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
  3515. so all conversions and caveats of that function apply here.
  3516. <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
  3517. <span class="apii">[-0, +0, <em>v</em>]</span>
  3518. <pre>lua_Number luaL_checknumber (lua_State *L, int narg);</pre>
  3519. <p>
  3520. Checks whether the function argument <code>narg</code> is a number
  3521. and returns this number.
  3522. <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
  3523. <span class="apii">[-0, +0, <em>v</em>]</span>
  3524. <pre>int luaL_checkoption (lua_State *L,
  3525. int narg,
  3526. const char *def,
  3527. const char *const lst[]);</pre>
  3528. <p>
  3529. Checks whether the function argument <code>narg</code> is a string and
  3530. searches for this string in the array <code>lst</code>
  3531. (which must be NULL-terminated).
  3532. Returns the index in the array where the string was found.
  3533. Raises an error if the argument is not a string or
  3534. if the string cannot be found.
  3535. <p>
  3536. If <code>def</code> is not <code>NULL</code>,
  3537. the function uses <code>def</code> as a default value when
  3538. there is no argument <code>narg</code> or if this argument is <b>nil</b>.
  3539. <p>
  3540. This is a useful function for mapping strings to C&nbsp;enums.
  3541. (The usual convention in Lua libraries is
  3542. to use strings instead of numbers to select options.)
  3543. <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
  3544. <span class="apii">[-0, +0, <em>v</em>]</span>
  3545. <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
  3546. <p>
  3547. Grows the stack size to <code>top + sz</code> elements,
  3548. raising an error if the stack cannot grow to that size.
  3549. <code>msg</code> is an additional text to go into the error message.
  3550. <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
  3551. <span class="apii">[-0, +0, <em>v</em>]</span>
  3552. <pre>const char *luaL_checkstring (lua_State *L, int narg);</pre>
  3553. <p>
  3554. Checks whether the function argument <code>narg</code> is a string
  3555. and returns this string.
  3556. <p>
  3557. This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
  3558. so all conversions and caveats of that function apply here.
  3559. <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
  3560. <span class="apii">[-0, +0, <em>v</em>]</span>
  3561. <pre>void luaL_checktype (lua_State *L, int narg, int t);</pre>
  3562. <p>
  3563. Checks whether the function argument <code>narg</code> has type <code>t</code>.
  3564. See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
  3565. <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
  3566. <span class="apii">[-0, +0, <em>v</em>]</span>
  3567. <pre>void *luaL_checkudata (lua_State *L, int narg, const char *tname);</pre>
  3568. <p>
  3569. Checks whether the function argument <code>narg</code> is a userdata
  3570. of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
  3571. <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
  3572. <span class="apii">[-0, +?, <em>m</em>]</span>
  3573. <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
  3574. <p>
  3575. Loads and runs the given file.
  3576. It is defined as the following macro:
  3577. <pre>
  3578. (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
  3579. </pre><p>
  3580. It returns 0 if there are no errors
  3581. or 1 in case of errors.
  3582. <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
  3583. <span class="apii">[-0, +?, <em>m</em>]</span>
  3584. <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
  3585. <p>
  3586. Loads and runs the given string.
  3587. It is defined as the following macro:
  3588. <pre>
  3589. (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
  3590. </pre><p>
  3591. It returns 0 if there are no errors
  3592. or 1 in case of errors.
  3593. <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
  3594. <span class="apii">[-0, +0, <em>v</em>]</span>
  3595. <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
  3596. <p>
  3597. Raises an error.
  3598. The error message format is given by <code>fmt</code>
  3599. plus any extra arguments,
  3600. following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
  3601. It also adds at the beginning of the message the file name and
  3602. the line number where the error occurred,
  3603. if this information is available.
  3604. <p>
  3605. This function never returns,
  3606. but it is an idiom to use it in C&nbsp;functions
  3607. as <code>return luaL_error(<em>args</em>)</code>.
  3608. <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
  3609. <span class="apii">[-0, +(0|1), <em>m</em>]</span>
  3610. <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
  3611. <p>
  3612. Pushes onto the stack the field <code>e</code> from the metatable
  3613. of the object at index <code>obj</code>.
  3614. If the object does not have a metatable,
  3615. or if the metatable does not have this field,
  3616. returns 0 and pushes nothing.
  3617. <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
  3618. <span class="apii">[-0, +1, <em>-</em>]</span>
  3619. <pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
  3620. <p>
  3621. Pushes onto the stack the metatable associated with name <code>tname</code>
  3622. in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
  3623. <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
  3624. <span class="apii">[-0, +1, <em>m</em>]</span>
  3625. <pre>const char *luaL_gsub (lua_State *L,
  3626. const char *s,
  3627. const char *p,
  3628. const char *r);</pre>
  3629. <p>
  3630. Creates a copy of string <code>s</code> by replacing
  3631. any occurrence of the string <code>p</code>
  3632. with the string <code>r</code>.
  3633. Pushes the resulting string on the stack and returns it.
  3634. <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
  3635. <span class="apii">[-0, +1, <em>m</em>]</span>
  3636. <pre>int luaL_loadbuffer (lua_State *L,
  3637. const char *buff,
  3638. size_t sz,
  3639. const char *name);</pre>
  3640. <p>
  3641. Loads a buffer as a Lua chunk.
  3642. This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
  3643. buffer pointed to by <code>buff</code> with size <code>sz</code>.
  3644. <p>
  3645. This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
  3646. <code>name</code> is the chunk name,
  3647. used for debug information and error messages.
  3648. <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
  3649. <span class="apii">[-0, +1, <em>m</em>]</span>
  3650. <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
  3651. <p>
  3652. Loads a file as a Lua chunk.
  3653. This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
  3654. named <code>filename</code>.
  3655. If <code>filename</code> is <code>NULL</code>,
  3656. then it loads from the standard input.
  3657. The first line in the file is ignored if it starts with a <code>#</code>.
  3658. <p>
  3659. This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
  3660. but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
  3661. if it cannot open/read the file.
  3662. <p>
  3663. As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
  3664. it does not run it.
  3665. <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
  3666. <span class="apii">[-0, +1, <em>m</em>]</span>
  3667. <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
  3668. <p>
  3669. Loads a string as a Lua chunk.
  3670. This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
  3671. the zero-terminated string <code>s</code>.
  3672. <p>
  3673. This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
  3674. <p>
  3675. Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
  3676. it does not run it.
  3677. <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
  3678. <span class="apii">[-0, +1, <em>m</em>]</span>
  3679. <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
  3680. <p>
  3681. If the registry already has the key <code>tname</code>,
  3682. returns 0.
  3683. Otherwise,
  3684. creates a new table to be used as a metatable for userdata,
  3685. adds it to the registry with key <code>tname</code>,
  3686. and returns 1.
  3687. <p>
  3688. In both cases pushes onto the stack the final value associated
  3689. with <code>tname</code> in the registry.
  3690. <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
  3691. <span class="apii">[-0, +0, <em>-</em>]</span>
  3692. <pre>lua_State *luaL_newstate (void);</pre>
  3693. <p>
  3694. Creates a new Lua state.
  3695. It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
  3696. allocator based on the standard&nbsp;C <code>realloc</code> function
  3697. and then sets a panic function (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) that prints
  3698. an error message to the standard error output in case of fatal
  3699. errors.
  3700. <p>
  3701. Returns the new state,
  3702. or <code>NULL</code> if there is a memory allocation error.
  3703. <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
  3704. <span class="apii">[-0, +0, <em>m</em>]</span>
  3705. <pre>void luaL_openlibs (lua_State *L);</pre>
  3706. <p>
  3707. Opens all standard Lua libraries into the given state.
  3708. <hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
  3709. <span class="apii">[-0, +0, <em>v</em>]</span>
  3710. <pre>int luaL_optint (lua_State *L, int narg, int d);</pre>
  3711. <p>
  3712. If the function argument <code>narg</code> is a number,
  3713. returns this number cast to an <code>int</code>.
  3714. If this argument is absent or is <b>nil</b>,
  3715. returns <code>d</code>.
  3716. Otherwise, raises an error.
  3717. <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
  3718. <span class="apii">[-0, +0, <em>v</em>]</span>
  3719. <pre>lua_Integer luaL_optinteger (lua_State *L,
  3720. int narg,
  3721. lua_Integer d);</pre>
  3722. <p>
  3723. If the function argument <code>narg</code> is a number,
  3724. returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
  3725. If this argument is absent or is <b>nil</b>,
  3726. returns <code>d</code>.
  3727. Otherwise, raises an error.
  3728. <hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3><p>
  3729. <span class="apii">[-0, +0, <em>v</em>]</span>
  3730. <pre>long luaL_optlong (lua_State *L, int narg, long d);</pre>
  3731. <p>
  3732. If the function argument <code>narg</code> is a number,
  3733. returns this number cast to a <code>long</code>.
  3734. If this argument is absent or is <b>nil</b>,
  3735. returns <code>d</code>.
  3736. Otherwise, raises an error.
  3737. <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
  3738. <span class="apii">[-0, +0, <em>v</em>]</span>
  3739. <pre>const char *luaL_optlstring (lua_State *L,
  3740. int narg,
  3741. const char *d,
  3742. size_t *l);</pre>
  3743. <p>
  3744. If the function argument <code>narg</code> is a string,
  3745. returns this string.
  3746. If this argument is absent or is <b>nil</b>,
  3747. returns <code>d</code>.
  3748. Otherwise, raises an error.
  3749. <p>
  3750. If <code>l</code> is not <code>NULL</code>,
  3751. fills the position <code>*l</code> with the results's length.
  3752. <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
  3753. <span class="apii">[-0, +0, <em>v</em>]</span>
  3754. <pre>lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);</pre>
  3755. <p>
  3756. If the function argument <code>narg</code> is a number,
  3757. returns this number.
  3758. If this argument is absent or is <b>nil</b>,
  3759. returns <code>d</code>.
  3760. Otherwise, raises an error.
  3761. <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
  3762. <span class="apii">[-0, +0, <em>v</em>]</span>
  3763. <pre>const char *luaL_optstring (lua_State *L,
  3764. int narg,
  3765. const char *d);</pre>
  3766. <p>
  3767. If the function argument <code>narg</code> is a string,
  3768. returns this string.
  3769. If this argument is absent or is <b>nil</b>,
  3770. returns <code>d</code>.
  3771. Otherwise, raises an error.
  3772. <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
  3773. <span class="apii">[-0, +0, <em>-</em>]</span>
  3774. <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
  3775. <p>
  3776. Returns an address to a space of size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>
  3777. where you can copy a string to be added to buffer <code>B</code>
  3778. (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
  3779. After copying the string into this space you must call
  3780. <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
  3781. it to the buffer.
  3782. <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
  3783. <span class="apii">[-?, +1, <em>m</em>]</span>
  3784. <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
  3785. <p>
  3786. Finishes the use of buffer <code>B</code> leaving the final string on
  3787. the top of the stack.
  3788. <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
  3789. <span class="apii">[-1, +0, <em>m</em>]</span>
  3790. <pre>int luaL_ref (lua_State *L, int t);</pre>
  3791. <p>
  3792. Creates and returns a <em>reference</em>,
  3793. in the table at index <code>t</code>,
  3794. for the object at the top of the stack (and pops the object).
  3795. <p>
  3796. A reference is a unique integer key.
  3797. As long as you do not manually add integer keys into table <code>t</code>,
  3798. <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
  3799. You can retrieve an object referred by reference <code>r</code>
  3800. by calling <code>lua_rawgeti(L, t, r)</code>.
  3801. Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
  3802. <p>
  3803. If the object at the top of the stack is <b>nil</b>,
  3804. <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
  3805. The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
  3806. from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
  3807. <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
  3808. <pre>typedef struct luaL_Reg {
  3809. const char *name;
  3810. lua_CFunction func;
  3811. } luaL_Reg;</pre>
  3812. <p>
  3813. Type for arrays of functions to be registered by
  3814. <a href="#luaL_register"><code>luaL_register</code></a>.
  3815. <code>name</code> is the function name and <code>func</code> is a pointer to
  3816. the function.
  3817. Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
  3818. in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
  3819. <hr><h3><a name="luaL_register"><code>luaL_register</code></a></h3><p>
  3820. <span class="apii">[-(0|1), +1, <em>m</em>]</span>
  3821. <pre>void luaL_register (lua_State *L,
  3822. const char *libname,
  3823. const luaL_Reg *l);</pre>
  3824. <p>
  3825. Opens a library.
  3826. <p>
  3827. When called with <code>libname</code> equal to <code>NULL</code>,
  3828. it simply registers all functions in the list <code>l</code>
  3829. (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
  3830. <p>
  3831. When called with a non-null <code>libname</code>,
  3832. <code>luaL_register</code> creates a new table <code>t</code>,
  3833. sets it as the value of the global variable <code>libname</code>,
  3834. sets it as the value of <code>package.loaded[libname]</code>,
  3835. and registers on it all functions in the list <code>l</code>.
  3836. If there is a table in <code>package.loaded[libname]</code> or in
  3837. variable <code>libname</code>,
  3838. reuses this table instead of creating a new one.
  3839. <p>
  3840. In any case the function leaves the table
  3841. on the top of the stack.
  3842. <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
  3843. <span class="apii">[-0, +0, <em>-</em>]</span>
  3844. <pre>const char *luaL_typename (lua_State *L, int index);</pre>
  3845. <p>
  3846. Returns the name of the type of the value at the given index.
  3847. <hr><h3><a name="luaL_typerror"><code>luaL_typerror</code></a></h3><p>
  3848. <span class="apii">[-0, +0, <em>v</em>]</span>
  3849. <pre>int luaL_typerror (lua_State *L, int narg, const char *tname);</pre>
  3850. <p>
  3851. Generates an error with a message like the following:
  3852. <pre>
  3853. <em>location</em>: bad argument <em>narg</em> to '<em>func</em>' (<em>tname</em> expected, got <em>rt</em>)
  3854. </pre><p>
  3855. where <code><em>location</em></code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
  3856. <code><em>func</em></code> is the name of the current function,
  3857. and <code><em>rt</em></code> is the type name of the actual argument.
  3858. <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
  3859. <span class="apii">[-0, +0, <em>-</em>]</span>
  3860. <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
  3861. <p>
  3862. Releases reference <code>ref</code> from the table at index <code>t</code>
  3863. (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
  3864. The entry is removed from the table,
  3865. so that the referred object can be collected.
  3866. The reference <code>ref</code> is also freed to be used again.
  3867. <p>
  3868. If <code>ref</code> is <a href="#pdf-LUA_NOREF"><code>LUA_NOREF</code></a> or <a href="#pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>,
  3869. <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
  3870. <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
  3871. <span class="apii">[-0, +1, <em>m</em>]</span>
  3872. <pre>void luaL_where (lua_State *L, int lvl);</pre>
  3873. <p>
  3874. Pushes onto the stack a string identifying the current position
  3875. of the control at level <code>lvl</code> in the call stack.
  3876. Typically this string has the following format:
  3877. <pre>
  3878. <em>chunkname</em>:<em>currentline</em>:
  3879. </pre><p>
  3880. Level&nbsp;0 is the running function,
  3881. level&nbsp;1 is the function that called the running function,
  3882. etc.
  3883. <p>
  3884. This function is used to build a prefix for error messages.
  3885. <h1>5 - <a name="5">Standard Libraries</a></h1>
  3886. <p>
  3887. The standard Lua libraries provide useful functions
  3888. that are implemented directly through the C&nbsp;API.
  3889. Some of these functions provide essential services to the language
  3890. (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
  3891. others provide access to "outside" services (e.g., I/O);
  3892. and others could be implemented in Lua itself,
  3893. but are quite useful or have critical performance requirements that
  3894. deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
  3895. <p>
  3896. All libraries are implemented through the official C&nbsp;API
  3897. and are provided as separate C&nbsp;modules.
  3898. Currently, Lua has the following standard libraries:
  3899. <ul>
  3900. <li>basic library,</li> which includes the coroutine sub-library;
  3901. <li>package library;</li>
  3902. <li>string manipulation;</li>
  3903. <li>table manipulation;</li>
  3904. <li>mathematical functions (sin, log, etc.);</li>
  3905. <li>input and output;</li>
  3906. <li>operating system facilities;</li>
  3907. <li>debug facilities.</li>
  3908. </ul><p>
  3909. Except for the basic and package libraries,
  3910. each library provides all its functions as fields of a global table
  3911. or as methods of its objects.
  3912. <p>
  3913. To have access to these libraries,
  3914. the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
  3915. which opens all standard libraries.
  3916. Alternatively,
  3917. it can open them individually by calling
  3918. <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
  3919. <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
  3920. <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
  3921. <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
  3922. <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
  3923. <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
  3924. <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
  3925. and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
  3926. These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>
  3927. and should not be called directly:
  3928. you must call them like any other Lua C&nbsp;function,
  3929. e.g., by using <a href="#lua_call"><code>lua_call</code></a>.
  3930. <h2>5.1 - <a name="5.1">Basic Functions</a></h2>
  3931. <p>
  3932. The basic library provides some core functions to Lua.
  3933. If you do not include this library in your application,
  3934. you should check carefully whether you need to provide
  3935. implementations for some of its facilities.
  3936. <p>
  3937. <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
  3938. Issues an error when
  3939. the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
  3940. otherwise, returns all its arguments.
  3941. <code>message</code> is an error message;
  3942. when absent, it defaults to "assertion failed!"
  3943. <p>
  3944. <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage (opt [, arg])</code></a></h3>
  3945. <p>
  3946. This function is a generic interface to the garbage collector.
  3947. It performs different functions according to its first argument, <code>opt</code>:
  3948. <ul>
  3949. <li><b>"stop":</b>
  3950. stops the garbage collector.
  3951. </li>
  3952. <li><b>"restart":</b>
  3953. restarts the garbage collector.
  3954. </li>
  3955. <li><b>"collect":</b>
  3956. performs a full garbage-collection cycle.
  3957. </li>
  3958. <li><b>"count":</b>
  3959. returns the total memory in use by Lua (in Kbytes).
  3960. </li>
  3961. <li><b>"step":</b>
  3962. performs a garbage-collection step.
  3963. The step "size" is controlled by <code>arg</code>
  3964. (larger values mean more steps) in a non-specified way.
  3965. If you want to control the step size
  3966. you must experimentally tune the value of <code>arg</code>.
  3967. Returns <b>true</b> if the step finished a collection cycle.
  3968. </li>
  3969. <li><b>"setpause":</b>
  3970. sets <code>arg</code> as the new value for the <em>pause</em> of
  3971. the collector (see <a href="#2.10">&sect;2.10</a>).
  3972. Returns the previous value for <em>pause</em>.
  3973. </li>
  3974. <li><b>"setstepmul":</b>
  3975. sets <code>arg</code> as the new value for the <em>step multiplier</em> of
  3976. the collector (see <a href="#2.10">&sect;2.10</a>).
  3977. Returns the previous value for <em>step</em>.
  3978. </li>
  3979. </ul>
  3980. <p>
  3981. <hr><h3><a name="pdf-dofile"><code>dofile (filename)</code></a></h3>
  3982. Opens the named file and executes its contents as a Lua chunk.
  3983. When called without arguments,
  3984. <code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
  3985. Returns all values returned by the chunk.
  3986. In case of errors, <code>dofile</code> propagates the error
  3987. to its caller (that is, <code>dofile</code> does not run in protected mode).
  3988. <p>
  3989. <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
  3990. Terminates the last protected function called
  3991. and returns <code>message</code> as the error message.
  3992. Function <code>error</code> never returns.
  3993. <p>
  3994. Usually, <code>error</code> adds some information about the error position
  3995. at the beginning of the message.
  3996. The <code>level</code> argument specifies how to get the error position.
  3997. With level&nbsp;1 (the default), the error position is where the
  3998. <code>error</code> function was called.
  3999. Level&nbsp;2 points the error to where the function
  4000. that called <code>error</code> was called; and so on.
  4001. Passing a level&nbsp;0 avoids the addition of error position information
  4002. to the message.
  4003. <p>
  4004. <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
  4005. A global variable (not a function) that
  4006. holds the global environment (that is, <code>_G._G = _G</code>).
  4007. Lua itself does not use this variable;
  4008. changing its value does not affect any environment,
  4009. nor vice-versa.
  4010. (Use <a href="#pdf-setfenv"><code>setfenv</code></a> to change environments.)
  4011. <p>
  4012. <hr><h3><a name="pdf-getfenv"><code>getfenv ([f])</code></a></h3>
  4013. Returns the current environment in use by the function.
  4014. <code>f</code> can be a Lua function or a number
  4015. that specifies the function at that stack level:
  4016. Level&nbsp;1 is the function calling <code>getfenv</code>.
  4017. If the given function is not a Lua function,
  4018. or if <code>f</code> is 0,
  4019. <code>getfenv</code> returns the global environment.
  4020. The default for <code>f</code> is 1.
  4021. <p>
  4022. <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
  4023. <p>
  4024. If <code>object</code> does not have a metatable, returns <b>nil</b>.
  4025. Otherwise,
  4026. if the object's metatable has a <code>"__metatable"</code> field,
  4027. returns the associated value.
  4028. Otherwise, returns the metatable of the given object.
  4029. <p>
  4030. <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
  4031. <p>
  4032. Returns three values: an iterator function, the table <code>t</code>, and 0,
  4033. so that the construction
  4034. <pre>
  4035. for i,v in ipairs(t) do <em>body</em> end
  4036. </pre><p>
  4037. will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), &middot;&middot;&middot;,
  4038. up to the first integer key absent from the table.
  4039. <p>
  4040. <hr><h3><a name="pdf-load"><code>load (func [, chunkname])</code></a></h3>
  4041. <p>
  4042. Loads a chunk using function <code>func</code> to get its pieces.
  4043. Each call to <code>func</code> must return a string that concatenates
  4044. with previous results.
  4045. A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
  4046. <p>
  4047. If there are no errors,
  4048. returns the compiled chunk as a function;
  4049. otherwise, returns <b>nil</b> plus the error message.
  4050. The environment of the returned function is the global environment.
  4051. <p>
  4052. <code>chunkname</code> is used as the chunk name for error messages
  4053. and debug information.
  4054. When absent,
  4055. it defaults to "<code>=(load)</code>".
  4056. <p>
  4057. <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename])</code></a></h3>
  4058. <p>
  4059. Similar to <a href="#pdf-load"><code>load</code></a>,
  4060. but gets the chunk from file <code>filename</code>
  4061. or from the standard input,
  4062. if no file name is given.
  4063. <p>
  4064. <hr><h3><a name="pdf-loadstring"><code>loadstring (string [, chunkname])</code></a></h3>
  4065. <p>
  4066. Similar to <a href="#pdf-load"><code>load</code></a>,
  4067. but gets the chunk from the given string.
  4068. <p>
  4069. To load and run a given string, use the idiom
  4070. <pre>
  4071. assert(loadstring(s))()
  4072. </pre>
  4073. <p>
  4074. When absent,
  4075. <code>chunkname</code> defaults to the given string.
  4076. <p>
  4077. <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
  4078. <p>
  4079. Allows a program to traverse all fields of a table.
  4080. Its first argument is a table and its second argument
  4081. is an index in this table.
  4082. <code>next</code> returns the next index of the table
  4083. and its associated value.
  4084. When called with <b>nil</b> as its second argument,
  4085. <code>next</code> returns an initial index
  4086. and its associated value.
  4087. When called with the last index,
  4088. or with <b>nil</b> in an empty table,
  4089. <code>next</code> returns <b>nil</b>.
  4090. If the second argument is absent, then it is interpreted as <b>nil</b>.
  4091. In particular,
  4092. you can use <code>next(t)</code> to check whether a table is empty.
  4093. <p>
  4094. The order in which the indices are enumerated is not specified,
  4095. <em>even for numeric indices</em>.
  4096. (To traverse a table in numeric order,
  4097. use a numerical <b>for</b> or the <a href="#pdf-ipairs"><code>ipairs</code></a> function.)
  4098. <p>
  4099. The behavior of <code>next</code> is <em>undefined</em> if,
  4100. during the traversal,
  4101. you assign any value to a non-existent field in the table.
  4102. You may however modify existing fields.
  4103. In particular, you may clear existing fields.
  4104. <p>
  4105. <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
  4106. <p>
  4107. Returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
  4108. so that the construction
  4109. <pre>
  4110. for k,v in pairs(t) do <em>body</em> end
  4111. </pre><p>
  4112. will iterate over all key&ndash;value pairs of table <code>t</code>.
  4113. <p>
  4114. See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
  4115. the table during its traversal.
  4116. <p>
  4117. <hr><h3><a name="pdf-pcall"><code>pcall (f, arg1, &middot;&middot;&middot;)</code></a></h3>
  4118. <p>
  4119. Calls function <code>f</code> with
  4120. the given arguments in <em>protected mode</em>.
  4121. This means that any error inside&nbsp;<code>f</code> is not propagated;
  4122. instead, <code>pcall</code> catches the error
  4123. and returns a status code.
  4124. Its first result is the status code (a boolean),
  4125. which is true if the call succeeds without errors.
  4126. In such case, <code>pcall</code> also returns all results from the call,
  4127. after this first result.
  4128. In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
  4129. <p>
  4130. <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
  4131. Receives any number of arguments,
  4132. and prints their values to <code>stdout</code>,
  4133. using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert them to strings.
  4134. <code>print</code> is not intended for formatted output,
  4135. but only as a quick way to show a value,
  4136. typically for debugging.
  4137. For formatted output, use <a href="#pdf-string.format"><code>string.format</code></a>.
  4138. <p>
  4139. <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
  4140. Checks whether <code>v1</code> is equal to <code>v2</code>,
  4141. without invoking any metamethod.
  4142. Returns a boolean.
  4143. <p>
  4144. <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
  4145. Gets the real value of <code>table[index]</code>,
  4146. without invoking any metamethod.
  4147. <code>table</code> must be a table;
  4148. <code>index</code> may be any value.
  4149. <p>
  4150. <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
  4151. Sets the real value of <code>table[index]</code> to <code>value</code>,
  4152. without invoking any metamethod.
  4153. <code>table</code> must be a table,
  4154. <code>index</code> any value different from <b>nil</b>,
  4155. and <code>value</code> any Lua value.
  4156. <p>
  4157. This function returns <code>table</code>.
  4158. <p>
  4159. <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
  4160. <p>
  4161. If <code>index</code> is a number,
  4162. returns all arguments after argument number <code>index</code>.
  4163. Otherwise, <code>index</code> must be the string <code>"#"</code>,
  4164. and <code>select</code> returns the total number of extra arguments it received.
  4165. <p>
  4166. <hr><h3><a name="pdf-setfenv"><code>setfenv (f, table)</code></a></h3>
  4167. <p>
  4168. Sets the environment to be used by the given function.
  4169. <code>f</code> can be a Lua function or a number
  4170. that specifies the function at that stack level:
  4171. Level&nbsp;1 is the function calling <code>setfenv</code>.
  4172. <code>setfenv</code> returns the given function.
  4173. <p>
  4174. As a special case, when <code>f</code> is 0 <code>setfenv</code> changes
  4175. the environment of the running thread.
  4176. In this case, <code>setfenv</code> returns no values.
  4177. <p>
  4178. <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
  4179. <p>
  4180. Sets the metatable for the given table.
  4181. (You cannot change the metatable of other types from Lua, only from&nbsp;C.)
  4182. If <code>metatable</code> is <b>nil</b>,
  4183. removes the metatable of the given table.
  4184. If the original metatable has a <code>"__metatable"</code> field,
  4185. raises an error.
  4186. <p>
  4187. This function returns <code>table</code>.
  4188. <p>
  4189. <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
  4190. Tries to convert its argument to a number.
  4191. If the argument is already a number or a string convertible
  4192. to a number, then <code>tonumber</code> returns this number;
  4193. otherwise, it returns <b>nil</b>.
  4194. <p>
  4195. An optional argument specifies the base to interpret the numeral.
  4196. The base may be any integer between 2 and 36, inclusive.
  4197. In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
  4198. represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
  4199. with '<code>Z</code>' representing 35.
  4200. In base 10 (the default), the number can have a decimal part,
  4201. as well as an optional exponent part (see <a href="#2.1">&sect;2.1</a>).
  4202. In other bases, only unsigned integers are accepted.
  4203. <p>
  4204. <hr><h3><a name="pdf-tostring"><code>tostring (e)</code></a></h3>
  4205. Receives an argument of any type and
  4206. converts it to a string in a reasonable format.
  4207. For complete control of how numbers are converted,
  4208. use <a href="#pdf-string.format"><code>string.format</code></a>.
  4209. <p>
  4210. If the metatable of <code>e</code> has a <code>"__tostring"</code> field,
  4211. then <code>tostring</code> calls the corresponding value
  4212. with <code>e</code> as argument,
  4213. and uses the result of the call as its result.
  4214. <p>
  4215. <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
  4216. Returns the type of its only argument, coded as a string.
  4217. The possible results of this function are
  4218. "<code>nil</code>" (a string, not the value <b>nil</b>),
  4219. "<code>number</code>",
  4220. "<code>string</code>",
  4221. "<code>boolean</code>",
  4222. "<code>table</code>",
  4223. "<code>function</code>",
  4224. "<code>thread</code>",
  4225. and "<code>userdata</code>".
  4226. <p>
  4227. <hr><h3><a name="pdf-unpack"><code>unpack (list [, i [, j]])</code></a></h3>
  4228. Returns the elements from the given table.
  4229. This function is equivalent to
  4230. <pre>
  4231. return list[i], list[i+1], &middot;&middot;&middot;, list[j]
  4232. </pre><p>
  4233. except that the above code can be written only for a fixed number
  4234. of elements.
  4235. By default, <code>i</code> is&nbsp;1 and <code>j</code> is the length of the list,
  4236. as defined by the length operator (see <a href="#2.5.5">&sect;2.5.5</a>).
  4237. <p>
  4238. <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
  4239. A global variable (not a function) that
  4240. holds a string containing the current interpreter version.
  4241. The current contents of this variable is "<code>Lua 5.1</code>".
  4242. <p>
  4243. <hr><h3><a name="pdf-xpcall"><code>xpcall (f, err)</code></a></h3>
  4244. <p>
  4245. This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
  4246. except that you can set a new error handler.
  4247. <p>
  4248. <code>xpcall</code> calls function <code>f</code> in protected mode,
  4249. using <code>err</code> as the error handler.
  4250. Any error inside <code>f</code> is not propagated;
  4251. instead, <code>xpcall</code> catches the error,
  4252. calls the <code>err</code> function with the original error object,
  4253. and returns a status code.
  4254. Its first result is the status code (a boolean),
  4255. which is true if the call succeeds without errors.
  4256. In this case, <code>xpcall</code> also returns all results from the call,
  4257. after this first result.
  4258. In case of any error,
  4259. <code>xpcall</code> returns <b>false</b> plus the result from <code>err</code>.
  4260. <h2>5.2 - <a name="5.2">Coroutine Manipulation</a></h2>
  4261. <p>
  4262. The operations related to coroutines comprise a sub-library of
  4263. the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
  4264. See <a href="#2.11">&sect;2.11</a> for a general description of coroutines.
  4265. <p>
  4266. <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
  4267. <p>
  4268. Creates a new coroutine, with body <code>f</code>.
  4269. <code>f</code> must be a Lua function.
  4270. Returns this new coroutine,
  4271. an object with type <code>"thread"</code>.
  4272. <p>
  4273. <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
  4274. <p>
  4275. Starts or continues the execution of coroutine <code>co</code>.
  4276. The first time you resume a coroutine,
  4277. it starts running its body.
  4278. The values <code>val1</code>, &middot;&middot;&middot; are passed
  4279. as the arguments to the body function.
  4280. If the coroutine has yielded,
  4281. <code>resume</code> restarts it;
  4282. the values <code>val1</code>, &middot;&middot;&middot; are passed
  4283. as the results from the yield.
  4284. <p>
  4285. If the coroutine runs without any errors,
  4286. <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
  4287. (if the coroutine yields) or any values returned by the body function
  4288. (if the coroutine terminates).
  4289. If there is any error,
  4290. <code>resume</code> returns <b>false</b> plus the error message.
  4291. <p>
  4292. <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
  4293. <p>
  4294. Returns the running coroutine,
  4295. or <b>nil</b> when called by the main thread.
  4296. <p>
  4297. <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
  4298. <p>
  4299. Returns the status of coroutine <code>co</code>, as a string:
  4300. <code>"running"</code>,
  4301. if the coroutine is running (that is, it called <code>status</code>);
  4302. <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
  4303. or if it has not started running yet;
  4304. <code>"normal"</code> if the coroutine is active but not running
  4305. (that is, it has resumed another coroutine);
  4306. and <code>"dead"</code> if the coroutine has finished its body function,
  4307. or if it has stopped with an error.
  4308. <p>
  4309. <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
  4310. <p>
  4311. Creates a new coroutine, with body <code>f</code>.
  4312. <code>f</code> must be a Lua function.
  4313. Returns a function that resumes the coroutine each time it is called.
  4314. Any arguments passed to the function behave as the
  4315. extra arguments to <code>resume</code>.
  4316. Returns the same values returned by <code>resume</code>,
  4317. except the first boolean.
  4318. In case of error, propagates the error.
  4319. <p>
  4320. <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
  4321. <p>
  4322. Suspends the execution of the calling coroutine.
  4323. The coroutine cannot be running a C&nbsp;function,
  4324. a metamethod, or an iterator.
  4325. Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
  4326. <h2>5.3 - <a name="5.3">Modules</a></h2>
  4327. <p>
  4328. The package library provides basic
  4329. facilities for loading and building modules in Lua.
  4330. It exports two of its functions directly in the global environment:
  4331. <a href="#pdf-require"><code>require</code></a> and <a href="#pdf-module"><code>module</code></a>.
  4332. Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
  4333. <p>
  4334. <hr><h3><a name="pdf-module"><code>module (name [, &middot;&middot;&middot;])</code></a></h3>
  4335. <p>
  4336. Creates a module.
  4337. If there is a table in <code>package.loaded[name]</code>,
  4338. this table is the module.
  4339. Otherwise, if there is a global table <code>t</code> with the given name,
  4340. this table is the module.
  4341. Otherwise creates a new table <code>t</code> and
  4342. sets it as the value of the global <code>name</code> and
  4343. the value of <code>package.loaded[name]</code>.
  4344. This function also initializes <code>t._NAME</code> with the given name,
  4345. <code>t._M</code> with the module (<code>t</code> itself),
  4346. and <code>t._PACKAGE</code> with the package name
  4347. (the full module name minus last component; see below).
  4348. Finally, <code>module</code> sets <code>t</code> as the new environment
  4349. of the current function and the new value of <code>package.loaded[name]</code>,
  4350. so that <a href="#pdf-require"><code>require</code></a> returns <code>t</code>.
  4351. <p>
  4352. If <code>name</code> is a compound name
  4353. (that is, one with components separated by dots),
  4354. <code>module</code> creates (or reuses, if they already exist)
  4355. tables for each component.
  4356. For instance, if <code>name</code> is <code>a.b.c</code>,
  4357. then <code>module</code> stores the module table in field <code>c</code> of
  4358. field <code>b</code> of global <code>a</code>.
  4359. <p>
  4360. This function can receive optional <em>options</em> after
  4361. the module name,
  4362. where each option is a function to be applied over the module.
  4363. <p>
  4364. <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
  4365. <p>
  4366. Loads the given module.
  4367. The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
  4368. to determine whether <code>modname</code> is already loaded.
  4369. If it is, then <code>require</code> returns the value stored
  4370. at <code>package.loaded[modname]</code>.
  4371. Otherwise, it tries to find a <em>loader</em> for the module.
  4372. <p>
  4373. To find a loader,
  4374. <code>require</code> is guided by the <a href="#pdf-package.loaders"><code>package.loaders</code></a> array.
  4375. By changing this array,
  4376. we can change how <code>require</code> looks for a module.
  4377. The following explanation is based on the default configuration
  4378. for <a href="#pdf-package.loaders"><code>package.loaders</code></a>.
  4379. <p>
  4380. First <code>require</code> queries <code>package.preload[modname]</code>.
  4381. If it has a value,
  4382. this value (which should be a function) is the loader.
  4383. Otherwise <code>require</code> searches for a Lua loader using the
  4384. path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
  4385. If that also fails, it searches for a C&nbsp;loader using the
  4386. path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
  4387. If that also fails,
  4388. it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.loaders"><code>package.loaders</code></a>).
  4389. <p>
  4390. Once a loader is found,
  4391. <code>require</code> calls the loader with a single argument, <code>modname</code>.
  4392. If the loader returns any value,
  4393. <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
  4394. If the loader returns no value and
  4395. has not assigned any value to <code>package.loaded[modname]</code>,
  4396. then <code>require</code> assigns <b>true</b> to this entry.
  4397. In any case, <code>require</code> returns the
  4398. final value of <code>package.loaded[modname]</code>.
  4399. <p>
  4400. If there is any error loading or running the module,
  4401. or if it cannot find any loader for the module,
  4402. then <code>require</code> signals an error.
  4403. <p>
  4404. <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
  4405. <p>
  4406. The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
  4407. <p>
  4408. Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
  4409. it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
  4410. using the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
  4411. or a default path defined in <code>luaconf.h</code>.
  4412. <p>
  4413. <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
  4414. <p>
  4415. A table used by <a href="#pdf-require"><code>require</code></a> to control which
  4416. modules are already loaded.
  4417. When you require a module <code>modname</code> and
  4418. <code>package.loaded[modname]</code> is not false,
  4419. <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
  4420. <p>
  4421. <hr><h3><a name="pdf-package.loaders"><code>package.loaders</code></a></h3>
  4422. <p>
  4423. A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
  4424. <p>
  4425. Each entry in this table is a <em>searcher function</em>.
  4426. When looking for a module,
  4427. <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
  4428. with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
  4429. sole parameter.
  4430. The function can return another function (the module <em>loader</em>)
  4431. or a string explaining why it did not find that module
  4432. (or <b>nil</b> if it has nothing to say).
  4433. Lua initializes this table with four functions.
  4434. <p>
  4435. The first searcher simply looks for a loader in the
  4436. <a href="#pdf-package.preload"><code>package.preload</code></a> table.
  4437. <p>
  4438. The second searcher looks for a loader as a Lua library,
  4439. using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
  4440. A path is a sequence of <em>templates</em> separated by semicolons.
  4441. For each template,
  4442. the searcher will change each interrogation
  4443. mark in the template by <code>filename</code>,
  4444. which is the module name with each dot replaced by a
  4445. "directory separator" (such as "<code>/</code>" in Unix);
  4446. then it will try to open the resulting file name.
  4447. So, for instance, if the Lua path is the string
  4448. <pre>
  4449. "./?.lua;./?.lc;/usr/local/?/init.lua"
  4450. </pre><p>
  4451. the search for a Lua file for module <code>foo</code>
  4452. will try to open the files
  4453. <code>./foo.lua</code>, <code>./foo.lc</code>, and
  4454. <code>/usr/local/foo/init.lua</code>, in that order.
  4455. <p>
  4456. The third searcher looks for a loader as a C&nbsp;library,
  4457. using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
  4458. For instance,
  4459. if the C&nbsp;path is the string
  4460. <pre>
  4461. "./?.so;./?.dll;/usr/local/?/init.so"
  4462. </pre><p>
  4463. the searcher for module <code>foo</code>
  4464. will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
  4465. and <code>/usr/local/foo/init.so</code>, in that order.
  4466. Once it finds a C&nbsp;library,
  4467. this searcher first uses a dynamic link facility to link the
  4468. application with the library.
  4469. Then it tries to find a C&nbsp;function inside the library to
  4470. be used as the loader.
  4471. The name of this C&nbsp;function is the string "<code>luaopen_</code>"
  4472. concatenated with a copy of the module name where each dot
  4473. is replaced by an underscore.
  4474. Moreover, if the module name has a hyphen,
  4475. its prefix up to (and including) the first hyphen is removed.
  4476. For instance, if the module name is <code>a.v1-b.c</code>,
  4477. the function name will be <code>luaopen_b_c</code>.
  4478. <p>
  4479. The fourth searcher tries an <em>all-in-one loader</em>.
  4480. It searches the C&nbsp;path for a library for
  4481. the root name of the given module.
  4482. For instance, when requiring <code>a.b.c</code>,
  4483. it will search for a C&nbsp;library for <code>a</code>.
  4484. If found, it looks into it for an open function for
  4485. the submodule;
  4486. in our example, that would be <code>luaopen_a_b_c</code>.
  4487. With this facility, a package can pack several C&nbsp;submodules
  4488. into one single library,
  4489. with each submodule keeping its original open function.
  4490. <p>
  4491. <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
  4492. <p>
  4493. Dynamically links the host program with the C&nbsp;library <code>libname</code>.
  4494. Inside this library, looks for a function <code>funcname</code>
  4495. and returns this function as a C&nbsp;function.
  4496. (So, <code>funcname</code> must follow the protocol (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>)).
  4497. <p>
  4498. This is a low-level function.
  4499. It completely bypasses the package and module system.
  4500. Unlike <a href="#pdf-require"><code>require</code></a>,
  4501. it does not perform any path searching and
  4502. does not automatically adds extensions.
  4503. <code>libname</code> must be the complete file name of the C&nbsp;library,
  4504. including if necessary a path and extension.
  4505. <code>funcname</code> must be the exact name exported by the C&nbsp;library
  4506. (which may depend on the C&nbsp;compiler and linker used).
  4507. <p>
  4508. This function is not supported by ANSI C.
  4509. As such, it is only available on some platforms
  4510. (Windows, Linux, Mac OS X, Solaris, BSD,
  4511. plus other Unix systems that support the <code>dlfcn</code> standard).
  4512. <p>
  4513. <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
  4514. <p>
  4515. The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
  4516. <p>
  4517. At start-up, Lua initializes this variable with
  4518. the value of the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
  4519. with a default path defined in <code>luaconf.h</code>,
  4520. if the environment variable is not defined.
  4521. Any "<code>;;</code>" in the value of the environment variable
  4522. is replaced by the default path.
  4523. <p>
  4524. <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
  4525. <p>
  4526. A table to store loaders for specific modules
  4527. (see <a href="#pdf-require"><code>require</code></a>).
  4528. <p>
  4529. <hr><h3><a name="pdf-package.seeall"><code>package.seeall (module)</code></a></h3>
  4530. <p>
  4531. Sets a metatable for <code>module</code> with
  4532. its <code>__index</code> field referring to the global environment,
  4533. so that this module inherits values
  4534. from the global environment.
  4535. To be used as an option to function <a href="#pdf-module"><code>module</code></a>.
  4536. <h2>5.4 - <a name="5.4">String Manipulation</a></h2>
  4537. <p>
  4538. This library provides generic functions for string manipulation,
  4539. such as finding and extracting substrings, and pattern matching.
  4540. When indexing a string in Lua, the first character is at position&nbsp;1
  4541. (not at&nbsp;0, as in C).
  4542. Indices are allowed to be negative and are interpreted as indexing backwards,
  4543. from the end of the string.
  4544. Thus, the last character is at position -1, and so on.
  4545. <p>
  4546. The string library provides all its functions inside the table
  4547. <a name="pdf-string"><code>string</code></a>.
  4548. It also sets a metatable for strings
  4549. where the <code>__index</code> field points to the <code>string</code> table.
  4550. Therefore, you can use the string functions in object-oriented style.
  4551. For instance, <code>string.byte(s, i)</code>
  4552. can be written as <code>s:byte(i)</code>.
  4553. <p>
  4554. The string library assumes one-byte character encodings.
  4555. <p>
  4556. <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
  4557. Returns the internal numerical codes of the characters <code>s[i]</code>,
  4558. <code>s[i+1]</code>, &middot;&middot;&middot;, <code>s[j]</code>.
  4559. The default value for <code>i</code> is&nbsp;1;
  4560. the default value for <code>j</code> is&nbsp;<code>i</code>.
  4561. <p>
  4562. Note that numerical codes are not necessarily portable across platforms.
  4563. <p>
  4564. <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
  4565. Receives zero or more integers.
  4566. Returns a string with length equal to the number of arguments,
  4567. in which each character has the internal numerical code equal
  4568. to its corresponding argument.
  4569. <p>
  4570. Note that numerical codes are not necessarily portable across platforms.
  4571. <p>
  4572. <hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
  4573. <p>
  4574. Returns a string containing a binary representation of the given function,
  4575. so that a later <a href="#pdf-loadstring"><code>loadstring</code></a> on this string returns
  4576. a copy of the function.
  4577. <code>function</code> must be a Lua function without upvalues.
  4578. <p>
  4579. <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
  4580. Looks for the first match of
  4581. <code>pattern</code> in the string <code>s</code>.
  4582. If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
  4583. where this occurrence starts and ends;
  4584. otherwise, it returns <b>nil</b>.
  4585. A third, optional numerical argument <code>init</code> specifies
  4586. where to start the search;
  4587. its default value is&nbsp;1 and can be negative.
  4588. A value of <b>true</b> as a fourth, optional argument <code>plain</code>
  4589. turns off the pattern matching facilities,
  4590. so the function does a plain "find substring" operation,
  4591. with no characters in <code>pattern</code> being considered "magic".
  4592. Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
  4593. <p>
  4594. If the pattern has captures,
  4595. then in a successful match
  4596. the captured values are also returned,
  4597. after the two indices.
  4598. <p>
  4599. <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
  4600. Returns a formatted version of its variable number of arguments
  4601. following the description given in its first argument (which must be a string).
  4602. The format string follows the same rules as the <code>printf</code> family of
  4603. standard C&nbsp;functions.
  4604. The only differences are that the options/modifiers
  4605. <code>*</code>, <code>l</code>, <code>L</code>, <code>n</code>, <code>p</code>,
  4606. and <code>h</code> are not supported
  4607. and that there is an extra option, <code>q</code>.
  4608. The <code>q</code> option formats a string in a form suitable to be safely read
  4609. back by the Lua interpreter:
  4610. the string is written between double quotes,
  4611. and all double quotes, newlines, embedded zeros,
  4612. and backslashes in the string
  4613. are correctly escaped when written.
  4614. For instance, the call
  4615. <pre>
  4616. string.format('%q', 'a string with "quotes" and \n new line')
  4617. </pre><p>
  4618. will produce the string:
  4619. <pre>
  4620. "a string with \"quotes\" and \
  4621. new line"
  4622. </pre>
  4623. <p>
  4624. The options <code>c</code>, <code>d</code>, <code>E</code>, <code>e</code>, <code>f</code>,
  4625. <code>g</code>, <code>G</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> all
  4626. expect a number as argument,
  4627. whereas <code>q</code> and <code>s</code> expect a string.
  4628. <p>
  4629. This function does not accept string values
  4630. containing embedded zeros,
  4631. except as arguments to the <code>q</code> option.
  4632. <p>
  4633. <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
  4634. Returns an iterator function that,
  4635. each time it is called,
  4636. returns the next captures from <code>pattern</code> over string <code>s</code>.
  4637. If <code>pattern</code> specifies no captures,
  4638. then the whole match is produced in each call.
  4639. <p>
  4640. As an example, the following loop
  4641. <pre>
  4642. s = "hello world from Lua"
  4643. for w in string.gmatch(s, "%a+") do
  4644. print(w)
  4645. end
  4646. </pre><p>
  4647. will iterate over all the words from string <code>s</code>,
  4648. printing one per line.
  4649. The next example collects all pairs <code>key=value</code> from the
  4650. given string into a table:
  4651. <pre>
  4652. t = {}
  4653. s = "from=world, to=Lua"
  4654. for k, v in string.gmatch(s, "(%w+)=(%w+)") do
  4655. t[k] = v
  4656. end
  4657. </pre>
  4658. <p>
  4659. For this function, a '<code>^</code>' at the start of a pattern does not
  4660. work as an anchor, as this would prevent the iteration.
  4661. <p>
  4662. <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
  4663. Returns a copy of <code>s</code>
  4664. in which all (or the first <code>n</code>, if given)
  4665. occurrences of the <code>pattern</code> have been
  4666. replaced by a replacement string specified by <code>repl</code>,
  4667. which can be a string, a table, or a function.
  4668. <code>gsub</code> also returns, as its second value,
  4669. the total number of matches that occurred.
  4670. <p>
  4671. If <code>repl</code> is a string, then its value is used for replacement.
  4672. The character&nbsp;<code>%</code> works as an escape character:
  4673. any sequence in <code>repl</code> of the form <code>%<em>n</em></code>,
  4674. with <em>n</em> between 1 and 9,
  4675. stands for the value of the <em>n</em>-th captured substring (see below).
  4676. The sequence <code>%0</code> stands for the whole match.
  4677. The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
  4678. <p>
  4679. If <code>repl</code> is a table, then the table is queried for every match,
  4680. using the first capture as the key;
  4681. if the pattern specifies no captures,
  4682. then the whole match is used as the key.
  4683. <p>
  4684. If <code>repl</code> is a function, then this function is called every time a
  4685. match occurs, with all captured substrings passed as arguments,
  4686. in order;
  4687. if the pattern specifies no captures,
  4688. then the whole match is passed as a sole argument.
  4689. <p>
  4690. If the value returned by the table query or by the function call
  4691. is a string or a number,
  4692. then it is used as the replacement string;
  4693. otherwise, if it is <b>false</b> or <b>nil</b>,
  4694. then there is no replacement
  4695. (that is, the original match is kept in the string).
  4696. <p>
  4697. Here are some examples:
  4698. <pre>
  4699. x = string.gsub("hello world", "(%w+)", "%1 %1")
  4700. --&gt; x="hello hello world world"
  4701. x = string.gsub("hello world", "%w+", "%0 %0", 1)
  4702. --&gt; x="hello hello world"
  4703. x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
  4704. --&gt; x="world hello Lua from"
  4705. x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
  4706. --&gt; x="home = /home/roberto, user = roberto"
  4707. x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
  4708. return loadstring(s)()
  4709. end)
  4710. --&gt; x="4+5 = 9"
  4711. local t = {name="lua", version="5.1"}
  4712. x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
  4713. --&gt; x="lua-5.1.tar.gz"
  4714. </pre>
  4715. <p>
  4716. <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
  4717. Receives a string and returns its length.
  4718. The empty string <code>""</code> has length 0.
  4719. Embedded zeros are counted,
  4720. so <code>"a\000bc\000"</code> has length 5.
  4721. <p>
  4722. <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
  4723. Receives a string and returns a copy of this string with all
  4724. uppercase letters changed to lowercase.
  4725. All other characters are left unchanged.
  4726. The definition of what an uppercase letter is depends on the current locale.
  4727. <p>
  4728. <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
  4729. Looks for the first <em>match</em> of
  4730. <code>pattern</code> in the string <code>s</code>.
  4731. If it finds one, then <code>match</code> returns
  4732. the captures from the pattern;
  4733. otherwise it returns <b>nil</b>.
  4734. If <code>pattern</code> specifies no captures,
  4735. then the whole match is returned.
  4736. A third, optional numerical argument <code>init</code> specifies
  4737. where to start the search;
  4738. its default value is&nbsp;1 and can be negative.
  4739. <p>
  4740. <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n)</code></a></h3>
  4741. Returns a string that is the concatenation of <code>n</code> copies of
  4742. the string <code>s</code>.
  4743. <p>
  4744. <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
  4745. Returns a string that is the string <code>s</code> reversed.
  4746. <p>
  4747. <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
  4748. Returns the substring of <code>s</code> that
  4749. starts at <code>i</code> and continues until <code>j</code>;
  4750. <code>i</code> and <code>j</code> can be negative.
  4751. If <code>j</code> is absent, then it is assumed to be equal to -1
  4752. (which is the same as the string length).
  4753. In particular,
  4754. the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
  4755. with length <code>j</code>,
  4756. and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
  4757. with length <code>i</code>.
  4758. <p>
  4759. <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
  4760. Receives a string and returns a copy of this string with all
  4761. lowercase letters changed to uppercase.
  4762. All other characters are left unchanged.
  4763. The definition of what a lowercase letter is depends on the current locale.
  4764. <h3>5.4.1 - <a name="5.4.1">Patterns</a></h3>
  4765. <h4>Character Class:</h4><p>
  4766. A <em>character class</em> is used to represent a set of characters.
  4767. The following combinations are allowed in describing a character class:
  4768. <ul>
  4769. <li><b><em>x</em>:</b>
  4770. (where <em>x</em> is not one of the <em>magic characters</em>
  4771. <code>^$()%.[]*+-?</code>)
  4772. represents the character <em>x</em> itself.
  4773. </li>
  4774. <li><b><code>.</code>:</b> (a dot) represents all characters.</li>
  4775. <li><b><code>%a</code>:</b> represents all letters.</li>
  4776. <li><b><code>%c</code>:</b> represents all control characters.</li>
  4777. <li><b><code>%d</code>:</b> represents all digits.</li>
  4778. <li><b><code>%l</code>:</b> represents all lowercase letters.</li>
  4779. <li><b><code>%p</code>:</b> represents all punctuation characters.</li>
  4780. <li><b><code>%s</code>:</b> represents all space characters.</li>
  4781. <li><b><code>%u</code>:</b> represents all uppercase letters.</li>
  4782. <li><b><code>%w</code>:</b> represents all alphanumeric characters.</li>
  4783. <li><b><code>%x</code>:</b> represents all hexadecimal digits.</li>
  4784. <li><b><code>%z</code>:</b> represents the character with representation 0.</li>
  4785. <li><b><code>%<em>x</em></code>:</b> (where <em>x</em> is any non-alphanumeric character)
  4786. represents the character <em>x</em>.
  4787. This is the standard way to escape the magic characters.
  4788. Any punctuation character (even the non magic)
  4789. can be preceded by a '<code>%</code>'
  4790. when used to represent itself in a pattern.
  4791. </li>
  4792. <li><b><code>[<em>set</em>]</code>:</b>
  4793. represents the class which is the union of all
  4794. characters in <em>set</em>.
  4795. A range of characters can be specified by
  4796. separating the end characters of the range with a '<code>-</code>'.
  4797. All classes <code>%</code><em>x</em> described above can also be used as
  4798. components in <em>set</em>.
  4799. All other characters in <em>set</em> represent themselves.
  4800. For example, <code>[%w_]</code> (or <code>[_%w]</code>)
  4801. represents all alphanumeric characters plus the underscore,
  4802. <code>[0-7]</code> represents the octal digits,
  4803. and <code>[0-7%l%-]</code> represents the octal digits plus
  4804. the lowercase letters plus the '<code>-</code>' character.
  4805. <p>
  4806. The interaction between ranges and classes is not defined.
  4807. Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
  4808. have no meaning.
  4809. </li>
  4810. <li><b><code>[^<em>set</em>]</code>:</b>
  4811. represents the complement of <em>set</em>,
  4812. where <em>set</em> is interpreted as above.
  4813. </li>
  4814. </ul><p>
  4815. For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
  4816. the corresponding uppercase letter represents the complement of the class.
  4817. For instance, <code>%S</code> represents all non-space characters.
  4818. <p>
  4819. The definitions of letter, space, and other character groups
  4820. depend on the current locale.
  4821. In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
  4822. <h4>Pattern Item:</h4><p>
  4823. A <em>pattern item</em> can be
  4824. <ul>
  4825. <li>
  4826. a single character class,
  4827. which matches any single character in the class;
  4828. </li>
  4829. <li>
  4830. a single character class followed by '<code>*</code>',
  4831. which matches 0 or more repetitions of characters in the class.
  4832. These repetition items will always match the longest possible sequence;
  4833. </li>
  4834. <li>
  4835. a single character class followed by '<code>+</code>',
  4836. which matches 1 or more repetitions of characters in the class.
  4837. These repetition items will always match the longest possible sequence;
  4838. </li>
  4839. <li>
  4840. a single character class followed by '<code>-</code>',
  4841. which also matches 0 or more repetitions of characters in the class.
  4842. Unlike '<code>*</code>',
  4843. these repetition items will always match the <em>shortest</em> possible sequence;
  4844. </li>
  4845. <li>
  4846. a single character class followed by '<code>?</code>',
  4847. which matches 0 or 1 occurrence of a character in the class;
  4848. </li>
  4849. <li>
  4850. <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
  4851. such item matches a substring equal to the <em>n</em>-th captured string
  4852. (see below);
  4853. </li>
  4854. <li>
  4855. <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
  4856. such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
  4857. and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
  4858. This means that, if one reads the string from left to right,
  4859. counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
  4860. the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
  4861. For instance, the item <code>%b()</code> matches expressions with
  4862. balanced parentheses.
  4863. </li>
  4864. </ul>
  4865. <h4>Pattern:</h4><p>
  4866. A <em>pattern</em> is a sequence of pattern items.
  4867. A '<code>^</code>' at the beginning of a pattern anchors the match at the
  4868. beginning of the subject string.
  4869. A '<code>$</code>' at the end of a pattern anchors the match at the
  4870. end of the subject string.
  4871. At other positions,
  4872. '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
  4873. <h4>Captures:</h4><p>
  4874. A pattern can contain sub-patterns enclosed in parentheses;
  4875. they describe <em>captures</em>.
  4876. When a match succeeds, the substrings of the subject string
  4877. that match captures are stored (<em>captured</em>) for future use.
  4878. Captures are numbered according to their left parentheses.
  4879. For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
  4880. the part of the string matching <code>"a*(.)%w(%s*)"</code> is
  4881. stored as the first capture (and therefore has number&nbsp;1);
  4882. the character matching "<code>.</code>" is captured with number&nbsp;2,
  4883. and the part matching "<code>%s*</code>" has number&nbsp;3.
  4884. <p>
  4885. As a special case, the empty capture <code>()</code> captures
  4886. the current string position (a number).
  4887. For instance, if we apply the pattern <code>"()aa()"</code> on the
  4888. string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
  4889. <p>
  4890. A pattern cannot contain embedded zeros. Use <code>%z</code> instead.
  4891. <h2>5.5 - <a name="5.5">Table Manipulation</a></h2><p>
  4892. This library provides generic functions for table manipulation.
  4893. It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
  4894. <p>
  4895. Most functions in the table library assume that the table
  4896. represents an array or a list.
  4897. For these functions, when we talk about the "length" of a table
  4898. we mean the result of the length operator.
  4899. <p>
  4900. <hr><h3><a name="pdf-table.concat"><code>table.concat (table [, sep [, i [, j]]])</code></a></h3>
  4901. Given an array where all elements are strings or numbers,
  4902. returns <code>table[i]..sep..table[i+1] &middot;&middot;&middot; sep..table[j]</code>.
  4903. The default value for <code>sep</code> is the empty string,
  4904. the default for <code>i</code> is 1,
  4905. and the default for <code>j</code> is the length of the table.
  4906. If <code>i</code> is greater than <code>j</code>, returns the empty string.
  4907. <p>
  4908. <hr><h3><a name="pdf-table.insert"><code>table.insert (table, [pos,] value)</code></a></h3>
  4909. <p>
  4910. Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>,
  4911. shifting up other elements to open space, if necessary.
  4912. The default value for <code>pos</code> is <code>n+1</code>,
  4913. where <code>n</code> is the length of the table (see <a href="#2.5.5">&sect;2.5.5</a>),
  4914. so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
  4915. of table <code>t</code>.
  4916. <p>
  4917. <hr><h3><a name="pdf-table.maxn"><code>table.maxn (table)</code></a></h3>
  4918. <p>
  4919. Returns the largest positive numerical index of the given table,
  4920. or zero if the table has no positive numerical indices.
  4921. (To do its job this function does a linear traversal of
  4922. the whole table.)
  4923. <p>
  4924. <hr><h3><a name="pdf-table.remove"><code>table.remove (table [, pos])</code></a></h3>
  4925. <p>
  4926. Removes from <code>table</code> the element at position <code>pos</code>,
  4927. shifting down other elements to close the space, if necessary.
  4928. Returns the value of the removed element.
  4929. The default value for <code>pos</code> is <code>n</code>,
  4930. where <code>n</code> is the length of the table,
  4931. so that a call <code>table.remove(t)</code> removes the last element
  4932. of table <code>t</code>.
  4933. <p>
  4934. <hr><h3><a name="pdf-table.sort"><code>table.sort (table [, comp])</code></a></h3>
  4935. Sorts table elements in a given order, <em>in-place</em>,
  4936. from <code>table[1]</code> to <code>table[n]</code>,
  4937. where <code>n</code> is the length of the table.
  4938. If <code>comp</code> is given,
  4939. then it must be a function that receives two table elements,
  4940. and returns true
  4941. when the first is less than the second
  4942. (so that <code>not comp(a[i+1],a[i])</code> will be true after the sort).
  4943. If <code>comp</code> is not given,
  4944. then the standard Lua operator <code>&lt;</code> is used instead.
  4945. <p>
  4946. The sort algorithm is not stable;
  4947. that is, elements considered equal by the given order
  4948. may have their relative positions changed by the sort.
  4949. <h2>5.6 - <a name="5.6">Mathematical Functions</a></h2>
  4950. <p>
  4951. This library is an interface to the standard C&nbsp;math library.
  4952. It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
  4953. <p>
  4954. <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
  4955. <p>
  4956. Returns the absolute value of <code>x</code>.
  4957. <p>
  4958. <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
  4959. <p>
  4960. Returns the arc cosine of <code>x</code> (in radians).
  4961. <p>
  4962. <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
  4963. <p>
  4964. Returns the arc sine of <code>x</code> (in radians).
  4965. <p>
  4966. <hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
  4967. <p>
  4968. Returns the arc tangent of <code>x</code> (in radians).
  4969. <p>
  4970. <hr><h3><a name="pdf-math.atan2"><code>math.atan2 (y, x)</code></a></h3>
  4971. <p>
  4972. Returns the arc tangent of <code>y/x</code> (in radians),
  4973. but uses the signs of both parameters to find the
  4974. quadrant of the result.
  4975. (It also handles correctly the case of <code>x</code> being zero.)
  4976. <p>
  4977. <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
  4978. <p>
  4979. Returns the smallest integer larger than or equal to <code>x</code>.
  4980. <p>
  4981. <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
  4982. <p>
  4983. Returns the cosine of <code>x</code> (assumed to be in radians).
  4984. <p>
  4985. <hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
  4986. <p>
  4987. Returns the hyperbolic cosine of <code>x</code>.
  4988. <p>
  4989. <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
  4990. <p>
  4991. Returns the angle <code>x</code> (given in radians) in degrees.
  4992. <p>
  4993. <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
  4994. <p>
  4995. Returns the value <em>e<sup>x</sup></em>.
  4996. <p>
  4997. <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
  4998. <p>
  4999. Returns the largest integer smaller than or equal to <code>x</code>.
  5000. <p>
  5001. <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
  5002. <p>
  5003. Returns the remainder of the division of <code>x</code> by <code>y</code>
  5004. that rounds the quotient towards zero.
  5005. <p>
  5006. <hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
  5007. <p>
  5008. Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
  5009. <code>e</code> is an integer and the absolute value of <code>m</code> is
  5010. in the range <em>[0.5, 1)</em>
  5011. (or zero when <code>x</code> is zero).
  5012. <p>
  5013. <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
  5014. <p>
  5015. The value <code>HUGE_VAL</code>,
  5016. a value larger than or equal to any other numerical value.
  5017. <p>
  5018. <hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
  5019. <p>
  5020. Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
  5021. <p>
  5022. <hr><h3><a name="pdf-math.log"><code>math.log (x)</code></a></h3>
  5023. <p>
  5024. Returns the natural logarithm of <code>x</code>.
  5025. <p>
  5026. <hr><h3><a name="pdf-math.log10"><code>math.log10 (x)</code></a></h3>
  5027. <p>
  5028. Returns the base-10 logarithm of <code>x</code>.
  5029. <p>
  5030. <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
  5031. <p>
  5032. Returns the maximum value among its arguments.
  5033. <p>
  5034. <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
  5035. <p>
  5036. Returns the minimum value among its arguments.
  5037. <p>
  5038. <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
  5039. <p>
  5040. Returns two numbers,
  5041. the integral part of <code>x</code> and the fractional part of <code>x</code>.
  5042. <p>
  5043. <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
  5044. <p>
  5045. The value of <em>pi</em>.
  5046. <p>
  5047. <hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
  5048. <p>
  5049. Returns <em>x<sup>y</sup></em>.
  5050. (You can also use the expression <code>x^y</code> to compute this value.)
  5051. <p>
  5052. <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
  5053. <p>
  5054. Returns the angle <code>x</code> (given in degrees) in radians.
  5055. <p>
  5056. <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
  5057. <p>
  5058. This function is an interface to the simple
  5059. pseudo-random generator function <code>rand</code> provided by ANSI&nbsp;C.
  5060. (No guarantees can be given for its statistical properties.)
  5061. <p>
  5062. When called without arguments,
  5063. returns a uniform pseudo-random real number
  5064. in the range <em>[0,1)</em>.
  5065. When called with an integer number <code>m</code>,
  5066. <code>math.random</code> returns
  5067. a uniform pseudo-random integer in the range <em>[1, m]</em>.
  5068. When called with two integer numbers <code>m</code> and <code>n</code>,
  5069. <code>math.random</code> returns a uniform pseudo-random
  5070. integer in the range <em>[m, n]</em>.
  5071. <p>
  5072. <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
  5073. <p>
  5074. Sets <code>x</code> as the "seed"
  5075. for the pseudo-random generator:
  5076. equal seeds produce equal sequences of numbers.
  5077. <p>
  5078. <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
  5079. <p>
  5080. Returns the sine of <code>x</code> (assumed to be in radians).
  5081. <p>
  5082. <hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
  5083. <p>
  5084. Returns the hyperbolic sine of <code>x</code>.
  5085. <p>
  5086. <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
  5087. <p>
  5088. Returns the square root of <code>x</code>.
  5089. (You can also use the expression <code>x^0.5</code> to compute this value.)
  5090. <p>
  5091. <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
  5092. <p>
  5093. Returns the tangent of <code>x</code> (assumed to be in radians).
  5094. <p>
  5095. <hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
  5096. <p>
  5097. Returns the hyperbolic tangent of <code>x</code>.
  5098. <h2>5.7 - <a name="5.7">Input and Output Facilities</a></h2>
  5099. <p>
  5100. The I/O library provides two different styles for file manipulation.
  5101. The first one uses implicit file descriptors;
  5102. that is, there are operations to set a default input file and a
  5103. default output file,
  5104. and all input/output operations are over these default files.
  5105. The second style uses explicit file descriptors.
  5106. <p>
  5107. When using implicit file descriptors,
  5108. all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
  5109. When using explicit file descriptors,
  5110. the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
  5111. and then all operations are supplied as methods of the file descriptor.
  5112. <p>
  5113. The table <code>io</code> also provides
  5114. three predefined file descriptors with their usual meanings from C:
  5115. <a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>.
  5116. The I/O library never closes these files.
  5117. <p>
  5118. Unless otherwise stated,
  5119. all I/O functions return <b>nil</b> on failure
  5120. (plus an error message as a second result and
  5121. a system-dependent error code as a third result)
  5122. and some value different from <b>nil</b> on success.
  5123. <p>
  5124. <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
  5125. <p>
  5126. Equivalent to <code>file:close()</code>.
  5127. Without a <code>file</code>, closes the default output file.
  5128. <p>
  5129. <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
  5130. <p>
  5131. Equivalent to <code>file:flush</code> over the default output file.
  5132. <p>
  5133. <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
  5134. <p>
  5135. When called with a file name, it opens the named file (in text mode),
  5136. and sets its handle as the default input file.
  5137. When called with a file handle,
  5138. it simply sets this file handle as the default input file.
  5139. When called without parameters,
  5140. it returns the current default input file.
  5141. <p>
  5142. In case of errors this function raises the error,
  5143. instead of returning an error code.
  5144. <p>
  5145. <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename])</code></a></h3>
  5146. <p>
  5147. Opens the given file name in read mode
  5148. and returns an iterator function that,
  5149. each time it is called,
  5150. returns a new line from the file.
  5151. Therefore, the construction
  5152. <pre>
  5153. for line in io.lines(filename) do <em>body</em> end
  5154. </pre><p>
  5155. will iterate over all lines of the file.
  5156. When the iterator function detects the end of file,
  5157. it returns <b>nil</b> (to finish the loop) and automatically closes the file.
  5158. <p>
  5159. The call <code>io.lines()</code> (with no file name) is equivalent
  5160. to <code>io.input():lines()</code>;
  5161. that is, it iterates over the lines of the default input file.
  5162. In this case it does not close the file when the loop ends.
  5163. <p>
  5164. <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
  5165. <p>
  5166. This function opens a file,
  5167. in the mode specified in the string <code>mode</code>.
  5168. It returns a new file handle,
  5169. or, in case of errors, <b>nil</b> plus an error message.
  5170. <p>
  5171. The <code>mode</code> string can be any of the following:
  5172. <ul>
  5173. <li><b>"r":</b> read mode (the default);</li>
  5174. <li><b>"w":</b> write mode;</li>
  5175. <li><b>"a":</b> append mode;</li>
  5176. <li><b>"r+":</b> update mode, all previous data is preserved;</li>
  5177. <li><b>"w+":</b> update mode, all previous data is erased;</li>
  5178. <li><b>"a+":</b> append update mode, previous data is preserved,
  5179. writing is only allowed at the end of file.</li>
  5180. </ul><p>
  5181. The <code>mode</code> string can also have a '<code>b</code>' at the end,
  5182. which is needed in some systems to open the file in binary mode.
  5183. This string is exactly what is used in the
  5184. standard&nbsp;C function <code>fopen</code>.
  5185. <p>
  5186. <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
  5187. <p>
  5188. Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
  5189. <p>
  5190. <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
  5191. <p>
  5192. Starts program <code>prog</code> in a separated process and returns
  5193. a file handle that you can use to read data from this program
  5194. (if <code>mode</code> is <code>"r"</code>, the default)
  5195. or to write data to this program
  5196. (if <code>mode</code> is <code>"w"</code>).
  5197. <p>
  5198. This function is system dependent and is not available
  5199. on all platforms.
  5200. <p>
  5201. <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
  5202. <p>
  5203. Equivalent to <code>io.input():read</code>.
  5204. <p>
  5205. <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
  5206. <p>
  5207. Returns a handle for a temporary file.
  5208. This file is opened in update mode
  5209. and it is automatically removed when the program ends.
  5210. <p>
  5211. <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
  5212. <p>
  5213. Checks whether <code>obj</code> is a valid file handle.
  5214. Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
  5215. <code>"closed file"</code> if <code>obj</code> is a closed file handle,
  5216. or <b>nil</b> if <code>obj</code> is not a file handle.
  5217. <p>
  5218. <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
  5219. <p>
  5220. Equivalent to <code>io.output():write</code>.
  5221. <p>
  5222. <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
  5223. <p>
  5224. Closes <code>file</code>.
  5225. Note that files are automatically closed when
  5226. their handles are garbage collected,
  5227. but that takes an unpredictable amount of time to happen.
  5228. <p>
  5229. <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
  5230. <p>
  5231. Saves any written data to <code>file</code>.
  5232. <p>
  5233. <hr><h3><a name="pdf-file:lines"><code>file:lines ()</code></a></h3>
  5234. <p>
  5235. Returns an iterator function that,
  5236. each time it is called,
  5237. returns a new line from the file.
  5238. Therefore, the construction
  5239. <pre>
  5240. for line in file:lines() do <em>body</em> end
  5241. </pre><p>
  5242. will iterate over all lines of the file.
  5243. (Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
  5244. when the loop ends.)
  5245. <p>
  5246. <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
  5247. <p>
  5248. Reads the file <code>file</code>,
  5249. according to the given formats, which specify what to read.
  5250. For each format,
  5251. the function returns a string (or a number) with the characters read,
  5252. or <b>nil</b> if it cannot read data with the specified format.
  5253. When called without formats,
  5254. it uses a default format that reads the entire next line
  5255. (see below).
  5256. <p>
  5257. The available formats are
  5258. <ul>
  5259. <li><b>"*n":</b>
  5260. reads a number;
  5261. this is the only format that returns a number instead of a string.
  5262. </li>
  5263. <li><b>"*a":</b>
  5264. reads the whole file, starting at the current position.
  5265. On end of file, it returns the empty string.
  5266. </li>
  5267. <li><b>"*l":</b>
  5268. reads the next line (skipping the end of line),
  5269. returning <b>nil</b> on end of file.
  5270. This is the default format.
  5271. </li>
  5272. <li><b><em>number</em>:</b>
  5273. reads a string with up to this number of characters,
  5274. returning <b>nil</b> on end of file.
  5275. If number is zero,
  5276. it reads nothing and returns an empty string,
  5277. or <b>nil</b> on end of file.
  5278. </li>
  5279. </ul>
  5280. <p>
  5281. <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence] [, offset])</code></a></h3>
  5282. <p>
  5283. Sets and gets the file position,
  5284. measured from the beginning of the file,
  5285. to the position given by <code>offset</code> plus a base
  5286. specified by the string <code>whence</code>, as follows:
  5287. <ul>
  5288. <li><b>"set":</b> base is position 0 (beginning of the file);</li>
  5289. <li><b>"cur":</b> base is current position;</li>
  5290. <li><b>"end":</b> base is end of file;</li>
  5291. </ul><p>
  5292. In case of success, function <code>seek</code> returns the final file position,
  5293. measured in bytes from the beginning of the file.
  5294. If this function fails, it returns <b>nil</b>,
  5295. plus a string describing the error.
  5296. <p>
  5297. The default value for <code>whence</code> is <code>"cur"</code>,
  5298. and for <code>offset</code> is 0.
  5299. Therefore, the call <code>file:seek()</code> returns the current
  5300. file position, without changing it;
  5301. the call <code>file:seek("set")</code> sets the position to the
  5302. beginning of the file (and returns 0);
  5303. and the call <code>file:seek("end")</code> sets the position to the
  5304. end of the file, and returns its size.
  5305. <p>
  5306. <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
  5307. <p>
  5308. Sets the buffering mode for an output file.
  5309. There are three available modes:
  5310. <ul>
  5311. <li><b>"no":</b>
  5312. no buffering; the result of any output operation appears immediately.
  5313. </li>
  5314. <li><b>"full":</b>
  5315. full buffering; output operation is performed only
  5316. when the buffer is full (or when you explicitly <code>flush</code> the file
  5317. (see <a href="#pdf-io.flush"><code>io.flush</code></a>)).
  5318. </li>
  5319. <li><b>"line":</b>
  5320. line buffering; output is buffered until a newline is output
  5321. or there is any input from some special files
  5322. (such as a terminal device).
  5323. </li>
  5324. </ul><p>
  5325. For the last two cases, <code>size</code>
  5326. specifies the size of the buffer, in bytes.
  5327. The default is an appropriate size.
  5328. <p>
  5329. <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
  5330. <p>
  5331. Writes the value of each of its arguments to
  5332. the <code>file</code>.
  5333. The arguments must be strings or numbers.
  5334. To write other values,
  5335. use <a href="#pdf-tostring"><code>tostring</code></a> or <a href="#pdf-string.format"><code>string.format</code></a> before <code>write</code>.
  5336. <h2>5.8 - <a name="5.8">Operating System Facilities</a></h2>
  5337. <p>
  5338. This library is implemented through table <a name="pdf-os"><code>os</code></a>.
  5339. <p>
  5340. <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
  5341. <p>
  5342. Returns an approximation of the amount in seconds of CPU time
  5343. used by the program.
  5344. <p>
  5345. <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
  5346. <p>
  5347. Returns a string or a table containing date and time,
  5348. formatted according to the given string <code>format</code>.
  5349. <p>
  5350. If the <code>time</code> argument is present,
  5351. this is the time to be formatted
  5352. (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
  5353. Otherwise, <code>date</code> formats the current time.
  5354. <p>
  5355. If <code>format</code> starts with '<code>!</code>',
  5356. then the date is formatted in Coordinated Universal Time.
  5357. After this optional character,
  5358. if <code>format</code> is the string "<code>*t</code>",
  5359. then <code>date</code> returns a table with the following fields:
  5360. <code>year</code> (four digits), <code>month</code> (1--12), <code>day</code> (1--31),
  5361. <code>hour</code> (0--23), <code>min</code> (0--59), <code>sec</code> (0--61),
  5362. <code>wday</code> (weekday, Sunday is&nbsp;1),
  5363. <code>yday</code> (day of the year),
  5364. and <code>isdst</code> (daylight saving flag, a boolean).
  5365. <p>
  5366. If <code>format</code> is not "<code>*t</code>",
  5367. then <code>date</code> returns the date as a string,
  5368. formatted according to the same rules as the C&nbsp;function <code>strftime</code>.
  5369. <p>
  5370. When called without arguments,
  5371. <code>date</code> returns a reasonable date and time representation that depends on
  5372. the host system and on the current locale
  5373. (that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
  5374. <p>
  5375. <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
  5376. <p>
  5377. Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
  5378. In POSIX, Windows, and some other systems,
  5379. this value is exactly <code>t2</code><em>-</em><code>t1</code>.
  5380. <p>
  5381. <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
  5382. <p>
  5383. This function is equivalent to the C&nbsp;function <code>system</code>.
  5384. It passes <code>command</code> to be executed by an operating system shell.
  5385. It returns a status code, which is system-dependent.
  5386. If <code>command</code> is absent, then it returns nonzero if a shell is available
  5387. and zero otherwise.
  5388. <p>
  5389. <hr><h3><a name="pdf-os.exit"><code>os.exit ([code])</code></a></h3>
  5390. <p>
  5391. Calls the C&nbsp;function <code>exit</code>,
  5392. with an optional <code>code</code>,
  5393. to terminate the host program.
  5394. The default value for <code>code</code> is the success code.
  5395. <p>
  5396. <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
  5397. <p>
  5398. Returns the value of the process environment variable <code>varname</code>,
  5399. or <b>nil</b> if the variable is not defined.
  5400. <p>
  5401. <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
  5402. <p>
  5403. Deletes the file or directory with the given name.
  5404. Directories must be empty to be removed.
  5405. If this function fails, it returns <b>nil</b>,
  5406. plus a string describing the error.
  5407. <p>
  5408. <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
  5409. <p>
  5410. Renames file or directory named <code>oldname</code> to <code>newname</code>.
  5411. If this function fails, it returns <b>nil</b>,
  5412. plus a string describing the error.
  5413. <p>
  5414. <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
  5415. <p>
  5416. Sets the current locale of the program.
  5417. <code>locale</code> is a string specifying a locale;
  5418. <code>category</code> is an optional string describing which category to change:
  5419. <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
  5420. <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
  5421. the default category is <code>"all"</code>.
  5422. The function returns the name of the new locale,
  5423. or <b>nil</b> if the request cannot be honored.
  5424. <p>
  5425. If <code>locale</code> is the empty string,
  5426. the current locale is set to an implementation-defined native locale.
  5427. If <code>locale</code> is the string "<code>C</code>",
  5428. the current locale is set to the standard C locale.
  5429. <p>
  5430. When called with <b>nil</b> as the first argument,
  5431. this function only returns the name of the current locale
  5432. for the given category.
  5433. <p>
  5434. <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
  5435. <p>
  5436. Returns the current time when called without arguments,
  5437. or a time representing the date and time specified by the given table.
  5438. This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
  5439. and may have fields <code>hour</code>, <code>min</code>, <code>sec</code>, and <code>isdst</code>
  5440. (for a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function).
  5441. <p>
  5442. The returned value is a number, whose meaning depends on your system.
  5443. In POSIX, Windows, and some other systems, this number counts the number
  5444. of seconds since some given start time (the "epoch").
  5445. In other systems, the meaning is not specified,
  5446. and the number returned by <code>time</code> can be used only as an argument to
  5447. <code>date</code> and <code>difftime</code>.
  5448. <p>
  5449. <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
  5450. <p>
  5451. Returns a string with a file name that can
  5452. be used for a temporary file.
  5453. The file must be explicitly opened before its use
  5454. and explicitly removed when no longer needed.
  5455. <p>
  5456. On some systems (POSIX),
  5457. this function also creates a file with that name,
  5458. to avoid security risks.
  5459. (Someone else might create the file with wrong permissions
  5460. in the time between getting the name and creating the file.)
  5461. You still have to open the file to use it
  5462. and to remove it (even if you do not use it).
  5463. <p>
  5464. When possible,
  5465. you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
  5466. which automatically removes the file when the program ends.
  5467. <h2>5.9 - <a name="5.9">The Debug Library</a></h2>
  5468. <p>
  5469. This library provides
  5470. the functionality of the debug interface to Lua programs.
  5471. You should exert care when using this library.
  5472. The functions provided here should be used exclusively for debugging
  5473. and similar tasks, such as profiling.
  5474. Please resist the temptation to use them as a
  5475. usual programming tool:
  5476. they can be very slow.
  5477. Moreover, several of these functions
  5478. violate some assumptions about Lua code
  5479. (e.g., that variables local to a function
  5480. cannot be accessed from outside or
  5481. that userdata metatables cannot be changed by Lua code)
  5482. and therefore can compromise otherwise secure code.
  5483. <p>
  5484. All functions in this library are provided
  5485. inside the <a name="pdf-debug"><code>debug</code></a> table.
  5486. All functions that operate over a thread
  5487. have an optional first argument which is the
  5488. thread to operate over.
  5489. The default is always the current thread.
  5490. <p>
  5491. <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
  5492. <p>
  5493. Enters an interactive mode with the user,
  5494. running each string that the user enters.
  5495. Using simple commands and other debug facilities,
  5496. the user can inspect global and local variables,
  5497. change their values, evaluate expressions, and so on.
  5498. A line containing only the word <code>cont</code> finishes this function,
  5499. so that the caller continues its execution.
  5500. <p>
  5501. Note that commands for <code>debug.debug</code> are not lexically nested
  5502. within any function, and so have no direct access to local variables.
  5503. <p>
  5504. <hr><h3><a name="pdf-debug.getfenv"><code>debug.getfenv (o)</code></a></h3>
  5505. Returns the environment of object <code>o</code>.
  5506. <p>
  5507. <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
  5508. <p>
  5509. Returns the current hook settings of the thread, as three values:
  5510. the current hook function, the current hook mask,
  5511. and the current hook count
  5512. (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
  5513. <p>
  5514. <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] function [, what])</code></a></h3>
  5515. <p>
  5516. Returns a table with information about a function.
  5517. You can give the function directly,
  5518. or you can give a number as the value of <code>function</code>,
  5519. which means the function running at level <code>function</code> of the call stack
  5520. of the given thread:
  5521. level&nbsp;0 is the current function (<code>getinfo</code> itself);
  5522. level&nbsp;1 is the function that called <code>getinfo</code>;
  5523. and so on.
  5524. If <code>function</code> is a number larger than the number of active functions,
  5525. then <code>getinfo</code> returns <b>nil</b>.
  5526. <p>
  5527. The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
  5528. with the string <code>what</code> describing which fields to fill in.
  5529. The default for <code>what</code> is to get all information available,
  5530. except the table of valid lines.
  5531. If present,
  5532. the option '<code>f</code>'
  5533. adds a field named <code>func</code> with the function itself.
  5534. If present,
  5535. the option '<code>L</code>'
  5536. adds a field named <code>activelines</code> with the table of
  5537. valid lines.
  5538. <p>
  5539. For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
  5540. a table with a name for the current function,
  5541. if a reasonable name can be found,
  5542. and the expression <code>debug.getinfo(print)</code>
  5543. returns a table with all available information
  5544. about the <a href="#pdf-print"><code>print</code></a> function.
  5545. <p>
  5546. <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] level, local)</code></a></h3>
  5547. <p>
  5548. This function returns the name and the value of the local variable
  5549. with index <code>local</code> of the function at level <code>level</code> of the stack.
  5550. (The first parameter or local variable has index&nbsp;1, and so on,
  5551. until the last active local variable.)
  5552. The function returns <b>nil</b> if there is no local
  5553. variable with the given index,
  5554. and raises an error when called with a <code>level</code> out of range.
  5555. (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
  5556. <p>
  5557. Variable names starting with '<code>(</code>' (open parentheses)
  5558. represent internal variables
  5559. (loop control variables, temporaries, and C&nbsp;function locals).
  5560. <p>
  5561. <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (object)</code></a></h3>
  5562. <p>
  5563. Returns the metatable of the given <code>object</code>
  5564. or <b>nil</b> if it does not have a metatable.
  5565. <p>
  5566. <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
  5567. <p>
  5568. Returns the registry table (see <a href="#3.5">&sect;3.5</a>).
  5569. <p>
  5570. <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (func, up)</code></a></h3>
  5571. <p>
  5572. This function returns the name and the value of the upvalue
  5573. with index <code>up</code> of the function <code>func</code>.
  5574. The function returns <b>nil</b> if there is no upvalue with the given index.
  5575. <p>
  5576. <hr><h3><a name="pdf-debug.setfenv"><code>debug.setfenv (object, table)</code></a></h3>
  5577. <p>
  5578. Sets the environment of the given <code>object</code> to the given <code>table</code>.
  5579. Returns <code>object</code>.
  5580. <p>
  5581. <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
  5582. <p>
  5583. Sets the given function as a hook.
  5584. The string <code>mask</code> and the number <code>count</code> describe
  5585. when the hook will be called.
  5586. The string mask may have the following characters,
  5587. with the given meaning:
  5588. <ul>
  5589. <li><b><code>"c"</code>:</b> the hook is called every time Lua calls a function;</li>
  5590. <li><b><code>"r"</code>:</b> the hook is called every time Lua returns from a function;</li>
  5591. <li><b><code>"l"</code>:</b> the hook is called every time Lua enters a new line of code.</li>
  5592. </ul><p>
  5593. With a <code>count</code> different from zero,
  5594. the hook is called after every <code>count</code> instructions.
  5595. <p>
  5596. When called without arguments,
  5597. <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
  5598. <p>
  5599. When the hook is called, its first parameter is a string
  5600. describing the event that has triggered its call:
  5601. <code>"call"</code>, <code>"return"</code> (or <code>"tail return"</code>,
  5602. when simulating a return from a tail call),
  5603. <code>"line"</code>, and <code>"count"</code>.
  5604. For line events,
  5605. the hook also gets the new line number as its second parameter.
  5606. Inside a hook,
  5607. you can call <code>getinfo</code> with level&nbsp;2 to get more information about
  5608. the running function
  5609. (level&nbsp;0 is the <code>getinfo</code> function,
  5610. and level&nbsp;1 is the hook function),
  5611. unless the event is <code>"tail return"</code>.
  5612. In this case, Lua is only simulating the return,
  5613. and a call to <code>getinfo</code> will return invalid data.
  5614. <p>
  5615. <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
  5616. <p>
  5617. This function assigns the value <code>value</code> to the local variable
  5618. with index <code>local</code> of the function at level <code>level</code> of the stack.
  5619. The function returns <b>nil</b> if there is no local
  5620. variable with the given index,
  5621. and raises an error when called with a <code>level</code> out of range.
  5622. (You can call <code>getinfo</code> to check whether the level is valid.)
  5623. Otherwise, it returns the name of the local variable.
  5624. <p>
  5625. <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (object, table)</code></a></h3>
  5626. <p>
  5627. Sets the metatable for the given <code>object</code> to the given <code>table</code>
  5628. (which can be <b>nil</b>).
  5629. <p>
  5630. <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (func, up, value)</code></a></h3>
  5631. <p>
  5632. This function assigns the value <code>value</code> to the upvalue
  5633. with index <code>up</code> of the function <code>func</code>.
  5634. The function returns <b>nil</b> if there is no upvalue
  5635. with the given index.
  5636. Otherwise, it returns the name of the upvalue.
  5637. <p>
  5638. <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message] [, level])</code></a></h3>
  5639. <p>
  5640. Returns a string with a traceback of the call stack.
  5641. An optional <code>message</code> string is appended
  5642. at the beginning of the traceback.
  5643. An optional <code>level</code> number tells at which level
  5644. to start the traceback
  5645. (default is 1, the function calling <code>traceback</code>).
  5646. <h1>6 - <a name="6">Lua Stand-alone</a></h1>
  5647. <p>
  5648. Although Lua has been designed as an extension language,
  5649. to be embedded in a host C&nbsp;program,
  5650. it is also frequently used as a stand-alone language.
  5651. An interpreter for Lua as a stand-alone language,
  5652. called simply <code>lua</code>,
  5653. is provided with the standard distribution.
  5654. The stand-alone interpreter includes
  5655. all standard libraries, including the debug library.
  5656. Its usage is:
  5657. <pre>
  5658. lua [options] [script [args]]
  5659. </pre><p>
  5660. The options are:
  5661. <ul>
  5662. <li><b><code>-e <em>stat</em></code>:</b> executes string <em>stat</em>;</li>
  5663. <li><b><code>-l <em>mod</em></code>:</b> "requires" <em>mod</em>;</li>
  5664. <li><b><code>-i</code>:</b> enters interactive mode after running <em>script</em>;</li>
  5665. <li><b><code>-v</code>:</b> prints version information;</li>
  5666. <li><b><code>--</code>:</b> stops handling options;</li>
  5667. <li><b><code>-</code>:</b> executes <code>stdin</code> as a file and stops handling options.</li>
  5668. </ul><p>
  5669. After handling its options, <code>lua</code> runs the given <em>script</em>,
  5670. passing to it the given <em>args</em> as string arguments.
  5671. When called without arguments,
  5672. <code>lua</code> behaves as <code>lua -v -i</code>
  5673. when the standard input (<code>stdin</code>) is a terminal,
  5674. and as <code>lua -</code> otherwise.
  5675. <p>
  5676. Before running any argument,
  5677. the interpreter checks for an environment variable <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a>.
  5678. If its format is <code>@<em>filename</em></code>,
  5679. then <code>lua</code> executes the file.
  5680. Otherwise, <code>lua</code> executes the string itself.
  5681. <p>
  5682. All options are handled in order, except <code>-i</code>.
  5683. For instance, an invocation like
  5684. <pre>
  5685. $ lua -e'a=1' -e 'print(a)' script.lua
  5686. </pre><p>
  5687. will first set <code>a</code> to 1, then print the value of <code>a</code> (which is '<code>1</code>'),
  5688. and finally run the file <code>script.lua</code> with no arguments.
  5689. (Here <code>$</code> is the shell prompt. Your prompt may be different.)
  5690. <p>
  5691. Before starting to run the script,
  5692. <code>lua</code> collects all arguments in the command line
  5693. in a global table called <code>arg</code>.
  5694. The script name is stored at index 0,
  5695. the first argument after the script name goes to index 1,
  5696. and so on.
  5697. Any arguments before the script name
  5698. (that is, the interpreter name plus the options)
  5699. go to negative indices.
  5700. For instance, in the call
  5701. <pre>
  5702. $ lua -la b.lua t1 t2
  5703. </pre><p>
  5704. the interpreter first runs the file <code>a.lua</code>,
  5705. then creates a table
  5706. <pre>
  5707. arg = { [-2] = "lua", [-1] = "-la",
  5708. [0] = "b.lua",
  5709. [1] = "t1", [2] = "t2" }
  5710. </pre><p>
  5711. and finally runs the file <code>b.lua</code>.
  5712. The script is called with <code>arg[1]</code>, <code>arg[2]</code>, &middot;&middot;&middot;
  5713. as arguments;
  5714. it can also access these arguments with the vararg expression '<code>...</code>'.
  5715. <p>
  5716. In interactive mode,
  5717. if you write an incomplete statement,
  5718. the interpreter waits for its completion
  5719. by issuing a different prompt.
  5720. <p>
  5721. If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
  5722. then its value is used as the prompt.
  5723. Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
  5724. its value is used as the secondary prompt
  5725. (issued during incomplete statements).
  5726. Therefore, both prompts can be changed directly on the command line
  5727. or in any Lua programs by assigning to <code>_PROMPT</code>.
  5728. See the next example:
  5729. <pre>
  5730. $ lua -e"_PROMPT='myprompt&gt; '" -i
  5731. </pre><p>
  5732. (The outer pair of quotes is for the shell,
  5733. the inner pair is for Lua.)
  5734. Note the use of <code>-i</code> to enter interactive mode;
  5735. otherwise,
  5736. the program would just end silently
  5737. right after the assignment to <code>_PROMPT</code>.
  5738. <p>
  5739. To allow the use of Lua as a
  5740. script interpreter in Unix systems,
  5741. the stand-alone interpreter skips
  5742. the first line of a chunk if it starts with <code>#</code>.
  5743. Therefore, Lua scripts can be made into executable programs
  5744. by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
  5745. as in
  5746. <pre>
  5747. #!/usr/local/bin/lua
  5748. </pre><p>
  5749. (Of course,
  5750. the location of the Lua interpreter may be different in your machine.
  5751. If <code>lua</code> is in your <code>PATH</code>,
  5752. then
  5753. <pre>
  5754. #!/usr/bin/env lua
  5755. </pre><p>
  5756. is a more portable solution.)
  5757. <h1>7 - <a name="7">Incompatibilities with the Previous Version</a></h1>
  5758. <p>
  5759. Here we list the incompatibilities that you may find when moving a program
  5760. from Lua&nbsp;5.0 to Lua&nbsp;5.1.
  5761. You can avoid most of the incompatibilities compiling Lua with
  5762. appropriate options (see file <code>luaconf.h</code>).
  5763. However,
  5764. all these compatibility options will be removed in the next version of Lua.
  5765. <h2>7.1 - <a name="7.1">Changes in the Language</a></h2>
  5766. <ul>
  5767. <li>
  5768. The vararg system changed from the pseudo-argument <code>arg</code> with a
  5769. table with the extra arguments to the vararg expression.
  5770. (See compile-time option <code>LUA_COMPAT_VARARG</code> in <code>luaconf.h</code>.)
  5771. </li>
  5772. <li>
  5773. There was a subtle change in the scope of the implicit
  5774. variables of the <b>for</b> statement and for the <b>repeat</b> statement.
  5775. </li>
  5776. <li>
  5777. The long string/long comment syntax (<code>[[<em>string</em>]]</code>)
  5778. does not allow nesting.
  5779. You can use the new syntax (<code>[=[<em>string</em>]=]</code>) in these cases.
  5780. (See compile-time option <code>LUA_COMPAT_LSTR</code> in <code>luaconf.h</code>.)
  5781. </li>
  5782. </ul>
  5783. <h2>7.2 - <a name="7.2">Changes in the Libraries</a></h2>
  5784. <ul>
  5785. <li>
  5786. Function <code>string.gfind</code> was renamed <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>.
  5787. (See compile-time option <code>LUA_COMPAT_GFIND</code> in <code>luaconf.h</code>.)
  5788. </li>
  5789. <li>
  5790. When <a href="#pdf-string.gsub"><code>string.gsub</code></a> is called with a function as its
  5791. third argument,
  5792. whenever this function returns <b>nil</b> or <b>false</b> the
  5793. replacement string is the whole match,
  5794. instead of the empty string.
  5795. </li>
  5796. <li>
  5797. Function <code>table.setn</code> was deprecated.
  5798. Function <code>table.getn</code> corresponds
  5799. to the new length operator (<code>#</code>);
  5800. use the operator instead of the function.
  5801. (See compile-time option <code>LUA_COMPAT_GETN</code> in <code>luaconf.h</code>.)
  5802. </li>
  5803. <li>
  5804. Function <code>loadlib</code> was renamed <a href="#pdf-package.loadlib"><code>package.loadlib</code></a>.
  5805. (See compile-time option <code>LUA_COMPAT_LOADLIB</code> in <code>luaconf.h</code>.)
  5806. </li>
  5807. <li>
  5808. Function <code>math.mod</code> was renamed <a href="#pdf-math.fmod"><code>math.fmod</code></a>.
  5809. (See compile-time option <code>LUA_COMPAT_MOD</code> in <code>luaconf.h</code>.)
  5810. </li>
  5811. <li>
  5812. Functions <code>table.foreach</code> and <code>table.foreachi</code> are deprecated.
  5813. You can use a for loop with <code>pairs</code> or <code>ipairs</code> instead.
  5814. </li>
  5815. <li>
  5816. There were substantial changes in function <a href="#pdf-require"><code>require</code></a> due to
  5817. the new module system.
  5818. However, the new behavior is mostly compatible with the old,
  5819. but <code>require</code> gets the path from <a href="#pdf-package.path"><code>package.path</code></a> instead
  5820. of from <code>LUA_PATH</code>.
  5821. </li>
  5822. <li>
  5823. Function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> has different arguments.
  5824. Function <code>gcinfo</code> is deprecated;
  5825. use <code>collectgarbage("count")</code> instead.
  5826. </li>
  5827. </ul>
  5828. <h2>7.3 - <a name="7.3">Changes in the API</a></h2>
  5829. <ul>
  5830. <li>
  5831. The <code>luaopen_*</code> functions (to open libraries)
  5832. cannot be called directly,
  5833. like a regular C function.
  5834. They must be called through Lua,
  5835. like a Lua function.
  5836. </li>
  5837. <li>
  5838. Function <code>lua_open</code> was replaced by <a href="#lua_newstate"><code>lua_newstate</code></a> to
  5839. allow the user to set a memory-allocation function.
  5840. You can use <a href="#luaL_newstate"><code>luaL_newstate</code></a> from the standard library to
  5841. create a state with a standard allocation function
  5842. (based on <code>realloc</code>).
  5843. </li>
  5844. <li>
  5845. Functions <code>luaL_getn</code> and <code>luaL_setn</code>
  5846. (from the auxiliary library) are deprecated.
  5847. Use <a href="#lua_objlen"><code>lua_objlen</code></a> instead of <code>luaL_getn</code>
  5848. and nothing instead of <code>luaL_setn</code>.
  5849. </li>
  5850. <li>
  5851. Function <code>luaL_openlib</code> was replaced by <a href="#luaL_register"><code>luaL_register</code></a>.
  5852. </li>
  5853. <li>
  5854. Function <code>luaL_checkudata</code> now throws an error when the given value
  5855. is not a userdata of the expected type.
  5856. (In Lua&nbsp;5.0 it returned <code>NULL</code>.)
  5857. </li>
  5858. </ul>
  5859. <h1>8 - <a name="8">The Complete Syntax of Lua</a></h1>
  5860. <p>
  5861. Here is the complete syntax of Lua in extended BNF.
  5862. (It does not describe operator precedences.)
  5863. <pre>
  5864. chunk ::= {stat [`<b>;</b>&acute;]} [laststat [`<b>;</b>&acute;]]
  5865. block ::= chunk
  5866. stat ::= varlist `<b>=</b>&acute; explist |
  5867. functioncall |
  5868. <b>do</b> block <b>end</b> |
  5869. <b>while</b> exp <b>do</b> block <b>end</b> |
  5870. <b>repeat</b> block <b>until</b> exp |
  5871. <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
  5872. <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b> |
  5873. <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
  5874. <b>function</b> funcname funcbody |
  5875. <b>local</b> <b>function</b> Name funcbody |
  5876. <b>local</b> namelist [`<b>=</b>&acute; explist]
  5877. laststat ::= <b>return</b> [explist] | <b>break</b>
  5878. funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
  5879. varlist ::= var {`<b>,</b>&acute; var}
  5880. var ::= Name | prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute; | prefixexp `<b>.</b>&acute; Name
  5881. namelist ::= Name {`<b>,</b>&acute; Name}
  5882. explist ::= {exp `<b>,</b>&acute;} exp
  5883. exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | `<b>...</b>&acute; | function |
  5884. prefixexp | tableconstructor | exp binop exp | unop exp
  5885. prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
  5886. functioncall ::= prefixexp args | prefixexp `<b>:</b>&acute; Name args
  5887. args ::= `<b>(</b>&acute; [explist] `<b>)</b>&acute; | tableconstructor | String
  5888. function ::= <b>function</b> funcbody
  5889. funcbody ::= `<b>(</b>&acute; [parlist] `<b>)</b>&acute; block <b>end</b>
  5890. parlist ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
  5891. tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
  5892. fieldlist ::= field {fieldsep field} [fieldsep]
  5893. field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
  5894. fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
  5895. binop ::= `<b>+</b>&acute; | `<b>-</b>&acute; | `<b>*</b>&acute; | `<b>/</b>&acute; | `<b>^</b>&acute; | `<b>%</b>&acute; | `<b>..</b>&acute; |
  5896. `<b>&lt;</b>&acute; | `<b>&lt;=</b>&acute; | `<b>&gt;</b>&acute; | `<b>&gt;=</b>&acute; | `<b>==</b>&acute; | `<b>~=</b>&acute; |
  5897. <b>and</b> | <b>or</b>
  5898. unop ::= `<b>-</b>&acute; | <b>not</b> | `<b>#</b>&acute;
  5899. </pre>
  5900. <p>
  5901. <HR>
  5902. <SMALL>
  5903. Last update:
  5904. Mon Aug 18 13:25:46 BRT 2008
  5905. </SMALL>
  5906. <!--
  5907. Last change: revised for Lua 5.1.4
  5908. -->
  5909. </body></html>