aboutsummaryrefslogtreecommitdiff
path: root/manual
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-07-09 12:33:01 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-07-09 12:33:01 -0300
commit7c519dfbd0c68b952f0849e01deaa3750e1f8153 (patch)
treedde3ddbba310877db725df37a0d9f2cbe4e2a8f9 /manual
parentf59e6a93c0ad38a27a420e51abf8f13d962446b5 (diff)
downloadlua-7c519dfbd0c68b952f0849e01deaa3750e1f8153.tar.gz
lua-7c519dfbd0c68b952f0849e01deaa3750e1f8153.tar.bz2
lua-7c519dfbd0c68b952f0849e01deaa3750e1f8153.zip
Added manual and tests for version 5.4-w2
Diffstat (limited to 'manual')
-rwxr-xr-xmanual/2html518
-rw-r--r--manual/manual.of8704
2 files changed, 9222 insertions, 0 deletions
diff --git a/manual/2html b/manual/2html
new file mode 100755
index 00000000..04b2c61e
--- /dev/null
+++ b/manual/2html
@@ -0,0 +1,518 @@
1#!/usr/bin/env lua5.3
2
3
4-- special marks:
5-- \1 - paragraph (empty line)
6-- \4 - remove spaces around it
7-- \3 - ref (followed by label|)
8
9---------------------------------------------------------------
10header = [[
11<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
12<html>
13
14<head>
15<title>Lua 5.4 Reference Manual</title>
16<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
17<link rel="stylesheet" href="lua.css">
18<link rel="stylesheet" href="manual.css">
19</head>
20
21<body bgcolor="#FFFFFF">
22
23<hr>
24<h1>
25<a href="http://www.lua.org/home.html"><img src="logo.gif" alt="[Lua logo]" border="0"></a>
26Lua 5.4 Reference Manual
27</h1>
28
29by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
30<p>
31<small>
32<a href="http://www.lua.org/copyright.html">Copyright</a>
33&copy; 2018 Lua.org, PUC-Rio. All rights reserved.
34</small>
35<hr>
36
37<!-- ====================================================================== -->
38<p>
39
40]]
41
42footer = "\n\n</body></html>\n\n"
43
44local seefmt = '(see %s)'
45
46if arg[1] == 'port' then
47 seefmt = '(ver %s)'
48 header = string.gsub(header, "by (.-)\n",
49 "%1\n<p>Tradu&ccedil;&atilde;o: S&eacute;rgio Queiroz de Medeiros", 1)
50 header = string.gsub(header, "Lua (%d+.%d+) Reference Manual",
51 "Manual de Refer&ecirc;ncia de Lua %1")
52 header = string.gsub(header, "All rights reserved",
53 "Todos os direitos reservados")
54end
55
56
57---------------------------------------------------------------
58
59local function compose (f,g)
60 assert(f and g)
61 return function (s) return g(f(s)) end
62end
63
64local function concat (f, g)
65 assert(f and g)
66 return function (s) return f(s) .. g(s) end
67end
68
69
70local Tag = {}
71
72
73setmetatable(Tag, {
74 __index = function (t, tag)
75 local v = function (n, att)
76 local e = ""
77 if type(att) == "table" then
78 for k,v in pairs(att) do e = string.format('%s %s="%s"', e, k, v) end
79 end
80 if n then
81 return string.format("<%s%s>%s</%s>", tag, e, n, tag)
82 else
83 return string.format("<%s%s>", tag, e)
84 end
85 end
86 t[tag] = v
87 return v
88 end
89})
90
91
92
93---------------------------------------------------------------
94local labels = {}
95
96
97local function anchor (text, label, link, textlink)
98 if labels[label] then
99 error("label " .. label .. " already defined")
100 end
101 labels[label] = {text = textlink, link = link}
102 return Tag.a(text, {name=link})
103end
104
105local function makeref (label)
106 assert(not string.find(label, "|"))
107 return string.format("\3%s\3", label)
108end
109
110local function ref (label)
111 local l = labels[label]
112 if not l then
113 io.stderr:write("label ", label, " undefined\n")
114 return "@@@@@@@"
115 else
116 return Tag.a(l.text, {href="#"..l.link})
117 end
118end
119
120---------------------------------------------------------------
121local function nopara (t)
122 t = string.gsub(t, "\1", "\n\n")
123 t = string.gsub(t, "<p>%s*</p>", "")
124 return t
125end
126
127local function fixpara (t)
128 t = string.gsub(t, "\1", "\n</p>\n\n<p>\n")
129 t = string.gsub(t, "<p>%s*</p>", "")
130 return t
131end
132
133local function antipara (t)
134 return "</p>\n" .. t .. "<p>"
135end
136
137
138Tag.pre = compose(Tag.pre, antipara)
139Tag.ul = compose(Tag.ul, antipara)
140
141---------------------------------------------------------------
142local Gfoots = 0
143local footnotes = {}
144
145local line = Tag.hr(nil)
146
147local function dischargefoots ()
148 if #footnotes == 0 then return "" end
149 local fn = table.concat(footnotes)
150 footnotes = {}
151 return line .. Tag.h3"footnotes:" .. fn .. line
152end
153
154
155local Glists = 0
156local listings = {}
157
158local function dischargelist ()
159 if #listings == 0 then return "" end
160 local l = listings
161 listings = {}
162 return line .. table.concat(l, line..line) .. line
163end
164
165---------------------------------------------------------------
166local counters = {
167h1 = {val = 1},
168h2 = {father = "h1", val = 1},
169h3 = {father = "h2", val = 1},
170listing = {father = "h1", val = 1},
171}
172
173local function inccounter (count)
174 counters[count].val = counters[count].val + 1
175 for c, v in pairs(counters) do
176 if v.father == count then v.val = 1 end
177 end
178end
179
180local function getcounter (count)
181 local c = counters[count]
182 if c.father then
183 return getcounter(c.father) .. "." .. c.val
184 else
185 return c.val .. ""
186 end
187end
188---------------------------------------------------------------
189
190
191local function fixed (x)
192 return function () return x end
193end
194
195local function id (x) return x end
196
197
198local function prepos (x, y)
199 assert(x and y)
200 return function (s) return string.format("%s%s%s", x, s, y) end
201end
202
203
204local rw = Tag.b
205
206
207
208
209local function LuaName (name)
210 return Tag.code(name)
211end
212
213
214local function getparam (s)
215 local i, e = string.find(s, "^[^%s@|]+|")
216 if not i then return nil, s
217 else return string.sub(s, i, e - 1), string.sub(s, e + 1)
218 end
219end
220
221
222local function gettitle (h)
223 local title, p = assert(string.match(h, "<title>(.-)</title>()"))
224 return title, string.sub(h, p)
225end
226
227local function getparamtitle (what, h, nonum)
228 local label, title, c, count
229 label, h = getparam(h)
230 title, h = gettitle(h)
231 if not nonum then
232 count = getcounter(what)
233 inccounter(what)
234 c = string.format("%s &ndash; ", count)
235 else
236 c = ""
237 end
238 label = label or count
239 if label then
240 title = anchor(title, label, count, "&sect;"..count)
241 end
242 title = string.format("%s%s", c, title)
243 return title, h
244end
245
246local function section (what, nonum)
247 return function (h)
248 local title
249 title, h = getparamtitle(what, h, nonum)
250 local fn = what == "h1" and dischargefoots() or ""
251 h = fixpara(Tag.p(h))
252 return "</p>\n" .. Tag[what](title) .. h .. fn ..
253 dischargelist() .. "<p>"
254 end
255end
256
257
258local function verbatim (s)
259 s = nopara(s)
260 s = string.gsub(s, "\n", "\n ")
261 s = string.gsub(s, "\n%s*$", "\n")
262 return Tag.pre(s)
263end
264
265
266local function verb (s)
267 return Tag.code(s)
268end
269
270
271local function lua2link (e)
272 return string.find(e, "luaL?_") and e or "pdf-"..e
273end
274
275
276local verbfixed = verb
277
278
279local Tex = {
280
281ANSI = function (func)
282 return "ISO&nbsp;C function " .. Tag.code(func)
283 end,
284At = fixed"@",
285B = Tag.b,
286bigskip = fixed"",
287bignum = id,
288C = fixed"",
289Ci = prepos("<!-- ", " -->"),
290CId = function (func)
291 return "C&nbsp;function " .. Tag.code(func)
292 end,
293chapter = section"h1",
294Char = compose(verbfixed, prepos("'", "'")),
295Cdots = fixed"&middot;&middot;&middot;",
296Close = fixed"}",
297col = Tag.td,
298defid = function (name)
299 local l = lua2link(name)
300 local c = Tag.code(name)
301 return anchor(c, l, l, c)
302 end,
303def = Tag.em,
304description = compose(nopara, Tag.ul),
305Em = fixed("\4" .. "&mdash;" .. "\4"),
306emph = Tag.em,
307emphx = Tag.em, -- emphasis plus index (if there was an index)
308En = fixed("&ndash;"),
309format = fixed"",
310["false"] = fixed(Tag.b"false"),
311id = Tag.code,
312idx = Tag.code,
313index = fixed"",
314Lidx = fixed"", -- Tag.code,
315ldots = fixed"...",
316x = id,
317itemize = compose(nopara, Tag.ul),
318leq = fixed"&le;",
319Lid = function (s)
320 return makeref(lua2link(s))
321 end,
322M = Tag.em,
323N = function (s) return (string.gsub(s, " ", "&nbsp;")) end,
324NE = id, -- tag"foreignphrase",
325num = id,
326["nil"] = fixed(Tag.b"nil"),
327Open = fixed"{",
328part = section("h1", true),
329Pat = compose(verbfixed, prepos("'", "'")),
330preface = section("h1", true),
331psect = section("h2", true),
332Q = prepos('"', '"'),
333refchp = makeref,
334refcode = makeref,
335refsec = makeref,
336
337pi = fixed"&pi;",
338rep = Tag.em, -- compose(prepos("&lt;", "&gt;"), Tag.em),
339Rw = rw,
340rw = rw,
341sb = Tag.sub,
342sp = Tag.sup,
343St = compose(verbfixed, prepos('"', '"')),
344sect1 = section"h1",
345sect2 = section"h2",
346sect3 = section"h3",
347sect4 = section("h4", true),
348simplesect = id,
349Tab2 = function (s) return Tag.table(s, {border=1}) end,
350row = Tag.tr,
351title = Tag.title,
352todo = Tag.todo,
353["true"] = fixed(Tag.b"true"),
354T = verb,
355
356item = function (s)
357 local t, p = string.match(s, "^([^\n|]+)|()")
358 if t then
359 s = string.sub(s, p)
360 s = Tag.b(t..": ") .. s
361 end
362 return Tag.li(fixpara(s))
363 end,
364
365verbatim = verbatim,
366
367manual = id,
368
369
370-- for the manual
371
372link =function (s)
373 local l, t = getparam(s)
374 assert(l)
375 return string.format("%s (%s)", t, makeref(l))
376end,
377
378see = function (s) return string.format(seefmt, makeref(s)) end,
379See = makeref,
380seeC = function (s)
381 return string.format(seefmt, makeref(s))
382 end,
383
384seeF = function (s)
385 return string.format(seefmt, makeref(lua2link(s)))
386 end,
387
388APIEntry = function (e)
389 local h, name
390 h, e = string.match(e, "^%s*(.-)%s*|(.*)$")
391 name = string.match(h, "(luaL?_[%w_]+)%)? +%(") or
392 string.match(h, "luaL?_[%w_]+")
393 local a = anchor(Tag.code(name), name, name, Tag.code(name))
394 local apiicmd, ne = string.match(e, "^(.-</span>)(.*)")
395--io.stderr:write(e)
396 if not apiicmd then
397 return antipara(Tag.hr() .. Tag.h3(a)) .. Tag.pre(h) .. e
398 else
399 return antipara(Tag.hr() .. Tag.h3(a)) .. apiicmd .. Tag.pre(h) .. ne
400 end
401end,
402
403LibEntry = function (e)
404 local h, name
405 h, e = string.match(e, "^(.-)|(.*)$")
406 name = string.gsub(h, " (.+", "")
407 local l = lua2link(name)
408 local a = anchor(Tag.code(h), l, l, Tag.code(name))
409 return Tag.hr() .. Tag.h3(a) .. e
410end,
411
412Produc = compose(nopara, Tag.pre),
413producname = prepos("\t", " ::= "),
414Or = fixed" | ",
415VerBar = fixed"&#124;", -- vertical bar
416OrNL = fixed" | \4",
417bnfNter = prepos("", ""),
418bnfopt = prepos("[", "]"),
419bnfrep = prepos("{", "}"),
420bnfter = compose(Tag.b, prepos("&lsquo;", "&rsquo;")),
421producbody = function (s)
422 s = string.gsub(s, "%s+", " ")
423 s = string.gsub(s, "\4", "\n\t\t")
424 return s
425 end,
426
427apii = function (s)
428 local pop,push,err = string.match(s, "^(.-),(.-),(.*)$")
429 if pop ~= "?" and string.find(pop, "%W") then
430 pop = "(" .. pop .. ")"
431 end
432 if push ~= "?" and string.find(push, "%W") then
433 push = "(" .. push .. ")"
434 end
435 err = (err == "-") and "&ndash;" or Tag.em(err)
436 return Tag.span(
437 string.format("[-%s, +%s, %s]", pop, push, err),
438 {class="apii"}
439 )
440 end,
441}
442
443local others = prepos("?? "," ??")
444
445local function trata (t)
446 t = string.gsub(t, "@(%w+)(%b{})", function (w, f)
447 f = trata(string.sub(f, 2, -2))
448 if type(Tex[w]) ~= "function" then
449 io.stderr:write(w .. "\n")
450 return others(f)
451 else
452 return Tex[w](f, w)
453 end
454 end)
455 return t
456end
457
458
459---------------------------------------------------------------------
460---------------------------------------------------------------------
461
462-- read whole book
463t = io.read"*a"
464
465t = string.gsub(t, "[<>&\128-\255]",
466 {["<"] = "&lt;",
467 [">"] = "&gt;",
468 ["&"] = "&amp;",
469 ["\170"] = "&ordf;",
470 ["\186"] = "&ordm;",
471 ["\192"] = "&Agrave;",
472 ["\193"] = "&Aacute;",
473 ["\194"] = "&Acirc;",
474 ["\195"] = "&Atilde;",
475 ["\199"] = "&Ccedil;",
476 ["\201"] = "&Eacute;",
477 ["\202"] = "&Ecirc;",
478 ["\205"] = "&Iacute;",
479 ["\211"] = "&Oacute;",
480 ["\212"] = "&Ocirc;",
481 ["\218"] = "&Uacute;",
482 ["\224"] = "&agrave;",
483 ["\225"] = "&aacute;",
484 ["\226"] = "&acirc;",
485 ["\227"] = "&atilde;",
486 ["\231"] = "&ccedil;",
487 ["\233"] = "&eacute;",
488 ["\234"] = "&ecirc;",
489 ["\237"] = "&iacute;",
490 ["\243"] = "&oacute;",
491 ["\244"] = "&ocirc;",
492 ["\245"] = "&otilde;",
493 ["\250"] = "&uacute;",
494 ["\252"] = "&uuml;"
495 })
496
497t = string.gsub(t, "\n\n+", "\1")
498
499
500
501-- complete macros with no arguments
502t = string.gsub(t, "(@%w+)([^{%w])", "%1{}%2")
503
504t = trata(t)
505
506-- correct references
507t = string.gsub(t, "\3(.-)\3", ref)
508
509-- remove extra space (??)
510t = string.gsub(t, "%s*\4%s*", "")
511
512t = nopara(t)
513
514-- HTML 3.2 does not need </p> (but complains when it is in wrong places :)
515t = string.gsub(t, "</p>", "")
516
517io.write(header, t, footer)
518
diff --git a/manual/manual.of b/manual/manual.of
new file mode 100644
index 00000000..935990d0
--- /dev/null
+++ b/manual/manual.of
@@ -0,0 +1,8704 @@
1@Ci{$Id: manual.of,v 1.175 2018/06/18 19:17:35 roberto Exp $}
2@C{[(-------------------------------------------------------------------------}
3@manual{
4
5@sect1{@title{Introduction}
6
7Lua is a powerful, efficient, lightweight, embeddable scripting language.
8It supports procedural programming,
9object-oriented programming, functional programming,
10data-driven programming, and data description.
11
12Lua combines simple procedural syntax with powerful data description
13constructs based on associative arrays and extensible semantics.
14Lua is dynamically typed,
15runs by interpreting bytecode with a register-based
16virtual machine,
17and has automatic memory management with
18incremental garbage collection,
19making it ideal for configuration, scripting,
20and rapid prototyping.
21
22Lua is implemented as a library, written in @emphx{clean C},
23the common subset of @N{Standard C} and C++.
24The Lua distribution includes a host program called @id{lua},
25which uses the Lua library to offer a complete,
26standalone Lua interpreter,
27for interactive or batch use.
28Lua is intended to be used both as a powerful, lightweight,
29embeddable scripting language for any program that needs one,
30and as a powerful but lightweight and efficient stand-alone language.
31
32As an extension language, Lua has no notion of a @Q{main} program:
33it works @emph{embedded} in a host client,
34called the @emph{embedding program} or simply the @emphx{host}.
35(Frequently, this host is the stand-alone @id{lua} program.)
36The host program can invoke functions to execute a piece of Lua code,
37can write and read Lua variables,
38and can register @N{C functions} to be called by Lua code.
39Through the use of @N{C functions}, Lua can be augmented to cope with
40a wide range of different domains,
41thus creating customized programming languages sharing a syntactical framework.
42
43Lua is free software,
44and is provided as usual with no guarantees,
45as stated in its license.
46The implementation described in this manual is available
47at Lua's official web site, @id{www.lua.org}.
48
49Like any other reference manual,
50this document is dry in places.
51For a discussion of the decisions behind the design of Lua,
52see the technical papers available at Lua's web site.
53For a detailed introduction to programming in Lua,
54see Roberto's book, @emphx{Programming in Lua}.
55
56}
57
58
59@C{-------------------------------------------------------------------------}
60@sect1{basic| @title{Basic Concepts}
61
62This section describes the basic concepts of the language.
63
64@sect2{TypesSec| @title{Values and Types}
65
66Lua is a dynamically typed language.
67This means that
68variables do not have types; only values do.
69There are no type definitions in the language.
70All values carry their own type.
71
72All values in Lua are first-class values.
73This means that all values can be stored in variables,
74passed as arguments to other functions, and returned as results.
75
76There are eight @x{basic types} in Lua:
77@def{nil}, @def{boolean}, @def{number},
78@def{string}, @def{function}, @def{userdata},
79@def{thread}, and @def{table}.
80The type @emph{nil} has one single value, @nil,
81whose main property is to be different from any other value;
82it usually represents the absence of a useful value.
83The type @emph{boolean} has two values, @false and @true.
84Both @nil and @false make a condition false;
85any other value makes it true.
86The type @emph{number} represents both
87integer numbers and real (floating-point) numbers.
88The type @emph{string} represents immutable sequences of bytes.
89@index{eight-bit clean}
90Lua is 8-bit clean:
91strings can contain any 8-bit value,
92including @x{embedded zeros} (@Char{\0}).
93Lua is also encoding-agnostic;
94it makes no assumptions about the contents of a string.
95
96The type @emph{number} uses two internal representations,
97or two @x{subtypes},
98one called @def{integer} and the other called @def{float}.
99Lua has explicit rules about when each representation is used,
100but it also converts between them automatically as needed @see{coercion}.
101Therefore,
102the programmer may choose to mostly ignore the difference
103between integers and floats
104or to assume complete control over the representation of each number.
105Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
106but you can also compile Lua so that it
107uses 32-bit integers and/or single-precision (32-bit) floats.
108The option with 32 bits for both integers and floats
109is particularly attractive
110for small machines and embedded systems.
111(See macro @id{LUA_32BITS} in file @id{luaconf.h}.)
112
113Lua can call (and manipulate) functions written in Lua and
114functions written in C @see{functioncall}.
115Both are represented by the type @emph{function}.
116
117The type @emph{userdata} is provided to allow arbitrary @N{C data} to
118be stored in Lua variables.
119A userdata value represents a block of raw memory.
120There are two kinds of userdata:
121@emphx{full userdata},
122which is an object with a block of memory managed by Lua,
123and @emphx{light userdata},
124which is simply a @N{C pointer} value.
125Userdata has no predefined operations in Lua,
126except assignment and identity test.
127By using @emph{metatables},
128the programmer can define operations for full userdata values
129@see{metatable}.
130Userdata values cannot be created or modified in Lua,
131only through the @N{C API}.
132This guarantees the integrity of data owned by the host program.
133
134The type @def{thread} represents independent threads of execution
135and it is used to implement coroutines @see{coroutine}.
136Lua threads are not related to operating-system threads.
137Lua supports coroutines on all systems,
138even those that do not support threads natively.
139
140The type @emph{table} implements @x{associative arrays},
141that is, @x{arrays} that can have as indices not only numbers,
142but any Lua value except @nil and @x{NaN}.
143(@emphx{Not a Number} is a special floating-point value
144used by the @x{IEEE 754} standard to represent
145undefined or unrepresentable numerical results, such as @T{0/0}.)
146Tables can be @emph{heterogeneous};
147that is, they can contain values of all types (except @nil).
148Any key with value @nil is not considered part of the table.
149Conversely, any key that is not part of a table has
150an associated value @nil.
151
152Tables are the sole data-structuring mechanism in Lua;
153they can be used to represent ordinary arrays, lists,
154symbol tables, sets, records, graphs, trees, etc.
155To represent @x{records}, Lua uses the field name as an index.
156The language supports this representation by
157providing @id{a.name} as syntactic sugar for @T{a["name"]}.
158There are several convenient ways to create tables in Lua
159@see{tableconstructor}.
160
161Like indices,
162the values of table fields can be of any type.
163In particular,
164because functions are first-class values,
165table fields can contain functions.
166Thus tables can also carry @emph{methods} @see{func-def}.
167
168The indexing of tables follows
169the definition of raw equality in the language.
170The expressions @T{a[i]} and @T{a[j]}
171denote the same table element
172if and only if @id{i} and @id{j} are raw equal
173(that is, equal without metamethods).
174In particular, floats with integral values
175are equal to their respective integers
176(e.g., @T{1.0 == 1}).
177To avoid ambiguities,
178any float with integral value used as a key
179is converted to its respective integer.
180For instance, if you write @T{a[2.0] = true},
181the actual key inserted into the table will be the
182integer @T{2}.
183(On the other hand,
1842 and @St{2} are different Lua values and therefore
185denote different table entries.)
186
187
188Tables, functions, threads, and (full) userdata values are @emph{objects}:
189variables do not actually @emph{contain} these values,
190only @emph{references} to them.
191Assignment, parameter passing, and function returns
192always manipulate references to such values;
193these operations do not imply any kind of copy.
194
195The library function @Lid{type} returns a string describing the type
196of a given value @see{predefined}.
197
198}
199
200@sect2{globalenv| @title{Environments and the Global Environment}
201
202As will be discussed in @refsec{variables} and @refsec{assignment},
203any reference to a free name
204(that is, a name not bound to any declaration) @id{var}
205is syntactically translated to @T{_ENV.var}.
206Moreover, every chunk is compiled in the scope of
207an external local variable named @id{_ENV} @see{chunks},
208so @id{_ENV} itself is never a free name in a chunk.
209
210Despite the existence of this external @id{_ENV} variable and
211the translation of free names,
212@id{_ENV} is a completely regular name.
213In particular,
214you can define new variables and parameters with that name.
215Each reference to a free name uses the @id{_ENV} that is
216visible at that point in the program,
217following the usual visibility rules of Lua @see{visibility}.
218
219Any table used as the value of @id{_ENV} is called an @def{environment}.
220
221Lua keeps a distinguished environment called the @def{global environment}.
222This value is kept at a special index in the C registry @see{registry}.
223In Lua, the global variable @Lid{_G} is initialized with this same value.
224(@Lid{_G} is never used internally.)
225
226When Lua loads a chunk,
227the default value for its @id{_ENV} upvalue
228is the global environment @seeF{load}.
229Therefore, by default,
230free names in Lua code refer to entries in the global environment
231(and, therefore, they are also called @def{global variables}).
232Moreover, all standard libraries are loaded in the global environment
233and some functions there operate on that environment.
234You can use @Lid{load} (or @Lid{loadfile})
235to load a chunk with a different environment.
236(In C, you have to load the chunk and then change the value
237of its first upvalue.)
238
239}
240
241@sect2{error| @title{Error Handling}
242
243Because Lua is an embedded extension language,
244all Lua actions start from @N{C code} in the host program
245calling a function from the Lua library.
246(When you use Lua standalone,
247the @id{lua} application is the host program.)
248Whenever an error occurs during
249the compilation or execution of a Lua chunk,
250control returns to the host,
251which can take appropriate measures
252(such as printing an error message).
253
254Lua code can explicitly generate an error by calling the
255@Lid{error} function.
256If you need to catch errors in Lua,
257you can use @Lid{pcall} or @Lid{xpcall}
258to call a given function in @emphx{protected mode}.
259
260Whenever there is an error,
261an @def{error object} (also called an @def{error message})
262is propagated with information about the error.
263Lua itself only generates errors whose error object is a string,
264but programs may generate errors with
265any value as the error object.
266It is up to the Lua program or its host to handle such error objects.
267
268
269When you use @Lid{xpcall} or @Lid{lua_pcall},
270you may give a @def{message handler}
271to be called in case of errors.
272This function is called with the original error object
273and returns a new error object.
274It is called before the error unwinds the stack,
275so that it can gather more information about the error,
276for instance by inspecting the stack and creating a stack traceback.
277This message handler is still protected by the protected call;
278so, an error inside the message handler
279will call the message handler again.
280If this loop goes on for too long,
281Lua breaks it and returns an appropriate message.
282(The message handler is called only for regular runtime errors.
283It is not called for memory-allocation errors
284nor for errors while running finalizers.)
285
286}
287
288@sect2{metatable| @title{Metatables and Metamethods}
289
290Every value in Lua can have a @emph{metatable}.
291This @def{metatable} is an ordinary Lua table
292that defines the behavior of the original value
293under certain special operations.
294You can change several aspects of the behavior
295of operations over a value by setting specific fields in its metatable.
296For instance, when a non-numeric value is the operand of an addition,
297Lua checks for a function in the field @St{__add} of the value's metatable.
298If it finds one,
299Lua calls this function to perform the addition.
300
301The key for each event in a metatable is a string
302with the event name prefixed by two underscores;
303the corresponding values are called @def{metamethods}.
304In the previous example, the key is @St{__add}
305and the metamethod is the function that performs the addition.
306Unless stated otherwise,
307metamethods should be function values.
308
309You can query the metatable of any value
310using the @Lid{getmetatable} function.
311Lua queries metamethods in metatables using a raw access @seeF{rawget}.
312So, to retrieve the metamethod for event @id{ev} in object @id{o},
313Lua does the equivalent to the following code:
314@verbatim{
315rawget(getmetatable(@rep{o}) or {}, "__@rep{ev}")
316}
317
318You can replace the metatable of tables
319using the @Lid{setmetatable} function.
320You cannot change the metatable of other types from Lua code
321(except by using the @link{debuglib|debug library});
322you should use the @N{C API} for that.
323
324Tables and full userdata have individual metatables
325(although multiple tables and userdata can share their metatables).
326Values of all other types share one single metatable per type;
327that is, there is one single metatable for all numbers,
328one for all strings, etc.
329By default, a value has no metatable,
330but the string library sets a metatable for the string type @see{strlib}.
331
332A metatable controls how an object behaves in
333arithmetic operations, bitwise operations,
334order comparisons, concatenation, length operation, calls, and indexing.
335A metatable also can define a function to be called
336when a userdata or a table is @link{GC|garbage collected}.
337
338For the unary operators (negation, length, and bitwise NOT),
339the metamethod is computed and called with a dummy second operand,
340equal to the first one.
341This extra operand is only to simplify Lua's internals
342(by making these operators behave like a binary operation)
343and may be removed in future versions.
344(For most uses this extra operand is irrelevant.)
345
346A detailed list of events controlled by metatables is given next.
347Each operation is identified by its corresponding key.
348
349@description{
350
351@item{@idx{__add}|
352the addition (@T{+}) operation.
353If any operand for an addition is not a number
354(nor a string coercible to a number),
355Lua will try to call a metamethod.
356First, Lua will check the first operand (even if it is valid).
357If that operand does not define a metamethod for @idx{__add},
358then Lua will check the second operand.
359If Lua can find a metamethod,
360it calls the metamethod with the two operands as arguments,
361and the result of the call
362(adjusted to one value)
363is the result of the operation.
364Otherwise,
365it raises an error.
366}
367
368@item{@idx{__sub}|
369the subtraction (@T{-}) operation.
370Behavior similar to the addition operation.
371}
372
373@item{@idx{__mul}|
374the multiplication (@T{*}) operation.
375Behavior similar to the addition operation.
376}
377
378@item{@idx{__div}|
379the division (@T{/}) operation.
380Behavior similar to the addition operation.
381}
382
383@item{@idx{__mod}|
384the modulo (@T{%}) operation.
385Behavior similar to the addition operation.
386}
387
388@item{@idx{__pow}|
389the exponentiation (@T{^}) operation.
390Behavior similar to the addition operation.
391}
392
393@item{@idx{__unm}|
394the negation (unary @T{-}) operation.
395Behavior similar to the addition operation.
396}
397
398@item{@idx{__idiv}|
399the floor division (@T{//}) operation.
400Behavior similar to the addition operation.
401}
402
403@item{@idx{__band}|
404the bitwise AND (@T{&}) operation.
405Behavior similar to the addition operation,
406except that Lua will try a metamethod
407if any operand is neither an integer
408nor a value coercible to an integer @see{coercion}.
409}
410
411@item{@idx{__bor}|
412the bitwise OR (@T{|}) operation.
413Behavior similar to the bitwise AND operation.
414}
415
416@item{@idx{__bxor}|
417the bitwise exclusive OR (binary @T{~}) operation.
418Behavior similar to the bitwise AND operation.
419}
420
421@item{@idx{__bnot}|
422the bitwise NOT (unary @T{~}) operation.
423Behavior similar to the bitwise AND operation.
424}
425
426@item{@idx{__shl}|
427the bitwise left shift (@T{<<}) operation.
428Behavior similar to the bitwise AND operation.
429}
430
431@item{@idx{__shr}|
432the bitwise right shift (@T{>>}) operation.
433Behavior similar to the bitwise AND operation.
434}
435
436@item{@idx{__concat}|
437the concatenation (@T{..}) operation.
438Behavior similar to the addition operation,
439except that Lua will try a metamethod
440if any operand is neither a string nor a number
441(which is always coercible to a string).
442}
443
444@item{@idx{__len}|
445the length (@T{#}) operation.
446If the object is not a string,
447Lua will try its metamethod.
448If there is a metamethod,
449Lua calls it with the object as argument,
450and the result of the call
451(always adjusted to one value)
452is the result of the operation.
453If there is no metamethod but the object is a table,
454then Lua uses the table length operation @see{len-op}.
455Otherwise, Lua raises an error.
456}
457
458@item{@idx{__eq}|
459the equal (@T{==}) operation.
460Behavior similar to the addition operation,
461except that Lua will try a metamethod only when the values
462being compared are either both tables or both full userdata
463and they are not primitively equal.
464The result of the call is always converted to a boolean.
465}
466
467@item{@idx{__lt}|
468the less than (@T{<}) operation.
469Behavior similar to the addition operation,
470except that Lua will try a metamethod only when the values
471being compared are neither both numbers nor both strings.
472The result of the call is always converted to a boolean.
473}
474
475@item{@idx{__le}|
476the less equal (@T{<=}) operation.
477Unlike other operations,
478the less-equal operation can use two different events.
479First, Lua looks for the @idx{__le} metamethod in both operands,
480like in the less than operation.
481If it cannot find such a metamethod,
482then it will try the @idx{__lt} metamethod,
483assuming that @T{a <= b} is equivalent to @T{not (b < a)}.
484As with the other comparison operators,
485the result is always a boolean.
486(This use of the @idx{__lt} event can be removed in future versions;
487it is also slower than a real @idx{__le} metamethod.)
488}
489
490@item{@idx{__index}|
491The indexing access operation @T{table[key]}.
492This event happens when @id{table} is not a table or
493when @id{key} is not present in @id{table}.
494The metamethod is looked up in @id{table}.
495
496Despite the name,
497the metamethod for this event can be either a function or a table.
498If it is a function,
499it is called with @id{table} and @id{key} as arguments,
500and the result of the call
501(adjusted to one value)
502is the result of the operation.
503If it is a table,
504the final result is the result of indexing this table with @id{key}.
505(This indexing is regular, not raw,
506and therefore can trigger another metamethod.)
507}
508
509@item{@idx{__newindex}|
510The indexing assignment @T{table[key] = value}.
511Like the index event,
512this event happens when @id{table} is not a table or
513when @id{key} is not present in @id{table}.
514The metamethod is looked up in @id{table}.
515
516Like with indexing,
517the metamethod for this event can be either a function or a table.
518If it is a function,
519it is called with @id{table}, @id{key}, and @id{value} as arguments.
520If it is a table,
521Lua does an indexing assignment to this table with the same key and value.
522(This assignment is regular, not raw,
523and therefore can trigger another metamethod.)
524
525Whenever there is a @idx{__newindex} metamethod,
526Lua does not perform the primitive assignment.
527(If necessary,
528the metamethod itself can call @Lid{rawset}
529to do the assignment.)
530}
531
532@item{@idx{__call}|
533The call operation @T{func(args)}.
534This event happens when Lua tries to call a non-function value
535(that is, @id{func} is not a function).
536The metamethod is looked up in @id{func}.
537If present,
538the metamethod is called with @id{func} as its first argument,
539followed by the arguments of the original call (@id{args}).
540All results of the call
541are the result of the operation.
542(This is the only metamethod that allows multiple results.)
543}
544
545}
546
547It is a good practice to add all needed metamethods to a table
548before setting it as a metatable of some object.
549In particular, the @idx{__gc} metamethod works only when this order
550is followed @see{finalizers}.
551
552Because metatables are regular tables,
553they can contain arbitrary fields,
554not only the event names defined above.
555Some functions in the standard library
556(e.g., @Lid{tostring})
557use other fields in metatables for their own purposes.
558
559}
560
561@sect2{GC| @title{Garbage Collection}
562
563Lua performs automatic memory management.
564This means that
565you do not have to worry about allocating memory for new objects
566or freeing it when the objects are no longer needed.
567Lua manages memory automatically by running
568a @def{garbage collector} to collect all @emph{dead objects}
569(that is, objects that are no longer accessible from Lua).
570All memory used by Lua is subject to automatic management:
571strings, tables, userdata, functions, threads, internal structures, etc.
572
573The garbage collector (GC) in Lua can work in two modes:
574incremental and generational.
575
576The default GC mode with the default parameters
577are adequate for most uses.
578Programs that waste a large proportion of its time
579allocating and freeing memory can benefit from other settings.
580Keep in mind that the GC behavior is non-portable
581both across platforms and across different Lua releases;
582therefore, optimal settings are also non-portable.
583
584You can change the GC mode and parameters by calling
585@Lid{lua_gc} in C
586or @Lid{collectgarbage} in Lua.
587You can also use these functions to control
588the collector directly (e.g., stop and restart it).
589
590@sect3{@title{Incremental Garbage Collection}
591
592In incremental mode,
593each GC cycle performs a mark-and-sweep collection in small steps
594interleaved with the program's execution.
595In this mode,
596the collector uses three numbers to control its garbage-collection cycles:
597the @def{garbage-collector pause},
598the @def{garbage-collector step multiplier},
599and the @def{garbage-collector step size}.
600
601The garbage-collector pause
602controls how long the collector waits before starting a new cycle.
603The collector starts a new cycle when the use of memory
604hits @M{n%} of the use after the previous collection.
605Larger values make the collector less aggressive.
606Values smaller than 100 mean the collector will not wait to
607start a new cycle.
608A value of 200 means that the collector waits for the total memory in use
609to double before starting a new cycle.
610The default value is 200; the maximum value is 1000.
611
612The garbage-collector step multiplier
613controls the relative speed of the collector relative to
614memory allocation,
615that is,
616how many elements it marks or sweeps for each
617kilobyte of memory allocated.
618Larger values make the collector more aggressive but also increase
619the size of each incremental step.
620You should not use values smaller than 100,
621because they make the collector too slow and
622can result in the collector never finishing a cycle.
623The default value is 100; the maximum value is 1000.
624
625The garbage-collector step size controls the
626size of each incremental step,
627specifically how many bytes the interpreter allocates
628before performing a step.
629This parameter is logarithmic:
630A value of @M{n} means the interpreter will allocate @M{2@sp{n}}
631bytes between steps and perform equivalent work during the step.
632A large value (e.g., 60) makes the collector a stop-the-world
633(non-incremental) collector.
634The default value is 13,
635which makes for steps of approximately @N{8 Kbytes}.
636
637}
638
639@sect3{@title{Generational Garbage Collection}
640
641In generational mode,
642the collector does frequent @emph{minor} collections,
643which traverses only objects recently created.
644If after a minor collection the use of memory is still above a limit,
645the collector does a @emph{major} collection,
646which traverses all objects.
647The generational mode uses two parameters:
648the @def{major multiplier} and the @def{the minor multiplier}.
649
650The major multiplier controls the frequency of major collections.
651For a major multiplier @M{x},
652a new major collection will be done when memory
653grows @M{x%} larger than the memory in use after the previous major
654collection.
655For instance, for a multiplier of 100,
656the collector will do a major collection when the use of memory
657gets larger than twice the use after the previous collection.
658The default value is 100; the maximum value is 1000.
659
660The minor multiplier controls the frequency of minor collections.
661For a minor multiplier @M{x},
662a new minor collection will be done when memory
663grows @M{x%} larger than the memory in use after the previous major
664collection.
665For instance, for a multiplier of 20,
666the collector will do a minor collection when the use of memory
667gets 20% larger than the use after the previous major collection.
668The default value is 20; the maximum value is 200.
669
670}
671
672@sect3{finalizers| @title{Garbage-Collection Metamethods}
673
674You can set garbage-collector metamethods for tables
675and, using the @N{C API},
676for full userdata @see{metatable}.
677These metamethods are also called @def{finalizers}.
678Finalizers allow you to coordinate Lua's garbage collection
679with external resource management
680(such as closing files, network or database connections,
681or freeing your own memory).
682
683For an object (table or userdata) to be finalized when collected,
684you must @emph{mark} it for finalization.
685@index{mark (for finalization)}
686You mark an object for finalization when you set its metatable
687and the metatable has a field indexed by the string @St{__gc}.
688Note that if you set a metatable without a @idx{__gc} field
689and later create that field in the metatable,
690the object will not be marked for finalization.
691
692When a marked object becomes garbage,
693it is not collected immediately by the garbage collector.
694Instead, Lua puts it in a list.
695After the collection,
696Lua goes through that list.
697For each object in the list,
698it checks the object's @idx{__gc} metamethod:
699If it is a function,
700Lua calls it with the object as its single argument;
701if the metamethod is not a function,
702Lua simply ignores it.
703
704At the end of each garbage-collection cycle,
705the finalizers for objects are called in
706the reverse order that the objects were marked for finalization,
707among those collected in that cycle;
708that is, the first finalizer to be called is the one associated
709with the object marked last in the program.
710The execution of each finalizer may occur at any point during
711the execution of the regular code.
712
713Because the object being collected must still be used by the finalizer,
714that object (and other objects accessible only through it)
715must be @emph{resurrected} by Lua.@index{resurrection}
716Usually, this resurrection is transient,
717and the object memory is freed in the next garbage-collection cycle.
718However, if the finalizer stores the object in some global place
719(e.g., a global variable),
720then the resurrection is permanent.
721Moreover, if the finalizer marks a finalizing object for finalization again,
722its finalizer will be called again in the next cycle where the
723object is unreachable.
724In any case,
725the object memory is freed only in a GC cycle where
726the object is unreachable and not marked for finalization.
727
728When you close a state @seeF{lua_close},
729Lua calls the finalizers of all objects marked for finalization,
730following the reverse order that they were marked.
731If any finalizer marks objects for collection during that phase,
732these marks have no effect.
733
734}
735
736@sect3{weak-table| @title{Weak Tables}
737
738A @def{weak table} is a table whose elements are
739@def{weak references}.
740A weak reference is ignored by the garbage collector.
741In other words,
742if the only references to an object are weak references,
743then the garbage collector will collect that object.
744
745A weak table can have weak keys, weak values, or both.
746A table with weak values allows the collection of its values,
747but prevents the collection of its keys.
748A table with both weak keys and weak values allows the collection of
749both keys and values.
750In any case, if either the key or the value is collected,
751the whole pair is removed from the table.
752The weakness of a table is controlled by the
753@idx{__mode} field of its metatable.
754This field, if present, must be one of the following strings:
755@St{k}, for a table with weak keys;
756@St{v}, for a table with weak values;
757or @St{kv}, for a table with both weak keys and values.
758
759A table with weak keys and strong values
760is also called an @def{ephemeron table}.
761In an ephemeron table,
762a value is considered reachable only if its key is reachable.
763In particular,
764if the only reference to a key comes through its value,
765the pair is removed.
766
767Any change in the weakness of a table may take effect only
768at the next collect cycle.
769In particular, if you change the weakness to a stronger mode,
770Lua may still collect some items from that table
771before the change takes effect.
772
773Only objects that have an explicit construction
774are removed from weak tables.
775Values, such as numbers and @x{light @N{C functions}},
776are not subject to garbage collection,
777and therefore are not removed from weak tables
778(unless their associated values are collected).
779Although strings are subject to garbage collection,
780they do not have an explicit construction,
781and therefore are not removed from weak tables.
782
783Resurrected objects
784(that is, objects being finalized
785and objects accessible only through objects being finalized)
786have a special behavior in weak tables.
787They are removed from weak values before running their finalizers,
788but are removed from weak keys only in the next collection
789after running their finalizers, when such objects are actually freed.
790This behavior allows the finalizer to access properties
791associated with the object through weak tables.
792
793If a weak table is among the resurrected objects in a collection cycle,
794it may not be properly cleared until the next cycle.
795
796}
797
798}
799
800@sect2{coroutine| @title{Coroutines}
801
802Lua supports coroutines,
803also called @emphx{collaborative multithreading}.
804A coroutine in Lua represents an independent thread of execution.
805Unlike threads in multithread systems, however,
806a coroutine only suspends its execution by explicitly calling
807a yield function.
808
809You create a coroutine by calling @Lid{coroutine.create}.
810Its sole argument is a function
811that is the main function of the coroutine.
812The @id{create} function only creates a new coroutine and
813returns a handle to it (an object of type @emph{thread});
814it does not start the coroutine.
815
816You execute a coroutine by calling @Lid{coroutine.resume}.
817When you first call @Lid{coroutine.resume},
818passing as its first argument
819a thread returned by @Lid{coroutine.create},
820the coroutine starts its execution by
821calling its main function.
822Extra arguments passed to @Lid{coroutine.resume} are passed
823as arguments to that function.
824After the coroutine starts running,
825it runs until it terminates or @emph{yields}.
826
827A coroutine can terminate its execution in two ways:
828normally, when its main function returns
829(explicitly or implicitly, after the last instruction);
830and abnormally, if there is an unprotected error.
831In case of normal termination,
832@Lid{coroutine.resume} returns @true,
833plus any values returned by the coroutine main function.
834In case of errors, @Lid{coroutine.resume} returns @false
835plus an error object.
836
837A coroutine yields by calling @Lid{coroutine.yield}.
838When a coroutine yields,
839the corresponding @Lid{coroutine.resume} returns immediately,
840even if the yield happens inside nested function calls
841(that is, not in the main function,
842but in a function directly or indirectly called by the main function).
843In the case of a yield, @Lid{coroutine.resume} also returns @true,
844plus any values passed to @Lid{coroutine.yield}.
845The next time you resume the same coroutine,
846it continues its execution from the point where it yielded,
847with the call to @Lid{coroutine.yield} returning any extra
848arguments passed to @Lid{coroutine.resume}.
849
850Like @Lid{coroutine.create},
851the @Lid{coroutine.wrap} function also creates a coroutine,
852but instead of returning the coroutine itself,
853it returns a function that, when called, resumes the coroutine.
854Any arguments passed to this function
855go as extra arguments to @Lid{coroutine.resume}.
856@Lid{coroutine.wrap} returns all the values returned by @Lid{coroutine.resume},
857except the first one (the boolean error code).
858Unlike @Lid{coroutine.resume},
859@Lid{coroutine.wrap} does not catch errors;
860any error is propagated to the caller.
861
862As an example of how coroutines work,
863consider the following code:
864@verbatim{
865function foo (a)
866 print("foo", a)
867 return coroutine.yield(2*a)
868end
869
870co = coroutine.create(function (a,b)
871 print("co-body", a, b)
872 local r = foo(a+1)
873 print("co-body", r)
874 local r, s = coroutine.yield(a+b, a-b)
875 print("co-body", r, s)
876 return b, "end"
877end)
878
879print("main", coroutine.resume(co, 1, 10))
880print("main", coroutine.resume(co, "r"))
881print("main", coroutine.resume(co, "x", "y"))
882print("main", coroutine.resume(co, "x", "y"))
883}
884When you run it, it produces the following output:
885@verbatim{
886co-body 1 10
887foo 2
888main true 4
889co-body r
890main true 11 -9
891co-body x y
892main true 10 end
893main false cannot resume dead coroutine
894}
895
896You can also create and manipulate coroutines through the C API:
897see functions @Lid{lua_newthread}, @Lid{lua_resume},
898and @Lid{lua_yield}.
899
900}
901
902}
903
904
905@C{-------------------------------------------------------------------------}
906@sect1{language| @title{The Language}
907
908This section describes the lexis, the syntax, and the semantics of Lua.
909In other words,
910this section describes
911which tokens are valid,
912how they can be combined,
913and what their combinations mean.
914
915Language constructs will be explained using the usual extended BNF notation,
916in which
917@N{@bnfrep{@rep{a}} means 0} or more @rep{a}'s, and
918@N{@bnfopt{@rep{a}} means} an optional @rep{a}.
919Non-terminals are shown like @bnfNter{non-terminal},
920keywords are shown like @rw{kword},
921and other terminal symbols are shown like @bnfter{=}.
922The complete syntax of Lua can be found in @refsec{BNF}
923at the end of this manual.
924
925@sect2{lexical| @title{Lexical Conventions}
926
927Lua is a @x{free-form} language.
928It ignores spaces (including new lines) and comments
929between lexical elements (@x{tokens}),
930except as delimiters between @x{names} and @x{keywords}.
931
932@def{Names}
933(also called @def{identifiers})
934in Lua can be any string of letters,
935digits, and underscores,
936not beginning with a digit and
937not being a reserved word.
938Identifiers are used to name variables, table fields, and labels.
939
940The following @def{keywords} are reserved
941and cannot be used as names:
942@index{reserved words}
943@verbatim{
944and break do else elseif end
945false for function goto if in
946local nil not or repeat return
947then true until while
948}
949
950Lua is a case-sensitive language:
951@id{and} is a reserved word, but @id{And} and @id{AND}
952are two different, valid names.
953As a convention,
954programs should avoid creating
955names that start with an underscore followed by
956one or more uppercase letters (such as @Lid{_VERSION}).
957
958The following strings denote other @x{tokens}:
959@verbatim{
960+ - * / % ^ #
961& ~ | << >> //
962== ~= <= >= < > =
963( ) { } [ ] ::
964; : , . .. ...
965}
966
967A @def{short literal string}
968can be delimited by matching single or double quotes,
969and can contain the following C-like escape sequences:
970@Char{\a} (bell),
971@Char{\b} (backspace),
972@Char{\f} (form feed),
973@Char{\n} (newline),
974@Char{\r} (carriage return),
975@Char{\t} (horizontal tab),
976@Char{\v} (vertical tab),
977@Char{\\} (backslash),
978@Char{\"} (quotation mark [double quote]),
979and @Char{\'} (apostrophe [single quote]).
980A backslash followed by a line break
981results in a newline in the string.
982The escape sequence @Char{\z} skips the following span
983of white-space characters,
984including line breaks;
985it is particularly useful to break and indent a long literal string
986into multiple lines without adding the newlines and spaces
987into the string contents.
988A short literal string cannot contain unescaped line breaks
989nor escapes not forming a valid escape sequence.
990
991We can specify any byte in a short literal string,
992including @x{embedded zeros},
993by its numeric value.
994This can be done
995with the escape sequence @T{\x@rep{XX}},
996where @rep{XX} is a sequence of exactly two hexadecimal digits,
997or with the escape sequence @T{\@rep{ddd}},
998where @rep{ddd} is a sequence of up to three decimal digits.
999(Note that if a decimal escape sequence is to be followed by a digit,
1000it must be expressed using exactly three digits.)
1001
1002The @x{UTF-8} encoding of a @x{Unicode} character
1003can be inserted in a literal string with
1004the escape sequence @T{\u{@rep{XXX}}}
1005(note the mandatory enclosing brackets),
1006where @rep{XXX} is a sequence of one or more hexadecimal digits
1007representing the character code point.
1008
1009Literal strings can also be defined using a long format
1010enclosed by @def{long brackets}.
1011We define an @def{opening long bracket of level @rep{n}} as an opening
1012square bracket followed by @rep{n} equal signs followed by another
1013opening square bracket.
1014So, an opening long bracket of @N{level 0} is written as @T{[[}, @C{]]}
1015an opening long bracket of @N{level 1} is written as @T{[=[}, @C{]]}
1016and so on.
1017A @emph{closing long bracket} is defined similarly;
1018for instance,
1019a closing long bracket of @N{level 4} is written as @C{[[} @T{]====]}.
1020A @def{long literal} starts with an opening long bracket of any level and
1021ends at the first closing long bracket of the same level.
1022It can contain any text except a closing bracket of the same level.
1023Literals in this bracketed form can run for several lines,
1024do not interpret any escape sequences,
1025and ignore long brackets of any other level.
1026Any kind of end-of-line sequence
1027(carriage return, newline, carriage return followed by newline,
1028or newline followed by carriage return)
1029is converted to a simple newline.
1030
1031For convenience,
1032when the opening long bracket is immediately followed by a newline,
1033the newline is not included in the string.
1034As an example, in a system using ASCII
1035(in which @Char{a} is coded @N{as 97},
1036newline is coded @N{as 10}, and @Char{1} is coded @N{as 49}),
1037the five literal strings below denote the same string:
1038@verbatim{
1039a = 'alo\n123"'
1040a = "alo\n123\""
1041a = '\97lo\10\04923"'
1042a = [[alo
1043123"]]
1044a = [==[
1045alo
1046123"]==]
1047}
1048
1049Any byte in a literal string not
1050explicitly affected by the previous rules represents itself.
1051However, Lua opens files for parsing in text mode,
1052and the system file functions may have problems with
1053some control characters.
1054So, it is safer to represent
1055non-text data as a quoted literal with
1056explicit escape sequences for the non-text characters.
1057
1058A @def{numeric constant} (or @def{numeral})
1059can be written with an optional fractional part
1060and an optional decimal exponent,
1061marked by a letter @Char{e} or @Char{E}.
1062Lua also accepts @x{hexadecimal constants},
1063which start with @T{0x} or @T{0X}.
1064Hexadecimal constants also accept an optional fractional part
1065plus an optional binary exponent,
1066marked by a letter @Char{p} or @Char{P}.
1067A numeric constant with a radix point or an exponent
1068denotes a float;
1069otherwise,
1070if its value fits in an integer,
1071it denotes an integer.
1072Examples of valid integer constants are
1073@verbatim{
10743 345 0xff 0xBEBADA
1075}
1076Examples of valid float constants are
1077@verbatim{
10783.0 3.1416 314.16e-2 0.31416E1 34e1
10790x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1080}
1081
1082A @def{comment} starts with a double hyphen (@T{--})
1083anywhere outside a string.
1084If the text immediately after @T{--} is not an opening long bracket,
1085the comment is a @def{short comment},
1086which runs until the end of the line.
1087Otherwise, it is a @def{long comment},
1088which runs until the corresponding closing long bracket.
1089
1090}
1091
1092@sect2{variables| @title{Variables}
1093
1094Variables are places that store values.
1095There are three kinds of variables in Lua:
1096global variables, local variables, and table fields.
1097
1098A single name can denote a global variable or a local variable
1099(or a function's formal parameter,
1100which is a particular kind of local variable):
1101@Produc{
1102@producname{var}@producbody{@bnfNter{Name}}
1103}
1104@bnfNter{Name} denotes identifiers, as defined in @See{lexical}.
1105
1106Any variable name is assumed to be global unless explicitly declared
1107as a local @see{localvar}.
1108@x{Local variables} are @emph{lexically scoped}:
1109local variables can be freely accessed by functions
1110defined inside their scope @see{visibility}.
1111
1112Before the first assignment to a variable, its value is @nil.
1113
1114Square brackets are used to index a table:
1115@Produc{
1116@producname{var}@producbody{prefixexp @bnfter{[} exp @bnfter{]}}
1117}
1118The meaning of accesses to table fields can be changed via metatables
1119@see{metatable}.
1120
1121The syntax @id{var.Name} is just syntactic sugar for
1122@T{var["Name"]}:
1123@Produc{
1124@producname{var}@producbody{prefixexp @bnfter{.} @bnfNter{Name}}
1125}
1126
1127An access to a global variable @id{x}
1128is equivalent to @id{_ENV.x}.
1129Due to the way that chunks are compiled,
1130the variable @id{_ENV} itself is never global @see{globalenv}.
1131
1132}
1133
1134@sect2{stats| @title{Statements}
1135
1136Lua supports an almost conventional set of @x{statements},
1137similar to those in Pascal or C.
1138This set includes
1139assignments, control structures, function calls,
1140and variable declarations.
1141
1142@sect3{@title{Blocks}
1143
1144A @x{block} is a list of statements,
1145which are executed sequentially:
1146@Produc{
1147@producname{block}@producbody{@bnfrep{stat}}
1148}
1149Lua has @def{empty statements}
1150that allow you to separate statements with semicolons,
1151start a block with a semicolon
1152or write two semicolons in sequence:
1153@Produc{
1154@producname{stat}@producbody{@bnfter{;}}
1155}
1156
1157Function calls and assignments
1158can start with an open parenthesis.
1159This possibility leads to an ambiguity in Lua's grammar.
1160Consider the following fragment:
1161@verbatim{
1162a = b + c
1163(print or io.write)('done')
1164}
1165The grammar could see it in two ways:
1166@verbatim{
1167a = b + c(print or io.write)('done')
1168
1169a = b + c; (print or io.write)('done')
1170}
1171The current parser always sees such constructions
1172in the first way,
1173interpreting the open parenthesis
1174as the start of the arguments to a call.
1175To avoid this ambiguity,
1176it is a good practice to always precede with a semicolon
1177statements that start with a parenthesis:
1178@verbatim{
1179;(print or io.write)('done')
1180}
1181
1182A block can be explicitly delimited to produce a single statement:
1183@Produc{
1184@producname{stat}@producbody{@Rw{do} block @Rw{end}}
1185}
1186Explicit blocks are useful
1187to control the scope of variable declarations.
1188Explicit blocks are also sometimes used to
1189add a @Rw{return} statement in the middle
1190of another block @see{control}.
1191
1192}
1193
1194@sect3{chunks| @title{Chunks}
1195
1196The unit of compilation of Lua is called a @def{chunk}.
1197Syntactically,
1198a chunk is simply a block:
1199@Produc{
1200@producname{chunk}@producbody{block}
1201}
1202
1203Lua handles a chunk as the body of an anonymous function
1204with a variable number of arguments
1205@see{func-def}.
1206As such, chunks can define local variables,
1207receive arguments, and return values.
1208Moreover, such anonymous function is compiled as in the
1209scope of an external local variable called @id{_ENV} @see{globalenv}.
1210The resulting function always has @id{_ENV} as its only upvalue,
1211even if it does not use that variable.
1212
1213A chunk can be stored in a file or in a string inside the host program.
1214To execute a chunk,
1215Lua first @emph{loads} it,
1216precompiling the chunk's code into instructions for a virtual machine,
1217and then Lua executes the compiled code
1218with an interpreter for the virtual machine.
1219
1220Chunks can also be precompiled into binary form;
1221see program @idx{luac} and function @Lid{string.dump} for details.
1222Programs in source and compiled forms are interchangeable;
1223Lua automatically detects the file type and acts accordingly @seeF{load}.
1224
1225}
1226
1227@sect3{assignment| @title{Assignment}
1228
1229Lua allows @x{multiple assignments}.
1230Therefore, the syntax for assignment
1231defines a list of variables on the left side
1232and a list of expressions on the right side.
1233The elements in both lists are separated by commas:
1234@Produc{
1235@producname{stat}@producbody{varlist @bnfter{=} explist}
1236@producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
1237@producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
1238}
1239Expressions are discussed in @See{expressions}.
1240
1241Before the assignment,
1242the list of values is @emph{adjusted} to the length of
1243the list of variables.@index{adjustment}
1244If there are more values than needed,
1245the excess values are thrown away.
1246If there are fewer values than needed,
1247the list is extended with as many @nil's as needed.
1248If the list of expressions ends with a function call,
1249then all values returned by that call enter the list of values,
1250before the adjustment
1251(except when the call is enclosed in parentheses; see @See{expressions}).
1252
1253The assignment statement first evaluates all its expressions
1254and only then the assignments are performed.
1255Thus the code
1256@verbatim{
1257i = 3
1258i, a[i] = i+1, 20
1259}
1260sets @T{a[3]} to 20, without affecting @T{a[4]}
1261because the @id{i} in @T{a[i]} is evaluated (to 3)
1262before it is @N{assigned 4}.
1263Similarly, the line
1264@verbatim{
1265x, y = y, x
1266}
1267exchanges the values of @id{x} and @id{y},
1268and
1269@verbatim{
1270x, y, z = y, z, x
1271}
1272cyclically permutes the values of @id{x}, @id{y}, and @id{z}.
1273
1274An assignment to a global name @T{x = val}
1275is equivalent to the assignment
1276@T{_ENV.x = val} @see{globalenv}.
1277
1278The meaning of assignments to table fields and
1279global variables (which are actually table fields, too)
1280can be changed via metatables @see{metatable}.
1281
1282}
1283
1284@sect3{control| @title{Control Structures}
1285The control structures
1286@Rw{if}, @Rw{while}, and @Rw{repeat} have the usual meaning and
1287familiar syntax:
1288@index{while-do statement}
1289@index{repeat-until statement}
1290@index{if-then-else statement}
1291@Produc{
1292@producname{stat}@producbody{@Rw{while} exp @Rw{do} block @Rw{end}}
1293@producname{stat}@producbody{@Rw{repeat} block @Rw{until} exp}
1294@producname{stat}@producbody{@Rw{if} exp @Rw{then} block
1295 @bnfrep{@Rw{elseif} exp @Rw{then} block}
1296 @bnfopt{@Rw{else} block} @Rw{end}}
1297}
1298Lua also has a @Rw{for} statement, in two flavors @see{for}.
1299
1300The @x{condition expression} of a
1301control structure can return any value.
1302Both @false and @nil test false.
1303All values different from @nil and @false test true.
1304(In particular, the number 0 and the empty string also test true).
1305
1306In the @Rw{repeat}@En@Rw{until} loop,
1307the inner block does not end at the @Rw{until} keyword,
1308but only after the condition.
1309So, the condition can refer to local variables
1310declared inside the loop block.
1311
1312The @Rw{goto} statement transfers the program control to a label.
1313For syntactical reasons,
1314labels in Lua are considered statements too:
1315@index{goto statement}
1316@index{label}
1317@Produc{
1318@producname{stat}@producbody{@Rw{goto} Name}
1319@producname{stat}@producbody{label}
1320@producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
1321}
1322
1323A label is visible in the entire block where it is defined,
1324except
1325inside nested blocks where a label with the same name is defined and
1326inside nested functions.
1327A goto may jump to any visible label as long as it does not
1328enter into the scope of a local variable.
1329
1330Labels and empty statements are called @def{void statements},
1331as they perform no actions.
1332
1333The @Rw{break} statement terminates the execution of a
1334@Rw{while}, @Rw{repeat}, or @Rw{for} loop,
1335skipping to the next statement after the loop:
1336@index{break statement}
1337@Produc{
1338@producname{stat}@producbody{@Rw{break}}
1339}
1340A @Rw{break} ends the innermost enclosing loop.
1341
1342The @Rw{return} statement is used to return values
1343from a function or a chunk
1344(which is an anonymous function).
1345@index{return statement}
1346Functions can return more than one value,
1347so the syntax for the @Rw{return} statement is
1348@Produc{
1349@producname{stat}@producbody{@Rw{return} @bnfopt{explist} @bnfopt{@bnfter{;}}}
1350}
1351
1352The @Rw{return} statement can only be written
1353as the last statement of a block.
1354If it is really necessary to @Rw{return} in the middle of a block,
1355then an explicit inner block can be used,
1356as in the idiom @T{do return end},
1357because now @Rw{return} is the last statement in its (inner) block.
1358
1359}
1360
1361@sect3{for| @title{For Statement}
1362
1363@index{for statement}
1364The @Rw{for} statement has two forms:
1365one numerical and one generic.
1366
1367The numerical @Rw{for} loop repeats a block of code while a
1368control variable runs through an arithmetic progression.
1369It has the following syntax:
1370@Produc{
1371@producname{stat}@producbody{@Rw{for} @bnfNter{Name} @bnfter{=}
1372 exp @bnfter{,} exp @bnfopt{@bnfter{,} exp} @Rw{do} block @Rw{end}}
1373}
1374The @emph{block} is repeated for @emph{name} starting at the value of
1375the first @emph{exp}, until it passes the second @emph{exp} by steps of the
1376third @emph{exp}.
1377More precisely, a @Rw{for} statement like
1378@verbatim{
1379for v = @rep{e1}, @rep{e2}, @rep{e3} do @rep{block} end
1380}
1381is equivalent to the code:
1382@verbatim{
1383do
1384 local @rep{var}, @rep{limit}, @rep{step} = tonumber(@rep{e1}), tonumber(@rep{e2}), tonumber(@rep{e3})
1385 if not (@rep{var} and @rep{limit} and @rep{step}) then error() end
1386 @rep{var} = @rep{var} - @rep{step}
1387 while true do
1388 @rep{var} = @rep{var} + @rep{step}
1389 if (@rep{step} >= 0 and @rep{var} > @rep{limit}) or (@rep{step} < 0 and @rep{var} < @rep{limit}) then
1390 break
1391 end
1392 local v = @rep{var}
1393 @rep{block}
1394 end
1395end
1396}
1397
1398Note the following:
1399@itemize{
1400
1401@item{
1402All three control expressions are evaluated only once,
1403before the loop starts.
1404They must all result in numbers.
1405}
1406
1407@item{
1408@T{@rep{var}}, @T{@rep{limit}}, and @T{@rep{step}} are invisible variables.
1409The names shown here are for explanatory purposes only.
1410}
1411
1412@item{
1413If the third expression (the step) is absent,
1414then a step @N{of 1} is used.
1415}
1416
1417@item{
1418You can use @Rw{break} and @Rw{goto} to exit a @Rw{for} loop.
1419}
1420
1421@item{
1422The loop variable @T{v} is local to the loop body.
1423If you need its value after the loop,
1424assign it to another variable before exiting the loop.
1425}
1426
1427@item{
1428The values in @rep{var}, @rep{limit}, and @rep{step}
1429can be integers or floats.
1430All operations on them respect the usual rules in Lua.
1431}
1432
1433}
1434
1435The generic @Rw{for} statement works over functions,
1436called @def{iterators}.
1437On each iteration, the iterator function is called to produce a new value,
1438stopping when this new value is @nil.
1439The generic @Rw{for} loop has the following syntax:
1440@Produc{
1441@producname{stat}@producbody{@Rw{for} namelist @Rw{in} explist
1442 @Rw{do} block @Rw{end}}
1443@producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
1444}
1445A @Rw{for} statement like
1446@verbatim{
1447for @rep{var_1}, @Cdots, @rep{var_n} in @rep{explist} do @rep{block} end
1448}
1449is equivalent to the code:
1450@verbatim{
1451do
1452 local @rep{f}, @rep{s}, @rep{var} = @rep{explist}
1453 while true do
1454 local @rep{var_1}, @Cdots, @rep{var_n} = @rep{f}(@rep{s}, @rep{var})
1455 if @rep{var_1} == nil then break end
1456 @rep{var} = @rep{var_1}
1457 @rep{block}
1458 end
1459end
1460}
1461Note the following:
1462@itemize{
1463
1464@item{
1465@T{@rep{explist}} is evaluated only once.
1466Its results are an @emph{iterator} function,
1467a @emph{state},
1468and an initial value for the first @emph{iterator variable}.
1469}
1470
1471@item{
1472@T{@rep{f}}, @T{@rep{s}}, and @T{@rep{var}} are invisible variables.
1473The names are here for explanatory purposes only.
1474}
1475
1476@item{
1477You can use @Rw{break} to exit a @Rw{for} loop.
1478}
1479
1480@item{
1481The loop variables @T{@rep{var_i}} are local to the loop;
1482you cannot use their values after the @Rw{for} ends.
1483If you need these values,
1484then assign them to other variables before breaking or exiting the loop.
1485}
1486
1487}
1488
1489}
1490
1491@sect3{funcstat| @title{Function Calls as Statements}
1492To allow possible side-effects,
1493function calls can be executed as statements:
1494@Produc{
1495@producname{stat}@producbody{functioncall}
1496}
1497In this case, all returned values are thrown away.
1498Function calls are explained in @See{functioncall}.
1499
1500}
1501
1502@sect3{localvar| @title{Local Declarations}
1503@x{Local variables} can be declared anywhere inside a block.
1504The declaration can include an initial assignment:
1505@Produc{
1506@producname{stat}@producbody{@Rw{local} namelist @bnfopt{@bnfter{=} explist}}
1507}
1508If present, an initial assignment has the same semantics
1509of a multiple assignment @see{assignment}.
1510Otherwise, all variables are initialized with @nil.
1511
1512A chunk is also a block @see{chunks},
1513and so local variables can be declared in a chunk outside any explicit block.
1514
1515The visibility rules for local variables are explained in @See{visibility}.
1516
1517}
1518
1519}
1520
1521@sect2{expressions| @title{Expressions}
1522
1523The basic expressions in Lua are the following:
1524@Produc{
1525@producname{exp}@producbody{prefixexp}
1526@producname{exp}@producbody{@Rw{nil} @Or @Rw{false} @Or @Rw{true}}
1527@producname{exp}@producbody{@bnfNter{Numeral}}
1528@producname{exp}@producbody{@bnfNter{LiteralString}}
1529@producname{exp}@producbody{functiondef}
1530@producname{exp}@producbody{tableconstructor}
1531@producname{exp}@producbody{@bnfter{...}}
1532@producname{exp}@producbody{exp binop exp}
1533@producname{exp}@producbody{unop exp}
1534@producname{prefixexp}@producbody{var @Or functioncall @Or
1535 @bnfter{(} exp @bnfter{)}}
1536}
1537
1538Numerals and literal strings are explained in @See{lexical};
1539variables are explained in @See{variables};
1540function definitions are explained in @See{func-def};
1541function calls are explained in @See{functioncall};
1542table constructors are explained in @See{tableconstructor}.
1543Vararg expressions,
1544denoted by three dots (@Char{...}), can only be used when
1545directly inside a vararg function;
1546they are explained in @See{func-def}.
1547
1548Binary operators comprise arithmetic operators @see{arith},
1549bitwise operators @see{bitwise},
1550relational operators @see{rel-ops}, logical operators @see{logic},
1551and the concatenation operator @see{concat}.
1552Unary operators comprise the unary minus @see{arith},
1553the unary bitwise NOT @see{bitwise},
1554the unary logical @Rw{not} @see{logic},
1555and the unary @def{length operator} @see{len-op}.
1556
1557Both function calls and vararg expressions can result in multiple values.
1558If a function call is used as a statement @see{funcstat},
1559then its return list is adjusted to zero elements,
1560thus discarding all returned values.
1561If an expression is used as the last (or the only) element
1562of a list of expressions,
1563then no adjustment is made
1564(unless the expression is enclosed in parentheses).
1565In all other contexts,
1566Lua adjusts the result list to one element,
1567either discarding all values except the first one
1568or adding a single @nil if there are no values.
1569
1570Here are some examples:
1571@verbatim{
1572f() -- adjusted to 0 results
1573g(f(), x) -- f() is adjusted to 1 result
1574g(x, f()) -- g gets x plus all results from f()
1575a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
1576a,b = ... -- a gets the first vararg argument, b gets
1577 -- the second (both a and b can get nil if there
1578 -- is no corresponding vararg argument)
1579
1580a,b,c = x, f() -- f() is adjusted to 2 results
1581a,b,c = f() -- f() is adjusted to 3 results
1582return f() -- returns all results from f()
1583return ... -- returns all received vararg arguments
1584return x,y,f() -- returns x, y, and all results from f()
1585{f()} -- creates a list with all results from f()
1586{...} -- creates a list with all vararg arguments
1587{f(), nil} -- f() is adjusted to 1 result
1588}
1589
1590Any expression enclosed in parentheses always results in only one value.
1591Thus,
1592@T{(f(x,y,z))} is always a single value,
1593even if @id{f} returns several values.
1594(The value of @T{(f(x,y,z))} is the first value returned by @id{f}
1595or @nil if @id{f} does not return any values.)
1596
1597
1598
1599@sect3{arith| @title{Arithmetic Operators}
1600Lua supports the following @x{arithmetic operators}:
1601@description{
1602@item{@T{+}|addition}
1603@item{@T{-}|subtraction}
1604@item{@T{*}|multiplication}
1605@item{@T{/}|float division}
1606@item{@T{//}|floor division}
1607@item{@T{%}|modulo}
1608@item{@T{^}|exponentiation}
1609@item{@T{-}|unary minus}
1610}
1611
1612With the exception of exponentiation and float division,
1613the arithmetic operators work as follows:
1614If both operands are integers,
1615the operation is performed over integers and the result is an integer.
1616Otherwise, if both operands are numbers,
1617then they are converted to floats,
1618the operation is performed following the usual rules
1619for floating-point arithmetic
1620(usually the @x{IEEE 754} standard),
1621and the result is a float.
1622(The string library coerces strings to numbers in
1623arithmetic operations; see @See{coercion} for details.)
1624
1625Exponentiation and float division (@T{/})
1626always convert their operands to floats
1627and the result is always a float.
1628Exponentiation uses the @ANSI{pow},
1629so that it works for non-integer exponents too.
1630
1631Floor division (@T{//}) is a division
1632that rounds the quotient towards minus infinity,
1633that is, the floor of the division of its operands.
1634
1635Modulo is defined as the remainder of a division
1636that rounds the quotient towards minus infinity (floor division).
1637
1638In case of overflows in integer arithmetic,
1639all operations @emphx{wrap around},
1640according to the usual rules of two-complement arithmetic.
1641(In other words,
1642they return the unique representable integer
1643that is equal modulo @M{2@sp{64}} to the mathematical result.)
1644}
1645
1646@sect3{bitwise| @title{Bitwise Operators}
1647Lua supports the following @x{bitwise operators}:
1648@description{
1649@item{@T{&}|bitwise AND}
1650@item{@T{@VerBar}|bitwise OR}
1651@item{@T{~}|bitwise exclusive OR}
1652@item{@T{>>}|right shift}
1653@item{@T{<<}|left shift}
1654@item{@T{~}|unary bitwise NOT}
1655}
1656
1657All bitwise operations convert its operands to integers
1658@see{coercion},
1659operate on all bits of those integers,
1660and result in an integer.
1661
1662Both right and left shifts fill the vacant bits with zeros.
1663Negative displacements shift to the other direction;
1664displacements with absolute values equal to or higher than
1665the number of bits in an integer
1666result in zero (as all bits are shifted out).
1667
1668}
1669
1670@sect3{coercion| @title{Coercions and Conversions}
1671Lua provides some automatic conversions between some
1672types and representations at run time.
1673Bitwise operators always convert float operands to integers.
1674Exponentiation and float division
1675always convert integer operands to floats.
1676All other arithmetic operations applied to mixed numbers
1677(integers and floats) convert the integer operand to a float.
1678The C API also converts both integers to floats and
1679floats to integers, as needed.
1680Moreover, string concatenation accepts numbers as arguments,
1681besides strings.
1682
1683In a conversion from integer to float,
1684if the integer value has an exact representation as a float,
1685that is the result.
1686Otherwise,
1687the conversion gets the nearest higher or
1688the nearest lower representable value.
1689This kind of conversion never fails.
1690
1691The conversion from float to integer
1692checks whether the float has an exact representation as an integer
1693(that is, the float has an integral value and
1694it is in the range of integer representation).
1695If it does, that representation is the result.
1696Otherwise, the conversion fails.
1697
1698The string library uses metamethods that try to coerce
1699strings to numbers in all arithmetic operations.
1700Any string operator is converted to an integer or a float,
1701following its syntax and the rules of the Lua lexer.
1702(The string may have also leading and trailing spaces and a sign.)
1703All conversions from strings to numbers
1704accept both a dot and the current locale mark
1705as the radix character.
1706(The Lua lexer, however, accepts only a dot.)
1707
1708The conversion from numbers to strings uses a
1709non-specified human-readable format.
1710For complete control over how numbers are converted to strings,
1711use the @id{format} function from the string library
1712@seeF{string.format}.
1713
1714}
1715
1716@sect3{rel-ops| @title{Relational Operators}
1717Lua supports the following @x{relational operators}:
1718@description{
1719@item{@T{==}|equality}
1720@item{@T{~=}|inequality}
1721@item{@T{<}|less than}
1722@item{@T{>}|greater than}
1723@item{@T{<=}|less or equal}
1724@item{@T{>=}|greater or equal}
1725}
1726These operators always result in @false or @true.
1727
1728Equality (@T{==}) first compares the type of its operands.
1729If the types are different, then the result is @false.
1730Otherwise, the values of the operands are compared.
1731Strings are compared in the obvious way.
1732Numbers are equal if they denote the same mathematical value.
1733
1734Tables, userdata, and threads
1735are compared by reference:
1736two objects are considered equal only if they are the same object.
1737Every time you create a new object
1738(a table, userdata, or thread),
1739this new object is different from any previously existing object.
1740A closure is always equal to itself.
1741Closures with any detectable difference
1742(different behavior, different definition) are always different.
1743Closures created at different times but with no detectable differences
1744may be classified as equal or not
1745(depending on internal cashing details).
1746
1747You can change the way that Lua compares tables and userdata
1748by using the @idx{__eq} metamethod @see{metatable}.
1749
1750Equality comparisons do not convert strings to numbers
1751or vice versa.
1752Thus, @T{"0"==0} evaluates to @false,
1753and @T{t[0]} and @T{t["0"]} denote different
1754entries in a table.
1755
1756The operator @T{~=} is exactly the negation of equality (@T{==}).
1757
1758The order operators work as follows.
1759If both arguments are numbers,
1760then they are compared according to their mathematical values
1761(regardless of their subtypes).
1762Otherwise, if both arguments are strings,
1763then their values are compared according to the current locale.
1764Otherwise, Lua tries to call the @idx{__lt} or the @idx{__le}
1765metamethod @see{metatable}.
1766A comparison @T{a > b} is translated to @T{b < a}
1767and @T{a >= b} is translated to @T{b <= a}.
1768
1769Following the @x{IEEE 754} standard,
1770@x{NaN} is considered neither smaller than,
1771nor equal to, nor greater than any value (including itself).
1772
1773}
1774
1775@sect3{logic| @title{Logical Operators}
1776The @x{logical operators} in Lua are
1777@Rw{and}, @Rw{or}, and @Rw{not}.
1778Like the control structures @see{control},
1779all logical operators consider both @false and @nil as false
1780and anything else as true.
1781
1782The negation operator @Rw{not} always returns @false or @true.
1783The conjunction operator @Rw{and} returns its first argument
1784if this value is @false or @nil;
1785otherwise, @Rw{and} returns its second argument.
1786The disjunction operator @Rw{or} returns its first argument
1787if this value is different from @nil and @false;
1788otherwise, @Rw{or} returns its second argument.
1789Both @Rw{and} and @Rw{or} use @x{short-circuit evaluation};
1790that is,
1791the second operand is evaluated only if necessary.
1792Here are some examples:
1793@verbatim{
179410 or 20 --> 10
179510 or error() --> 10
1796nil or "a" --> "a"
1797nil and 10 --> nil
1798false and error() --> false
1799false and nil --> false
1800false or nil --> nil
180110 and 20 --> 20
1802}
1803
1804}
1805
1806@sect3{concat| @title{Concatenation}
1807The string @x{concatenation} operator in Lua is
1808denoted by two dots (@Char{..}).
1809If both operands are strings or numbers, then they are converted to
1810strings according to the rules described in @See{coercion}.
1811Otherwise, the @idx{__concat} metamethod is called @see{metatable}.
1812
1813}
1814
1815@sect3{len-op| @title{The Length Operator}
1816
1817The length operator is denoted by the unary prefix operator @T{#}.
1818
1819The length of a string is its number of bytes
1820(that is, the usual meaning of string length when each
1821character is one byte).
1822
1823The length operator applied on a table
1824returns a @x{border} in that table.
1825A @def{border} in a table @id{t} is any natural number
1826that satisfies the following condition:
1827@verbatim{
1828(border == 0 or t[border] ~= nil) and t[border + 1] == nil
1829}
1830In words,
1831a border is any (natural) index present in the table
1832that is followed by an absent index
1833(or zero, when index 1 is absent).
1834
1835A table with exactly one border is called a @def{sequence}.
1836For instance, the table @T{{10, 20, 30, 40, 50}} is a sequence,
1837as it has only one border (5).
1838The table @T{{10, 20, 30, nil, 50}} has two borders (3 and 5),
1839and therefore it is not a sequence.
1840The table @T{{nil, 20, 30, nil, nil, 60, nil}}
1841has three borders (0, 3, and 6),
1842so it is not a sequence, too.
1843The table @T{{}} is a sequence with border 0.
1844Note that non-natural keys do not interfere
1845with whether a table is a sequence.
1846
1847When @id{t} is a sequence,
1848@T{#t} returns its only border,
1849which corresponds to the intuitive notion of the length of the sequence.
1850When @id{t} is not a sequence,
1851@T{#t} can return any of its borders.
1852(The exact one depends on details of
1853the internal representation of the table,
1854which in turn can depend on how the table was populated and
1855the memory addresses of its non-numeric keys.)
1856
1857The computation of the length of a table
1858has a guaranteed worst time of @M{O(log n)},
1859where @M{n} is the largest natural key in the table.
1860
1861A program can modify the behavior of the length operator for
1862any value but strings through the @idx{__len} metamethod @see{metatable}.
1863
1864}
1865
1866@sect3{prec| @title{Precedence}
1867@x{Operator precedence} in Lua follows the table below,
1868from lower to higher priority:
1869@verbatim{
1870or
1871and
1872< > <= >= ~= ==
1873|
1874~
1875&
1876<< >>
1877..
1878+ -
1879* / // %
1880unary operators (not # - ~)
1881^
1882}
1883As usual,
1884you can use parentheses to change the precedences of an expression.
1885The concatenation (@Char{..}) and exponentiation (@Char{^})
1886operators are right associative.
1887All other binary operators are left associative.
1888
1889}
1890
1891@sect3{tableconstructor| @title{Table Constructors}
1892Table @x{constructors} are expressions that create tables.
1893Every time a constructor is evaluated, a new table is created.
1894A constructor can be used to create an empty table
1895or to create a table and initialize some of its fields.
1896The general syntax for constructors is
1897@Produc{
1898@producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
1899@producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
1900@producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or
1901 @bnfNter{Name} @bnfter{=} exp @Or exp}
1902@producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
1903}
1904
1905Each field of the form @T{[exp1] = exp2} adds to the new table an entry
1906with key @id{exp1} and value @id{exp2}.
1907A field of the form @T{name = exp} is equivalent to
1908@T{["name"] = exp}.
1909Finally, fields of the form @id{exp} are equivalent to
1910@T{[i] = exp}, where @id{i} are consecutive integers
1911starting with 1.
1912Fields in the other formats do not affect this counting.
1913For example,
1914@verbatim{
1915a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
1916}
1917is equivalent to
1918@verbatim{
1919do
1920 local t = {}
1921 t[f(1)] = g
1922 t[1] = "x" -- 1st exp
1923 t[2] = "y" -- 2nd exp
1924 t.x = 1 -- t["x"] = 1
1925 t[3] = f(x) -- 3rd exp
1926 t[30] = 23
1927 t[4] = 45 -- 4th exp
1928 a = t
1929end
1930}
1931
1932The order of the assignments in a constructor is undefined.
1933(This order would be relevant only when there are repeated keys.)
1934
1935If the last field in the list has the form @id{exp}
1936and the expression is a function call or a vararg expression,
1937then all values returned by this expression enter the list consecutively
1938@see{functioncall}.
1939
1940The field list can have an optional trailing separator,
1941as a convenience for machine-generated code.
1942
1943}
1944
1945@sect3{functioncall| @title{Function Calls}
1946A @x{function call} in Lua has the following syntax:
1947@Produc{
1948@producname{functioncall}@producbody{prefixexp args}
1949}
1950In a function call,
1951first @bnfNter{prefixexp} and @bnfNter{args} are evaluated.
1952If the value of @bnfNter{prefixexp} has type @emph{function},
1953then this function is called
1954with the given arguments.
1955Otherwise, the @bnfNter{prefixexp} @idx{__call} metamethod is called,
1956having as first argument the value of @bnfNter{prefixexp},
1957followed by the original call arguments
1958@see{metatable}.
1959
1960The form
1961@Produc{
1962@producname{functioncall}@producbody{prefixexp @bnfter{:} @bnfNter{Name} args}
1963}
1964can be used to call @Q{methods}.
1965A call @T{v:name(@rep{args})}
1966is syntactic sugar for @T{v.name(v,@rep{args})},
1967except that @id{v} is evaluated only once.
1968
1969Arguments have the following syntax:
1970@Produc{
1971@producname{args}@producbody{@bnfter{(} @bnfopt{explist} @bnfter{)}}
1972@producname{args}@producbody{tableconstructor}
1973@producname{args}@producbody{@bnfNter{LiteralString}}
1974}
1975All argument expressions are evaluated before the call.
1976A call of the form @T{f{@rep{fields}}} is
1977syntactic sugar for @T{f({@rep{fields}})};
1978that is, the argument list is a single new table.
1979A call of the form @T{f'@rep{string}'}
1980(or @T{f"@rep{string}"} or @T{f[[@rep{string}]]})
1981is syntactic sugar for @T{f('@rep{string}')};
1982that is, the argument list is a single literal string.
1983
1984A call of the form @T{return @rep{functioncall}} is called
1985a @def{tail call}.
1986Lua implements @def{proper tail calls}
1987(or @emph{proper tail recursion}):
1988in a tail call,
1989the called function reuses the stack entry of the calling function.
1990Therefore, there is no limit on the number of nested tail calls that
1991a program can execute.
1992However, a tail call erases any debug information about the
1993calling function.
1994Note that a tail call only happens with a particular syntax,
1995where the @Rw{return} has one single function call as argument;
1996this syntax makes the calling function return exactly
1997the returns of the called function.
1998So, none of the following examples are tail calls:
1999@verbatim{
2000return (f(x)) -- results adjusted to 1
2001return 2 * f(x)
2002return x, f(x) -- additional results
2003f(x); return -- results discarded
2004return x or f(x) -- results adjusted to 1
2005}
2006
2007}
2008
2009@sect3{func-def| @title{Function Definitions}
2010
2011The syntax for function definition is
2012@Produc{
2013@producname{functiondef}@producbody{@Rw{function} funcbody}
2014@producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
2015}
2016
2017The following syntactic sugar simplifies function definitions:
2018@Produc{
2019@producname{stat}@producbody{@Rw{function} funcname funcbody}
2020@producname{stat}@producbody{@Rw{local} @Rw{function} @bnfNter{Name} funcbody}
2021@producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}} @bnfopt{@bnfter{:} @bnfNter{Name}}}
2022}
2023The statement
2024@verbatim{
2025function f () @rep{body} end
2026}
2027translates to
2028@verbatim{
2029f = function () @rep{body} end
2030}
2031The statement
2032@verbatim{
2033function t.a.b.c.f () @rep{body} end
2034}
2035translates to
2036@verbatim{
2037t.a.b.c.f = function () @rep{body} end
2038}
2039The statement
2040@verbatim{
2041local function f () @rep{body} end
2042}
2043translates to
2044@verbatim{
2045local f; f = function () @rep{body} end
2046}
2047not to
2048@verbatim{
2049local f = function () @rep{body} end
2050}
2051(This only makes a difference when the body of the function
2052contains references to @id{f}.)
2053
2054A function definition is an executable expression,
2055whose value has type @emph{function}.
2056When Lua precompiles a chunk,
2057all its function bodies are precompiled too.
2058Then, whenever Lua executes the function definition,
2059the function is @emph{instantiated} (or @emph{closed}).
2060This function instance (or @emphx{closure})
2061is the final value of the expression.
2062
2063Parameters act as local variables that are
2064initialized with the argument values:
2065@Produc{
2066@producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} @bnfter{...}} @Or
2067 @bnfter{...}}
2068}
2069When a Lua function is called,
2070it adjusts its list of @x{arguments} to
2071the length of its list of parameters,
2072unless the function is a @def{vararg function},
2073which is indicated by three dots (@Char{...})
2074at the end of its parameter list.
2075A vararg function does not adjust its argument list;
2076instead, it collects all extra arguments and supplies them
2077to the function through a @def{vararg expression},
2078which is also written as three dots.
2079The value of this expression is a list of all actual extra arguments,
2080similar to a function with multiple results.
2081If a vararg expression is used inside another expression
2082or in the middle of a list of expressions,
2083then its return list is adjusted to one element.
2084If the expression is used as the last element of a list of expressions,
2085then no adjustment is made
2086(unless that last expression is enclosed in parentheses).
2087
2088
2089As an example, consider the following definitions:
2090@verbatim{
2091function f(a, b) end
2092function g(a, b, ...) end
2093function r() return 1,2,3 end
2094}
2095Then, we have the following mapping from arguments to parameters and
2096to the vararg expression:
2097@verbatim{
2098CALL PARAMETERS
2099
2100f(3) a=3, b=nil
2101f(3, 4) a=3, b=4
2102f(3, 4, 5) a=3, b=4
2103f(r(), 10) a=1, b=10
2104f(r()) a=1, b=2
2105
2106g(3) a=3, b=nil, ... --> (nothing)
2107g(3, 4) a=3, b=4, ... --> (nothing)
2108g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
2109g(5, r()) a=5, b=1, ... --> 2 3
2110}
2111
2112Results are returned using the @Rw{return} statement @see{control}.
2113If control reaches the end of a function
2114without encountering a @Rw{return} statement,
2115then the function returns with no results.
2116
2117@index{multiple return}
2118There is a system-dependent limit on the number of values
2119that a function may return.
2120This limit is guaranteed to be larger than 1000.
2121
2122The @emphx{colon} syntax
2123is used for defining @def{methods},
2124that is, functions that have an implicit extra parameter @idx{self}.
2125Thus, the statement
2126@verbatim{
2127function t.a.b.c:f (@rep{params}) @rep{body} end
2128}
2129is syntactic sugar for
2130@verbatim{
2131t.a.b.c.f = function (self, @rep{params}) @rep{body} end
2132}
2133
2134}
2135
2136}
2137
2138@sect2{visibility| @title{Visibility Rules}
2139
2140@index{visibility}
2141Lua is a lexically scoped language.
2142The scope of a local variable begins at the first statement after
2143its declaration and lasts until the last non-void statement
2144of the innermost block that includes the declaration.
2145Consider the following example:
2146@verbatim{
2147x = 10 -- global variable
2148do -- new block
2149 local x = x -- new 'x', with value 10
2150 print(x) --> 10
2151 x = x+1
2152 do -- another block
2153 local x = x+1 -- another 'x'
2154 print(x) --> 12
2155 end
2156 print(x) --> 11
2157end
2158print(x) --> 10 (the global one)
2159}
2160
2161Notice that, in a declaration like @T{local x = x},
2162the new @id{x} being declared is not in scope yet,
2163and so the second @id{x} refers to the outside variable.
2164
2165Because of the @x{lexical scoping} rules,
2166local variables can be freely accessed by functions
2167defined inside their scope.
2168A local variable used by an inner function is called
2169an @def{upvalue}, or @emphx{external local variable},
2170inside the inner function.
2171
2172Notice that each execution of a @Rw{local} statement
2173defines new local variables.
2174Consider the following example:
2175@verbatim{
2176a = {}
2177local x = 20
2178for i=1,10 do
2179 local y = 0
2180 a[i] = function () y=y+1; return x+y end
2181end
2182}
2183The loop creates ten closures
2184(that is, ten instances of the anonymous function).
2185Each of these closures uses a different @id{y} variable,
2186while all of them share the same @id{x}.
2187
2188}
2189
2190}
2191
2192
2193@C{-------------------------------------------------------------------------}
2194@sect1{API| @title{The Application Program Interface}
2195
2196@index{C API}
2197This section describes the @N{C API} for Lua, that is,
2198the set of @N{C functions} available to the host program to communicate
2199with Lua.
2200All API functions and related types and constants
2201are declared in the header file @defid{lua.h}.
2202
2203Even when we use the term @Q{function},
2204any facility in the API may be provided as a macro instead.
2205Except where stated otherwise,
2206all such macros use each of their arguments exactly once
2207(except for the first argument, which is always a Lua state),
2208and so do not generate any hidden side-effects.
2209
2210As in most @N{C libraries},
2211the Lua API functions do not check their arguments
2212for validity or consistency.
2213However, you can change this behavior by compiling Lua
2214with the macro @defid{LUA_USE_APICHECK} defined.
2215
2216The Lua library is fully reentrant:
2217it has no global variables.
2218It keeps all information it needs in a dynamic structure,
2219called the @def{Lua state}.
2220
2221Each Lua state has one or more threads,
2222which correspond to independent, cooperative lines of execution.
2223The type @Lid{lua_State} (despite its name) refers to a thread.
2224(Indirectly, through the thread, it also refers to the
2225Lua state associated to the thread.)
2226
2227A pointer to a thread must be passed as the first argument to
2228every function in the library, except to @Lid{lua_newstate},
2229which creates a Lua state from scratch and returns a pointer
2230to the @emph{main thread} in the new state.
2231
2232
2233@sect2{@title{The Stack}
2234
2235Lua uses a @emph{virtual stack} to pass values to and from C.
2236Each element in this stack represents a Lua value
2237(@nil, number, string, etc.).
2238Functions in the API can access this stack through the
2239Lua state parameter that they receive.
2240
2241Whenever Lua calls C, the called function gets a new stack,
2242which is independent of previous stacks and of stacks of
2243@N{C functions} that are still active.
2244This stack initially contains any arguments to the @N{C function}
2245and it is where the @N{C function} can store temporary
2246Lua values and must push its results
2247to be returned to the caller @seeC{lua_CFunction}.
2248
2249For convenience,
2250most query operations in the API do not follow a strict stack discipline.
2251Instead, they can refer to any element in the stack
2252by using an @emph{index}:@index{index (API stack)}
2253A positive index represents an absolute stack position
2254(starting @N{at 1});
2255a negative index represents an offset relative to the top of the stack.
2256More specifically, if the stack has @rep{n} elements,
2257then @N{index 1} represents the first element
2258(that is, the element that was pushed onto the stack first)
2259and
2260@N{index @rep{n}} represents the last element;
2261@N{index @num{-1}} also represents the last element
2262(that is, the element at @N{the top})
2263and index @M{-n} represents the first element.
2264
2265}
2266
2267@sect2{stacksize| @title{Stack Size}
2268
2269When you interact with the Lua API,
2270you are responsible for ensuring consistency.
2271In particular,
2272@emph{you are responsible for controlling stack overflow}.
2273You can use the function @Lid{lua_checkstack}
2274to ensure that the stack has enough space for pushing new elements.
2275
2276Whenever Lua calls C,
2277it ensures that the stack has space for
2278at least @defid{LUA_MINSTACK} extra slots.
2279@id{LUA_MINSTACK} is defined as 20,
2280so that usually you do not have to worry about stack space
2281unless your code has loops pushing elements onto the stack.
2282
2283When you call a Lua function
2284without a fixed number of results @seeF{lua_call},
2285Lua ensures that the stack has enough space for all results,
2286but it does not ensure any extra space.
2287So, before pushing anything in the stack after such a call
2288you should use @Lid{lua_checkstack}.
2289
2290}
2291
2292@sect2{@title{Valid and Acceptable Indices}
2293
2294Any function in the API that receives stack indices
2295works only with @emphx{valid indices} or @emphx{acceptable indices}.
2296
2297A @def{valid index} is an index that refers to a
2298position that stores a modifiable Lua value.
2299It comprises stack indices @N{between 1} and the stack top
2300(@T{1 @leq abs(index) @leq top})
2301@index{stack index}
2302plus @def{pseudo-indices},
2303which represent some positions that are accessible to @N{C code}
2304but that are not in the stack.
2305Pseudo-indices are used to access the registry @see{registry}
2306and the upvalues of a @N{C function} @see{c-closure}.
2307
2308Functions that do not need a specific mutable position,
2309but only a value (e.g., query functions),
2310can be called with acceptable indices.
2311An @def{acceptable index} can be any valid index,
2312but it also can be any positive index after the stack top
2313within the space allocated for the stack,
2314that is, indices up to the stack size.
2315(Note that 0 is never an acceptable index.)
2316Indices to upvalues @see{c-closure} larger than the real number
2317of upvalues in the current @N{C function} are also acceptable (but invalid).
2318Except when noted otherwise,
2319functions in the API work with acceptable indices.
2320
2321Acceptable indices serve to avoid extra tests
2322against the stack top when querying the stack.
2323For instance, a @N{C function} can query its third argument
2324without the need to first check whether there is a third argument,
2325that is, without the need to check whether 3 is a valid index.
2326
2327For functions that can be called with acceptable indices,
2328any non-valid index is treated as if it
2329contains a value of a virtual type @defid{LUA_TNONE},
2330which behaves like a nil value.
2331
2332}
2333
2334@sect2{c-closure| @title{C Closures}
2335
2336When a @N{C function} is created,
2337it is possible to associate some values with it,
2338thus creating a @def{@N{C closure}}
2339@seeC{lua_pushcclosure};
2340these values are called @def{upvalues} and are
2341accessible to the function whenever it is called.
2342
2343Whenever a @N{C function} is called,
2344its upvalues are located at specific pseudo-indices.
2345These pseudo-indices are produced by the macro
2346@Lid{lua_upvalueindex}.
2347The first upvalue associated with a function is at index
2348@T{lua_upvalueindex(1)}, and so on.
2349Any access to @T{lua_upvalueindex(@rep{n})},
2350where @rep{n} is greater than the number of upvalues of the
2351current function
2352(but not greater than 256,
2353which is one plus the maximum number of upvalues in a closure),
2354produces an acceptable but invalid index.
2355
2356A @N{C closure} can also change the values of its corresponding upvalues.
2357
2358}
2359
2360@sect2{registry| @title{Registry}
2361
2362Lua provides a @def{registry},
2363a predefined table that can be used by any @N{C code} to
2364store whatever Lua values it needs to store.
2365The registry table is always located at pseudo-index
2366@defid{LUA_REGISTRYINDEX}.
2367Any @N{C library} can store data into this table,
2368but it must take care to choose keys
2369that are different from those used
2370by other libraries, to avoid collisions.
2371Typically, you should use as key a string containing your library name,
2372or a light userdata with the address of a @N{C object} in your code,
2373or any Lua object created by your code.
2374As with variable names,
2375string keys starting with an underscore followed by
2376uppercase letters are reserved for Lua.
2377
2378The integer keys in the registry are used
2379by the reference mechanism @seeC{luaL_ref}
2380and by some predefined values.
2381Therefore, integer keys must not be used for other purposes.
2382
2383When you create a new Lua state,
2384its registry comes with some predefined values.
2385These predefined values are indexed with integer keys
2386defined as constants in @id{lua.h}.
2387The following constants are defined:
2388@description{
2389@item{@defid{LUA_RIDX_MAINTHREAD}| At this index the registry has
2390the main thread of the state.
2391(The main thread is the one created together with the state.)
2392}
2393
2394@item{@defid{LUA_RIDX_GLOBALS}| At this index the registry has
2395the @x{global environment}.
2396}
2397}
2398
2399}
2400
2401@sect2{C-error|@title{Error Handling in C}
2402
2403Internally, Lua uses the C @id{longjmp} facility to handle errors.
2404(Lua will use exceptions if you compile it as C++;
2405search for @id{LUAI_THROW} in the source code for details.)
2406When Lua faces any error
2407(such as a @x{memory allocation error} or a type error)
2408it @emph{raises} an error;
2409that is, it does a long jump.
2410A @emphx{protected environment} uses @id{setjmp}
2411to set a recovery point;
2412any error jumps to the most recent active recovery point.
2413
2414Inside a @N{C function} you can raise an error by calling @Lid{lua_error}.
2415
2416Most functions in the API can raise an error,
2417for instance due to a @x{memory allocation error}.
2418The documentation for each function indicates whether
2419it can raise errors.
2420
2421If an error happens outside any protected environment,
2422Lua calls a @def{panic function} (see @Lid{lua_atpanic})
2423and then calls @T{abort},
2424thus exiting the host application.
2425Your panic function can avoid this exit by
2426never returning
2427(e.g., doing a long jump to your own recovery point outside Lua).
2428
2429The panic function,
2430as its name implies,
2431is a mechanism of last resort.
2432Programs should avoid it.
2433As a general rule,
2434when a @N{C function} is called by Lua with a Lua state,
2435it can do whatever it wants on that Lua state,
2436as it should be already protected.
2437However,
2438when C code operates on other Lua states
2439(e.g., a Lua parameter to the function,
2440a Lua state stored in the registry, or
2441the result of @Lid{lua_newthread}),
2442it should use them only in API calls that cannot raise errors.
2443
2444The panic function runs as if it were a @x{message handler} @see{error};
2445in particular, the error object is at the top of the stack.
2446However, there is no guarantee about stack space.
2447To push anything on the stack,
2448the panic function must first check the available space @see{stacksize}.
2449
2450}
2451
2452@sect2{continuations|@title{Handling Yields in C}
2453
2454Internally, Lua uses the C @id{longjmp} facility to yield a coroutine.
2455Therefore, if a @N{C function} @id{foo} calls an API function
2456and this API function yields
2457(directly or indirectly by calling another function that yields),
2458Lua cannot return to @id{foo} any more,
2459because the @id{longjmp} removes its frame from the C stack.
2460
2461To avoid this kind of problem,
2462Lua raises an error whenever it tries to yield across an API call,
2463except for three functions:
2464@Lid{lua_yieldk}, @Lid{lua_callk}, and @Lid{lua_pcallk}.
2465All those functions receive a @def{continuation function}
2466(as a parameter named @id{k}) to continue execution after a yield.
2467
2468We need to set some terminology to explain continuations.
2469We have a @N{C function} called from Lua which we will call
2470the @emph{original function}.
2471This original function then calls one of those three functions in the C API,
2472which we will call the @emph{callee function},
2473that then yields the current thread.
2474(This can happen when the callee function is @Lid{lua_yieldk},
2475or when the callee function is either @Lid{lua_callk} or @Lid{lua_pcallk}
2476and the function called by them yields.)
2477
2478Suppose the running thread yields while executing the callee function.
2479After the thread resumes,
2480it eventually will finish running the callee function.
2481However,
2482the callee function cannot return to the original function,
2483because its frame in the C stack was destroyed by the yield.
2484Instead, Lua calls a @def{continuation function},
2485which was given as an argument to the callee function.
2486As the name implies,
2487the continuation function should continue the task
2488of the original function.
2489
2490As an illustration, consider the following function:
2491@verbatim{
2492int original_function (lua_State *L) {
2493 ... /* code 1 */
2494 status = lua_pcall(L, n, m, h); /* calls Lua */
2495 ... /* code 2 */
2496}
2497}
2498Now we want to allow
2499the Lua code being run by @Lid{lua_pcall} to yield.
2500First, we can rewrite our function like here:
2501@verbatim{
2502int k (lua_State *L, int status, lua_KContext ctx) {
2503 ... /* code 2 */
2504}
2505
2506int original_function (lua_State *L) {
2507 ... /* code 1 */
2508 return k(L, lua_pcall(L, n, m, h), ctx);
2509}
2510}
2511In the above code,
2512the new function @id{k} is a
2513@emph{continuation function} (with type @Lid{lua_KFunction}),
2514which should do all the work that the original function
2515was doing after calling @Lid{lua_pcall}.
2516Now, we must inform Lua that it must call @id{k} if the Lua code
2517being executed by @Lid{lua_pcall} gets interrupted in some way
2518(errors or yielding),
2519so we rewrite the code as here,
2520replacing @Lid{lua_pcall} by @Lid{lua_pcallk}:
2521@verbatim{
2522int original_function (lua_State *L) {
2523 ... /* code 1 */
2524 return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
2525}
2526}
2527Note the external, explicit call to the continuation:
2528Lua will call the continuation only if needed, that is,
2529in case of errors or resuming after a yield.
2530If the called function returns normally without ever yielding,
2531@Lid{lua_pcallk} (and @Lid{lua_callk}) will also return normally.
2532(Of course, instead of calling the continuation in that case,
2533you can do the equivalent work directly inside the original function.)
2534
2535Besides the Lua state,
2536the continuation function has two other parameters:
2537the final status of the call plus the context value (@id{ctx}) that
2538was passed originally to @Lid{lua_pcallk}.
2539(Lua does not use this context value;
2540it only passes this value from the original function to the
2541continuation function.)
2542For @Lid{lua_pcallk},
2543the status is the same value that would be returned by @Lid{lua_pcallk},
2544except that it is @Lid{LUA_YIELD} when being executed after a yield
2545(instead of @Lid{LUA_OK}).
2546For @Lid{lua_yieldk} and @Lid{lua_callk},
2547the status is always @Lid{LUA_YIELD} when Lua calls the continuation.
2548(For these two functions,
2549Lua will not call the continuation in case of errors,
2550because they do not handle errors.)
2551Similarly, when using @Lid{lua_callk},
2552you should call the continuation function
2553with @Lid{LUA_OK} as the status.
2554(For @Lid{lua_yieldk}, there is not much point in calling
2555directly the continuation function,
2556because @Lid{lua_yieldk} usually does not return.)
2557
2558Lua treats the continuation function as if it were the original function.
2559The continuation function receives the same Lua stack
2560from the original function,
2561in the same state it would be if the callee function had returned.
2562(For instance,
2563after a @Lid{lua_callk} the function and its arguments are
2564removed from the stack and replaced by the results from the call.)
2565It also has the same upvalues.
2566Whatever it returns is handled by Lua as if it were the return
2567of the original function.
2568
2569}
2570
2571@sect2{@title{Functions and Types}
2572
2573Here we list all functions and types from the @N{C API} in
2574alphabetical order.
2575Each function has an indicator like this:
2576@apii{o,p,x}
2577
2578The first field, @T{o},
2579is how many elements the function pops from the stack.
2580The second field, @T{p},
2581is how many elements the function pushes onto the stack.
2582(Any function always pushes its results after popping its arguments.)
2583A field in the form @T{x|y} means the function can push (or pop)
2584@T{x} or @T{y} elements,
2585depending on the situation;
2586an interrogation mark @Char{?} means that
2587we cannot know how many elements the function pops/pushes
2588by looking only at its arguments
2589(e.g., they may depend on what is on the stack).
2590The third field, @T{x},
2591tells whether the function may raise errors:
2592@Char{-} means the function never raises any error;
2593@Char{m} means the function may raise out-of-memory errors
2594and errors running a finalizer;
2595@Char{v} means the function may raise the errors explained in the text;
2596@Char{e} means the function may raise any errors
2597(because it can run arbitrary Lua code,
2598either directly or through metamethods).
2599
2600
2601@APIEntry{int lua_absindex (lua_State *L, int idx);|
2602@apii{0,0,-}
2603
2604Converts the @x{acceptable index} @id{idx}
2605into an equivalent @x{absolute index}
2606(that is, one that does not depend on the stack top).
2607
2608}
2609
2610
2611@APIEntry{
2612typedef void * (*lua_Alloc) (void *ud,
2613 void *ptr,
2614 size_t osize,
2615 size_t nsize);|
2616
2617The type of the @x{memory-allocation function} used by Lua states.
2618The allocator function must provide a
2619functionality similar to @id{realloc},
2620but not exactly the same.
2621Its arguments are
2622@id{ud}, an opaque pointer passed to @Lid{lua_newstate};
2623@id{ptr}, a pointer to the block being allocated/reallocated/freed;
2624@id{osize}, the original size of the block or some code about what
2625is being allocated;
2626and @id{nsize}, the new size of the block.
2627
2628When @id{ptr} is not @id{NULL},
2629@id{osize} is the size of the block pointed by @id{ptr},
2630that is, the size given when it was allocated or reallocated.
2631
2632When @id{ptr} is @id{NULL},
2633@id{osize} encodes the kind of object that Lua is allocating.
2634@id{osize} is any of
2635@Lid{LUA_TSTRING}, @Lid{LUA_TTABLE}, @Lid{LUA_TFUNCTION},
2636@Lid{LUA_TUSERDATA}, or @Lid{LUA_TTHREAD} when (and only when)
2637Lua is creating a new object of that type.
2638When @id{osize} is some other value,
2639Lua is allocating memory for something else.
2640
2641Lua assumes the following behavior from the allocator function:
2642
2643When @id{nsize} is zero,
2644the allocator must behave like @id{free}
2645and return @id{NULL}.
2646
2647When @id{nsize} is not zero,
2648the allocator must behave like @id{realloc}.
2649The allocator returns @id{NULL}
2650if and only if it cannot fulfill the request.
2651
2652Here is a simple implementation for the @x{allocator function}.
2653It is used in the auxiliary library by @Lid{luaL_newstate}.
2654@verbatim{
2655static void *l_alloc (void *ud, void *ptr, size_t osize,
2656 size_t nsize) {
2657 (void)ud; (void)osize; /* not used */
2658 if (nsize == 0) {
2659 free(ptr);
2660 return NULL;
2661 }
2662 else
2663 return realloc(ptr, nsize);
2664}
2665}
2666Note that @N{Standard C} ensures
2667that @T{free(NULL)} has no effect and that
2668@T{realloc(NULL,size)} is equivalent to @T{malloc(size)}.
2669
2670}
2671
2672@APIEntry{void lua_arith (lua_State *L, int op);|
2673@apii{2|1,1,e}
2674
2675Performs an arithmetic or bitwise operation over the two values
2676(or one, in the case of negations)
2677at the top of the stack,
2678with the value at the top being the second operand,
2679pops these values, and pushes the result of the operation.
2680The function follows the semantics of the corresponding Lua operator
2681(that is, it may call metamethods).
2682
2683The value of @id{op} must be one of the following constants:
2684@description{
2685
2686@item{@defid{LUA_OPADD}| performs addition (@T{+})}
2687@item{@defid{LUA_OPSUB}| performs subtraction (@T{-})}
2688@item{@defid{LUA_OPMUL}| performs multiplication (@T{*})}
2689@item{@defid{LUA_OPDIV}| performs float division (@T{/})}
2690@item{@defid{LUA_OPIDIV}| performs floor division (@T{//})}
2691@item{@defid{LUA_OPMOD}| performs modulo (@T{%})}
2692@item{@defid{LUA_OPPOW}| performs exponentiation (@T{^})}
2693@item{@defid{LUA_OPUNM}| performs mathematical negation (unary @T{-})}
2694@item{@defid{LUA_OPBNOT}| performs bitwise NOT (@T{~})}
2695@item{@defid{LUA_OPBAND}| performs bitwise AND (@T{&})}
2696@item{@defid{LUA_OPBOR}| performs bitwise OR (@T{|})}
2697@item{@defid{LUA_OPBXOR}| performs bitwise exclusive OR (@T{~})}
2698@item{@defid{LUA_OPSHL}| performs left shift (@T{<<})}
2699@item{@defid{LUA_OPSHR}| performs right shift (@T{>>})}
2700
2701}
2702
2703}
2704
2705@APIEntry{lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);|
2706@apii{0,0,-}
2707
2708Sets a new panic function and returns the old one @see{C-error}.
2709
2710}
2711
2712@APIEntry{void lua_call (lua_State *L, int nargs, int nresults);|
2713@apii{nargs+1,nresults,e}
2714
2715Calls a function.
2716
2717To do a call you must use the following protocol:
2718first, the value to be called is pushed onto the stack;
2719then, the arguments to the call are pushed
2720in direct order;
2721that is, the first argument is pushed first.
2722Finally you call @Lid{lua_call};
2723@id{nargs} is the number of arguments that you pushed onto the stack.
2724All arguments and the function value are popped from the stack
2725when the function is called.
2726The function results are pushed onto the stack when the function returns.
2727The number of results is adjusted to @id{nresults},
2728unless @id{nresults} is @defid{LUA_MULTRET}.
2729In this case, all results from the function are pushed;
2730Lua takes care that the returned values fit into the stack space,
2731but it does not ensure any extra space in the stack.
2732The function results are pushed onto the stack in direct order
2733(the first result is pushed first),
2734so that after the call the last result is on the top of the stack.
2735
2736Any error while calling and running the function is propagated upwards
2737(with a @id{longjmp}).
2738Like regular Lua calls,
2739this function respects the @idx{__call} metamethod.
2740
2741The following example shows how the host program can do the
2742equivalent to this Lua code:
2743@verbatim{
2744a = f("how", t.x, 14)
2745}
2746Here it is @N{in C}:
2747@verbatim{
2748lua_getglobal(L, "f"); /* function to be called */
2749lua_pushliteral(L, "how"); /* 1st argument */
2750lua_getglobal(L, "t"); /* table to be indexed */
2751lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
2752lua_remove(L, -2); /* remove 't' from the stack */
2753lua_pushinteger(L, 14); /* 3rd argument */
2754lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
2755lua_setglobal(L, "a"); /* set global 'a' */
2756}
2757Note that the code above is @emph{balanced}:
2758at its end, the stack is back to its original configuration.
2759This is considered good programming practice.
2760
2761}
2762
2763@APIEntry{
2764void lua_callk (lua_State *L,
2765 int nargs,
2766 int nresults,
2767 lua_KContext ctx,
2768 lua_KFunction k);|
2769@apii{nargs + 1,nresults,e}
2770
2771This function behaves exactly like @Lid{lua_call},
2772but allows the called function to yield @see{continuations}.
2773
2774}
2775
2776@APIEntry{typedef int (*lua_CFunction) (lua_State *L);|
2777
2778Type for @N{C functions}.
2779
2780In order to communicate properly with Lua,
2781a @N{C function} must use the following protocol,
2782which defines the way parameters and results are passed:
2783a @N{C function} receives its arguments from Lua in its stack
2784in direct order (the first argument is pushed first).
2785So, when the function starts,
2786@T{lua_gettop(L)} returns the number of arguments received by the function.
2787The first argument (if any) is at index 1
2788and its last argument is at index @T{lua_gettop(L)}.
2789To return values to Lua, a @N{C function} just pushes them onto the stack,
2790in direct order (the first result is pushed first),
2791and returns the number of results.
2792Any other value in the stack below the results will be properly
2793discarded by Lua.
2794Like a Lua function, a @N{C function} called by Lua can also return
2795many results.
2796
2797As an example, the following function receives a variable number
2798of numeric arguments and returns their average and their sum:
2799@verbatim{
2800static int foo (lua_State *L) {
2801 int n = lua_gettop(L); /* number of arguments */
2802 lua_Number sum = 0.0;
2803 int i;
2804 for (i = 1; i <= n; i++) {
2805 if (!lua_isnumber(L, i)) {
2806 lua_pushliteral(L, "incorrect argument");
2807 lua_error(L);
2808 }
2809 sum += lua_tonumber(L, i);
2810 }
2811 lua_pushnumber(L, sum/n); /* first result */
2812 lua_pushnumber(L, sum); /* second result */
2813 return 2; /* number of results */
2814}
2815}
2816
2817
2818
2819}
2820
2821
2822@APIEntry{int lua_checkstack (lua_State *L, int n);|
2823@apii{0,0,-}
2824
2825Ensures that the stack has space for at least @id{n} extra slots
2826(that is, that you can safely push up to @id{n} values into it).
2827It returns false if it cannot fulfill the request,
2828either because it would cause the stack
2829to be larger than a fixed maximum size
2830(typically at least several thousand elements) or
2831because it cannot allocate memory for the extra space.
2832This function never shrinks the stack;
2833if the stack already has space for the extra slots,
2834it is left unchanged.
2835
2836}
2837
2838@APIEntry{void lua_close (lua_State *L);|
2839@apii{0,0,-}
2840
2841Destroys all objects in the given Lua state
2842(calling the corresponding garbage-collection metamethods, if any)
2843and frees all dynamic memory used by this state.
2844On several platforms, you may not need to call this function,
2845because all resources are naturally released when the host program ends.
2846On the other hand, long-running programs that create multiple states,
2847such as daemons or web servers,
2848will probably need to close states as soon as they are not needed.
2849
2850}
2851
2852@APIEntry{int lua_compare (lua_State *L, int index1, int index2, int op);|
2853@apii{0,0,e}
2854
2855Compares two Lua values.
2856Returns 1 if the value at index @id{index1} satisfies @id{op}
2857when compared with the value at index @id{index2},
2858following the semantics of the corresponding Lua operator
2859(that is, it may call metamethods).
2860Otherwise @N{returns 0}.
2861Also @N{returns 0} if any of the indices is not valid.
2862
2863The value of @id{op} must be one of the following constants:
2864@description{
2865
2866@item{@defid{LUA_OPEQ}| compares for equality (@T{==})}
2867@item{@defid{LUA_OPLT}| compares for less than (@T{<})}
2868@item{@defid{LUA_OPLE}| compares for less or equal (@T{<=})}
2869
2870}
2871
2872}
2873
2874@APIEntry{void lua_concat (lua_State *L, int n);|
2875@apii{n,1,e}
2876
2877Concatenates the @id{n} values at the top of the stack,
2878pops them, and leaves the result at the top.
2879If @N{@T{n} is 1}, the result is the single value on the stack
2880(that is, the function does nothing);
2881if @id{n} is 0, the result is the empty string.
2882Concatenation is performed following the usual semantics of Lua
2883@see{concat}.
2884
2885}
2886
2887@APIEntry{void lua_copy (lua_State *L, int fromidx, int toidx);|
2888@apii{0,0,-}
2889
2890Copies the element at index @id{fromidx}
2891into the valid index @id{toidx},
2892replacing the value at that position.
2893Values at other positions are not affected.
2894
2895}
2896
2897@APIEntry{void lua_createtable (lua_State *L, int narr, int nrec);|
2898@apii{0,1,m}
2899
2900Creates a new empty table and pushes it onto the stack.
2901Parameter @id{narr} is a hint for how many elements the table
2902will have as a sequence;
2903parameter @id{nrec} is a hint for how many other elements
2904the table will have.
2905Lua may use these hints to preallocate memory for the new table.
2906This preallocation is useful for performance when you know in advance
2907how many elements the table will have.
2908Otherwise you can use the function @Lid{lua_newtable}.
2909
2910}
2911
2912@APIEntry{int lua_dump (lua_State *L,
2913 lua_Writer writer,
2914 void *data,
2915 int strip);|
2916@apii{0,0,-}
2917
2918Dumps a function as a binary chunk.
2919Receives a Lua function on the top of the stack
2920and produces a binary chunk that,
2921if loaded again,
2922results in a function equivalent to the one dumped.
2923As it produces parts of the chunk,
2924@Lid{lua_dump} calls function @id{writer} @seeC{lua_Writer}
2925with the given @id{data}
2926to write them.
2927
2928If @id{strip} is true,
2929the binary representation may not include all debug information
2930about the function,
2931to save space.
2932
2933The value returned is the error code returned by the last
2934call to the writer;
2935@N{0 means} no errors.
2936
2937This function does not pop the Lua function from the stack.
2938
2939}
2940
2941@APIEntry{int lua_error (lua_State *L);|
2942@apii{1,0,v}
2943
2944Generates a Lua error,
2945using the value at the top of the stack as the error object.
2946This function does a long jump,
2947and therefore never returns
2948@seeC{luaL_error}.
2949
2950}
2951
2952@APIEntry{int lua_gc (lua_State *L, int what, int data);|
2953@apii{0,0,v}
2954
2955Controls the garbage collector.
2956
2957This function performs several tasks,
2958according to the value of the parameter @id{what}:
2959@description{
2960
2961@item{@id{LUA_GCSTOP}|
2962stops the garbage collector.
2963}
2964
2965@item{@id{LUA_GCRESTART}|
2966restarts the garbage collector.
2967}
2968
2969@item{@id{LUA_GCCOLLECT}|
2970performs a full garbage-collection cycle.
2971}
2972
2973@item{@id{LUA_GCCOUNT}|
2974returns the current amount of memory (in Kbytes) in use by Lua.
2975}
2976
2977@item{@id{LUA_GCCOUNTB}|
2978returns the remainder of dividing the current amount of bytes of
2979memory in use by Lua by 1024.
2980}
2981
2982@item{@id{LUA_GCSTEP}|
2983performs an incremental step of garbage collection.
2984}
2985
2986@item{@id{LUA_GCSETPAUSE}|
2987sets @id{data} as the new value
2988for the @emph{pause} of the collector @see{GC}
2989and returns the previous value of the pause.
2990}
2991
2992@item{@id{LUA_GCSETSTEPMUL}|
2993sets @id{data} as the new value for the @emph{step multiplier} of
2994the collector @see{GC}
2995and returns the previous value of the step multiplier.
2996}
2997
2998@item{@id{LUA_GCISRUNNING}|
2999returns a boolean that tells whether the collector is running
3000(i.e., not stopped).
3001}
3002
3003}
3004For more details about these options,
3005see @Lid{collectgarbage}.
3006
3007This function may raise errors when calling finalizers.
3008
3009}
3010
3011@APIEntry{lua_Alloc lua_getallocf (lua_State *L, void **ud);|
3012@apii{0,0,-}
3013
3014Returns the @x{memory-allocation function} of a given state.
3015If @id{ud} is not @id{NULL}, Lua stores in @T{*ud} the
3016opaque pointer given when the memory-allocator function was set.
3017
3018}
3019
3020@APIEntry{int lua_getfield (lua_State *L, int index, const char *k);|
3021@apii{0,1,e}
3022
3023Pushes onto the stack the value @T{t[k]},
3024where @id{t} is the value at the given index.
3025As in Lua, this function may trigger a metamethod
3026for the @Q{index} event @see{metatable}.
3027
3028Returns the type of the pushed value.
3029
3030}
3031
3032@APIEntry{void *lua_getextraspace (lua_State *L);|
3033@apii{0,0,-}
3034
3035Returns a pointer to a raw memory area associated with the
3036given Lua state.
3037The application can use this area for any purpose;
3038Lua does not use it for anything.
3039
3040Each new thread has this area initialized with a copy
3041of the area of the @x{main thread}.
3042
3043By default, this area has the size of a pointer to void,
3044but you can recompile Lua with a different size for this area.
3045(See @id{LUA_EXTRASPACE} in @id{luaconf.h}.)
3046
3047}
3048
3049@APIEntry{int lua_getglobal (lua_State *L, const char *name);|
3050@apii{0,1,e}
3051
3052Pushes onto the stack the value of the global @id{name}.
3053Returns the type of that value.
3054
3055}
3056
3057@APIEntry{int lua_geti (lua_State *L, int index, lua_Integer i);|
3058@apii{0,1,e}
3059
3060Pushes onto the stack the value @T{t[i]},
3061where @id{t} is the value at the given index.
3062As in Lua, this function may trigger a metamethod
3063for the @Q{index} event @see{metatable}.
3064
3065Returns the type of the pushed value.
3066
3067}
3068
3069@APIEntry{int lua_getmetatable (lua_State *L, int index);|
3070@apii{0,0|1,-}
3071
3072If the value at the given index has a metatable,
3073the function pushes that metatable onto the stack and @N{returns 1}.
3074Otherwise,
3075the function @N{returns 0} and pushes nothing on the stack.
3076
3077}
3078
3079@APIEntry{int lua_gettable (lua_State *L, int index);|
3080@apii{1,1,e}
3081
3082Pushes onto the stack the value @T{t[k]},
3083where @id{t} is the value at the given index
3084and @id{k} is the value at the top of the stack.
3085
3086This function pops the key from the stack,
3087pushing the resulting value in its place.
3088As in Lua, this function may trigger a metamethod
3089for the @Q{index} event @see{metatable}.
3090
3091Returns the type of the pushed value.
3092
3093}
3094
3095@APIEntry{int lua_gettop (lua_State *L);|
3096@apii{0,0,-}
3097
3098Returns the index of the top element in the stack.
3099Because indices start @N{at 1},
3100this result is equal to the number of elements in the stack;
3101in particular, @N{0 means} an empty stack.
3102
3103}
3104
3105@APIEntry{int lua_getiuservalue (lua_State *L, int index, int n);|
3106@apii{0,1,-}
3107
3108Pushes onto the stack the @id{n}-th user value associated with the
3109full userdata at the given index and
3110returns the type of the pushed value.
3111
3112If the userdata does not have that value,
3113pushes @nil and returns @Lid{LUA_TNONE}.
3114
3115}
3116
3117@APIEntry{void lua_insert (lua_State *L, int index);|
3118@apii{1,1,-}
3119
3120Moves the top element into the given valid index,
3121shifting up the elements above this index to open space.
3122This function cannot be called with a pseudo-index,
3123because a pseudo-index is not an actual stack position.
3124
3125}
3126
3127@APIEntry{typedef @ldots lua_Integer;|
3128
3129The type of integers in Lua.
3130
3131By default this type is @id{long long},
3132(usually a 64-bit two-complement integer),
3133but that can be changed to @id{long} or @id{int}
3134(usually a 32-bit two-complement integer).
3135(See @id{LUA_INT_TYPE} in @id{luaconf.h}.)
3136
3137Lua also defines the constants
3138@defid{LUA_MININTEGER} and @defid{LUA_MAXINTEGER},
3139with the minimum and the maximum values that fit in this type.
3140
3141}
3142
3143@APIEntry{int lua_isboolean (lua_State *L, int index);|
3144@apii{0,0,-}
3145
3146Returns 1 if the value at the given index is a boolean,
3147and @N{0 otherwise}.
3148
3149}
3150
3151@APIEntry{int lua_iscfunction (lua_State *L, int index);|
3152@apii{0,0,-}
3153
3154Returns 1 if the value at the given index is a @N{C function},
3155and @N{0 otherwise}.
3156
3157}
3158
3159@APIEntry{int lua_isfunction (lua_State *L, int index);|
3160@apii{0,0,-}
3161
3162Returns 1 if the value at the given index is a function
3163(either C or Lua), and @N{0 otherwise}.
3164
3165}
3166
3167@APIEntry{int lua_isinteger (lua_State *L, int index);|
3168@apii{0,0,-}
3169
3170Returns 1 if the value at the given index is an integer
3171(that is, the value is a number and is represented as an integer),
3172and @N{0 otherwise}.
3173
3174}
3175
3176@APIEntry{int lua_islightuserdata (lua_State *L, int index);|
3177@apii{0,0,-}
3178
3179Returns 1 if the value at the given index is a light userdata,
3180and @N{0 otherwise}.
3181
3182}
3183
3184@APIEntry{int lua_isnil (lua_State *L, int index);|
3185@apii{0,0,-}
3186
3187Returns 1 if the value at the given index is @nil,
3188and @N{0 otherwise}.
3189
3190}
3191
3192@APIEntry{int lua_isnone (lua_State *L, int index);|
3193@apii{0,0,-}
3194
3195Returns 1 if the given index is not valid,
3196and @N{0 otherwise}.
3197
3198}
3199
3200@APIEntry{int lua_isnoneornil (lua_State *L, int index);|
3201@apii{0,0,-}
3202
3203Returns 1 if the given index is not valid
3204or if the value at this index is @nil,
3205and @N{0 otherwise}.
3206
3207}
3208
3209@APIEntry{int lua_isnumber (lua_State *L, int index);|
3210@apii{0,0,-}
3211
3212Returns 1 if the value at the given index is a number
3213or a string convertible to a number,
3214and @N{0 otherwise}.
3215
3216}
3217
3218@APIEntry{int lua_isstring (lua_State *L, int index);|
3219@apii{0,0,-}
3220
3221Returns 1 if the value at the given index is a string
3222or a number (which is always convertible to a string),
3223and @N{0 otherwise}.
3224
3225}
3226
3227@APIEntry{int lua_istable (lua_State *L, int index);|
3228@apii{0,0,-}
3229
3230Returns 1 if the value at the given index is a table,
3231and @N{0 otherwise}.
3232
3233}
3234
3235@APIEntry{int lua_isthread (lua_State *L, int index);|
3236@apii{0,0,-}
3237
3238Returns 1 if the value at the given index is a thread,
3239and @N{0 otherwise}.
3240
3241}
3242
3243@APIEntry{int lua_isuserdata (lua_State *L, int index);|
3244@apii{0,0,-}
3245
3246Returns 1 if the value at the given index is a userdata
3247(either full or light), and @N{0 otherwise}.
3248
3249}
3250
3251@APIEntry{int lua_isyieldable (lua_State *L);|
3252@apii{0,0,-}
3253
3254Returns 1 if the given coroutine can yield,
3255and @N{0 otherwise}.
3256
3257}
3258
3259@APIEntry{typedef @ldots lua_KContext;|
3260
3261The type for continuation-function contexts.
3262It must be a numeric type.
3263This type is defined as @id{intptr_t}
3264when @id{intptr_t} is available,
3265so that it can store pointers too.
3266Otherwise, it is defined as @id{ptrdiff_t}.
3267
3268}
3269
3270@APIEntry{
3271typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);|
3272
3273Type for continuation functions @see{continuations}.
3274
3275}
3276
3277@APIEntry{void lua_len (lua_State *L, int index);|
3278@apii{0,1,e}
3279
3280Returns the length of the value at the given index.
3281It is equivalent to the @Char{#} operator in Lua @see{len-op} and
3282may trigger a metamethod for the @Q{length} event @see{metatable}.
3283The result is pushed on the stack.
3284
3285}
3286
3287@APIEntry{
3288int lua_load (lua_State *L,
3289 lua_Reader reader,
3290 void *data,
3291 const char *chunkname,
3292 const char *mode);|
3293@apii{0,1,-}
3294
3295Loads a Lua chunk without running it.
3296If there are no errors,
3297@id{lua_load} pushes the compiled chunk as a Lua
3298function on top of the stack.
3299Otherwise, it pushes an error message.
3300
3301The return values of @id{lua_load} are:
3302@description{
3303
3304@item{@Lid{LUA_OK}| no errors;}
3305
3306@item{@defid{LUA_ERRSYNTAX}|
3307syntax error during precompilation;}
3308
3309@item{@Lid{LUA_ERRMEM}|
3310@x{memory allocation (out-of-memory) error};}
3311
3312@item{@Lid{LUA_ERRGCMM}|
3313error while running a @idx{__gc} metamethod.
3314(This error has no relation with the chunk being loaded.
3315It is generated by the garbage collector.)
3316}
3317
3318}
3319
3320The @id{lua_load} function uses a user-supplied @id{reader} function
3321to read the chunk @seeC{lua_Reader}.
3322The @id{data} argument is an opaque value passed to the reader function.
3323
3324The @id{chunkname} argument gives a name to the chunk,
3325which is used for error messages and in debug information @see{debugI}.
3326
3327@id{lua_load} automatically detects whether the chunk is text or binary
3328and loads it accordingly (see program @idx{luac}).
3329The string @id{mode} works as in function @Lid{load},
3330with the addition that
3331a @id{NULL} value is equivalent to the string @St{bt}.
3332
3333@id{lua_load} uses the stack internally,
3334so the reader function must always leave the stack
3335unmodified when returning.
3336
3337If the resulting function has upvalues,
3338its first upvalue is set to the value of the @x{global environment}
3339stored at index @id{LUA_RIDX_GLOBALS} in the registry @see{registry}.
3340When loading main chunks,
3341this upvalue will be the @id{_ENV} variable @see{globalenv}.
3342Other upvalues are initialized with @nil.
3343
3344}
3345
3346@APIEntry{lua_State *lua_newstate (lua_Alloc f, void *ud);|
3347@apii{0,0,-}
3348
3349Creates a new thread running in a new, independent state.
3350Returns @id{NULL} if it cannot create the thread or the state
3351(due to lack of memory).
3352The argument @id{f} is the @x{allocator function};
3353Lua does all memory allocation for this state
3354through this function @seeF{lua_Alloc}.
3355The second argument, @id{ud}, is an opaque pointer that Lua
3356passes to the allocator in every call.
3357
3358}
3359
3360@APIEntry{void lua_newtable (lua_State *L);|
3361@apii{0,1,m}
3362
3363Creates a new empty table and pushes it onto the stack.
3364It is equivalent to @T{lua_createtable(L, 0, 0)}.
3365
3366}
3367
3368@APIEntry{lua_State *lua_newthread (lua_State *L);|
3369@apii{0,1,m}
3370
3371Creates a new thread, pushes it on the stack,
3372and returns a pointer to a @Lid{lua_State} that represents this new thread.
3373The new thread returned by this function shares with the original thread
3374its global environment,
3375but has an independent execution stack.
3376
3377There is no explicit function to close or to destroy a thread.
3378Threads are subject to garbage collection,
3379like any Lua object.
3380
3381}
3382
3383@APIEntry{void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);|
3384@apii{0,1,m}
3385
3386This function creates and pushes on the stack a new full userdata,
3387with @id{nuvalue} associated Lua values (called @id{user values})
3388plus an associated block of raw memory with @id{size} bytes.
3389(The user values can be set and read with the functions
3390@Lid{lua_setiuservalue} and @Lid{lua_getiuservalue}.)
3391
3392The function returns the address of the block of memory.
3393
3394}
3395
3396@APIEntry{int lua_next (lua_State *L, int index);|
3397@apii{1,2|0,v}
3398
3399Pops a key from the stack,
3400and pushes a key@En{}value pair from the table at the given index
3401(the @Q{next} pair after the given key).
3402If there are no more elements in the table,
3403then @Lid{lua_next} returns 0 (and pushes nothing).
3404
3405A typical traversal looks like this:
3406@verbatim{
3407/* table is in the stack at index 't' */
3408lua_pushnil(L); /* first key */
3409while (lua_next(L, t) != 0) {
3410 /* uses 'key' (at index -2) and 'value' (at index -1) */
3411 printf("%s - %s\n",
3412 lua_typename(L, lua_type(L, -2)),
3413 lua_typename(L, lua_type(L, -1)));
3414 /* removes 'value'; keeps 'key' for next iteration */
3415 lua_pop(L, 1);
3416}
3417}
3418
3419While traversing a table,
3420do not call @Lid{lua_tolstring} directly on a key,
3421unless you know that the key is actually a string.
3422Recall that @Lid{lua_tolstring} may change
3423the value at the given index;
3424this confuses the next call to @Lid{lua_next}.
3425
3426This function may raise an error if the given key
3427is neither @nil nor present in the table.
3428See function @Lid{next} for the caveats of modifying
3429the table during its traversal.
3430
3431}
3432
3433@APIEntry{typedef @ldots lua_Number;|
3434
3435The type of floats in Lua.
3436
3437By default this type is double,
3438but that can be changed to a single float or a long double.
3439(See @id{LUA_FLOAT_TYPE} in @id{luaconf.h}.)
3440
3441}
3442
3443@APIEntry{int lua_numbertointeger (lua_Number n, lua_Integer *p);|
3444
3445Converts a Lua float to a Lua integer.
3446This macro assumes that @id{n} has an integral value.
3447If that value is within the range of Lua integers,
3448it is converted to an integer and assigned to @T{*p}.
3449The macro results in a boolean indicating whether the
3450conversion was successful.
3451(Note that this range test can be tricky to do
3452correctly without this macro,
3453due to roundings.)
3454
3455This macro may evaluate its arguments more than once.
3456
3457}
3458
3459@APIEntry{int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);|
3460@apii{nargs + 1,nresults|1,-}
3461
3462Calls a function (or a callable object) in protected mode.
3463
3464Both @id{nargs} and @id{nresults} have the same meaning as
3465in @Lid{lua_call}.
3466If there are no errors during the call,
3467@Lid{lua_pcall} behaves exactly like @Lid{lua_call}.
3468However, if there is any error,
3469@Lid{lua_pcall} catches it,
3470pushes a single value on the stack (the error object),
3471and returns an error code.
3472Like @Lid{lua_call},
3473@Lid{lua_pcall} always removes the function
3474and its arguments from the stack.
3475
3476If @id{msgh} is 0,
3477then the error object returned on the stack
3478is exactly the original error object.
3479Otherwise, @id{msgh} is the stack index of a
3480@emph{message handler}.
3481(This index cannot be a pseudo-index.)
3482In case of runtime errors,
3483this function will be called with the error object
3484and its return value will be the object
3485returned on the stack by @Lid{lua_pcall}.
3486
3487Typically, the message handler is used to add more debug
3488information to the error object, such as a stack traceback.
3489Such information cannot be gathered after the return of @Lid{lua_pcall},
3490since by then the stack has unwound.
3491
3492The @Lid{lua_pcall} function returns one of the following constants
3493(defined in @id{lua.h}):
3494@description{
3495
3496@item{@defid{LUA_OK} (0)|
3497success.}
3498
3499@item{@defid{LUA_ERRRUN}|
3500a runtime error.
3501}
3502
3503@item{@defid{LUA_ERRMEM}|
3504@x{memory allocation error}.
3505For such errors, Lua does not call the @x{message handler}.
3506}
3507
3508@item{@defid{LUA_ERRERR}|
3509error while running the @x{message handler}.
3510}
3511
3512@item{@defid{LUA_ERRGCMM}|
3513error while running a @idx{__gc} metamethod.
3514For such errors, Lua does not call the @x{message handler}
3515(as this kind of error typically has no relation
3516with the function being called).
3517}
3518
3519}
3520
3521}
3522
3523@APIEntry{
3524int lua_pcallk (lua_State *L,
3525 int nargs,
3526 int nresults,
3527 int msgh,
3528 lua_KContext ctx,
3529 lua_KFunction k);|
3530@apii{nargs + 1,nresults|1,-}
3531
3532This function behaves exactly like @Lid{lua_pcall},
3533but allows the called function to yield @see{continuations}.
3534
3535}
3536
3537@APIEntry{void lua_pop (lua_State *L, int n);|
3538@apii{n,0,-}
3539
3540Pops @id{n} elements from the stack.
3541
3542}
3543
3544@APIEntry{void lua_pushboolean (lua_State *L, int b);|
3545@apii{0,1,-}
3546
3547Pushes a boolean value with value @id{b} onto the stack.
3548
3549}
3550
3551@APIEntry{void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);|
3552@apii{n,1,m}
3553
3554Pushes a new @N{C closure} onto the stack.
3555This function receives a pointer to a @N{C function}
3556and pushes onto the stack a Lua value of type @id{function} that,
3557when called, invokes the corresponding @N{C function}.
3558The parameter @id{n} tells how many upvalues this function will have
3559@see{c-closure}.
3560
3561Any function to be callable by Lua must
3562follow the correct protocol to receive its parameters
3563and return its results @seeC{lua_CFunction}.
3564
3565When a @N{C function} is created,
3566it is possible to associate some values with it,
3567thus creating a @x{@N{C closure}} @see{c-closure};
3568these values are then accessible to the function whenever it is called.
3569To associate values with a @N{C function},
3570first these values must be pushed onto the stack
3571(when there are multiple values, the first value is pushed first).
3572Then @Lid{lua_pushcclosure}
3573is called to create and push the @N{C function} onto the stack,
3574with the argument @id{n} telling how many values will be
3575associated with the function.
3576@Lid{lua_pushcclosure} also pops these values from the stack.
3577
3578The maximum value for @id{n} is 255.
3579
3580When @id{n} is zero,
3581this function creates a @def{light @N{C function}},
3582which is just a pointer to the @N{C function}.
3583In that case, it never raises a memory error.
3584
3585}
3586
3587@APIEntry{void lua_pushcfunction (lua_State *L, lua_CFunction f);|
3588@apii{0,1,-}
3589
3590Pushes a @N{C function} onto the stack.
3591
3592}
3593
3594@APIEntry{const char *lua_pushfstring (lua_State *L, const char *fmt, ...);|
3595@apii{0,1,v}
3596
3597Pushes onto the stack a formatted string
3598and returns a pointer to this string.
3599It is similar to the @ANSI{sprintf},
3600but has two important differences.
3601First,
3602you do not have to allocate space for the result;
3603the result is a Lua string and Lua takes care of memory allocation
3604(and deallocation, through garbage collection).
3605Second,
3606the conversion specifiers are quite restricted.
3607There are no flags, widths, or precisions.
3608The conversion specifiers can only be
3609@Char{%%} (inserts the character @Char{%}),
3610@Char{%s} (inserts a zero-terminated string, with no size restrictions),
3611@Char{%f} (inserts a @Lid{lua_Number}),
3612@Char{%I} (inserts a @Lid{lua_Integer}),
3613@Char{%p} (inserts a pointer as a hexadecimal numeral),
3614@Char{%d} (inserts an @T{int}),
3615@Char{%c} (inserts an @T{int} as a one-byte character), and
3616@Char{%U} (inserts a @T{long int} as a @x{UTF-8} byte sequence).
3617
3618This function may raise errors due to memory overflow
3619or an invalid conversion specifier.
3620
3621}
3622
3623@APIEntry{void lua_pushglobaltable (lua_State *L);|
3624@apii{0,1,-}
3625
3626Pushes the @x{global environment} onto the stack.
3627
3628}
3629
3630@APIEntry{void lua_pushinteger (lua_State *L, lua_Integer n);|
3631@apii{0,1,-}
3632
3633Pushes an integer with value @id{n} onto the stack.
3634
3635}
3636
3637@APIEntry{void lua_pushlightuserdata (lua_State *L, void *p);|
3638@apii{0,1,-}
3639
3640Pushes a light userdata onto the stack.
3641
3642Userdata represent @N{C values} in Lua.
3643A @def{light userdata} represents a pointer, a @T{void*}.
3644It is a value (like a number):
3645you do not create it, it has no individual metatable,
3646and it is not collected (as it was never created).
3647A light userdata is equal to @Q{any}
3648light userdata with the same @N{C address}.
3649
3650}
3651
3652@APIEntry{const char *lua_pushliteral (lua_State *L, const char *s);|
3653@apii{0,1,m}
3654
3655This macro is equivalent to @Lid{lua_pushstring},
3656but should be used only when @id{s} is a literal string.
3657
3658}
3659
3660@APIEntry{const char *lua_pushlstring (lua_State *L, const char *s, size_t len);|
3661@apii{0,1,m}
3662
3663Pushes the string pointed to by @id{s} with size @id{len}
3664onto the stack.
3665Lua makes (or reuses) an internal copy of the given string,
3666so the memory at @id{s} can be freed or reused immediately after
3667the function returns.
3668The string can contain any binary data,
3669including @x{embedded zeros}.
3670
3671Returns a pointer to the internal copy of the string.
3672
3673}
3674
3675@APIEntry{void lua_pushnil (lua_State *L);|
3676@apii{0,1,-}
3677
3678Pushes a nil value onto the stack.
3679
3680}
3681
3682@APIEntry{void lua_pushnumber (lua_State *L, lua_Number n);|
3683@apii{0,1,-}
3684
3685Pushes a float with value @id{n} onto the stack.
3686
3687}
3688
3689@APIEntry{const char *lua_pushstring (lua_State *L, const char *s);|
3690@apii{0,1,m}
3691
3692Pushes the zero-terminated string pointed to by @id{s}
3693onto the stack.
3694Lua makes (or reuses) an internal copy of the given string,
3695so the memory at @id{s} can be freed or reused immediately after
3696the function returns.
3697
3698Returns a pointer to the internal copy of the string.
3699
3700If @id{s} is @id{NULL}, pushes @nil and returns @id{NULL}.
3701
3702}
3703
3704@APIEntry{int lua_pushthread (lua_State *L);|
3705@apii{0,1,-}
3706
3707Pushes the thread represented by @id{L} onto the stack.
3708Returns 1 if this thread is the @x{main thread} of its state.
3709
3710}
3711
3712@APIEntry{void lua_pushvalue (lua_State *L, int index);|
3713@apii{0,1,-}
3714
3715Pushes a copy of the element at the given index
3716onto the stack.
3717
3718}
3719
3720@APIEntry{
3721const char *lua_pushvfstring (lua_State *L,
3722 const char *fmt,
3723 va_list argp);|
3724@apii{0,1,v}
3725
3726Equivalent to @Lid{lua_pushfstring}, except that it receives a @id{va_list}
3727instead of a variable number of arguments.
3728
3729}
3730
3731@APIEntry{int lua_rawequal (lua_State *L, int index1, int index2);|
3732@apii{0,0,-}
3733
3734Returns 1 if the two values in indices @id{index1} and
3735@id{index2} are primitively equal
3736(that is, without calling the @idx{__eq} metamethod).
3737Otherwise @N{returns 0}.
3738Also @N{returns 0} if any of the indices are not valid.
3739
3740}
3741
3742@APIEntry{int lua_rawget (lua_State *L, int index);|
3743@apii{1,1,-}
3744
3745Similar to @Lid{lua_gettable}, but does a raw access
3746(i.e., without metamethods).
3747
3748}
3749
3750@APIEntry{int lua_rawgeti (lua_State *L, int index, lua_Integer n);|
3751@apii{0,1,-}
3752
3753Pushes onto the stack the value @T{t[n]},
3754where @id{t} is the table at the given index.
3755The access is raw,
3756that is, it does not invoke the @idx{__index} metamethod.
3757
3758Returns the type of the pushed value.
3759
3760}
3761
3762@APIEntry{int lua_rawgetp (lua_State *L, int index, const void *p);|
3763@apii{0,1,-}
3764
3765Pushes onto the stack the value @T{t[k]},
3766where @id{t} is the table at the given index and
3767@id{k} is the pointer @id{p} represented as a light userdata.
3768The access is raw;
3769that is, it does not invoke the @idx{__index} metamethod.
3770
3771Returns the type of the pushed value.
3772
3773}
3774
3775@APIEntry{lua_Unsigned lua_rawlen (lua_State *L, int index);|
3776@apii{0,0,-}
3777
3778Returns the raw @Q{length} of the value at the given index:
3779for strings, this is the string length;
3780for tables, this is the result of the length operator (@Char{#})
3781with no metamethods;
3782for userdata, this is the size of the block of memory allocated
3783for the userdata;
3784for other values, it @N{is 0}.
3785
3786}
3787
3788@APIEntry{void lua_rawset (lua_State *L, int index);|
3789@apii{2,0,m}
3790
3791Similar to @Lid{lua_settable}, but does a raw assignment
3792(i.e., without metamethods).
3793
3794}
3795
3796@APIEntry{void lua_rawseti (lua_State *L, int index, lua_Integer i);|
3797@apii{1,0,m}
3798
3799Does the equivalent of @T{t[i] = v},
3800where @id{t} is the table at the given index
3801and @id{v} is the value at the top of the stack.
3802
3803This function pops the value from the stack.
3804The assignment is raw,
3805that is, it does not invoke the @idx{__newindex} metamethod.
3806
3807}
3808
3809@APIEntry{void lua_rawsetp (lua_State *L, int index, const void *p);|
3810@apii{1,0,m}
3811
3812Does the equivalent of @T{t[p] = v},
3813where @id{t} is the table at the given index,
3814@id{p} is encoded as a light userdata,
3815and @id{v} is the value at the top of the stack.
3816
3817This function pops the value from the stack.
3818The assignment is raw,
3819that is, it does not invoke @idx{__newindex} metamethod.
3820
3821}
3822
3823@APIEntry{
3824typedef const char * (*lua_Reader) (lua_State *L,
3825 void *data,
3826 size_t *size);|
3827
3828The reader function used by @Lid{lua_load}.
3829Every time it needs another piece of the chunk,
3830@Lid{lua_load} calls the reader,
3831passing along its @id{data} parameter.
3832The reader must return a pointer to a block of memory
3833with a new piece of the chunk
3834and set @id{size} to the block size.
3835The block must exist until the reader function is called again.
3836To signal the end of the chunk,
3837the reader must return @id{NULL} or set @id{size} to zero.
3838The reader function may return pieces of any size greater than zero.
3839
3840}
3841
3842@APIEntry{void lua_register (lua_State *L, const char *name, lua_CFunction f);|
3843@apii{0,0,e}
3844
3845Sets the @N{C function} @id{f} as the new value of global @id{name}.
3846It is defined as a macro:
3847@verbatim{
3848#define lua_register(L,n,f) \
3849 (lua_pushcfunction(L, f), lua_setglobal(L, n))
3850}
3851
3852}
3853
3854@APIEntry{void lua_remove (lua_State *L, int index);|
3855@apii{1,0,-}
3856
3857Removes the element at the given valid index,
3858shifting down the elements above this index to fill the gap.
3859This function cannot be called with a pseudo-index,
3860because a pseudo-index is not an actual stack position.
3861
3862}
3863
3864@APIEntry{void lua_replace (lua_State *L, int index);|
3865@apii{1,0,-}
3866
3867Moves the top element into the given valid index
3868without shifting any element
3869(therefore replacing the value at that given index),
3870and then pops the top element.
3871
3872}
3873
3874@APIEntry{int lua_resume (lua_State *L, lua_State *from, int nargs,
3875 int *nresults);|
3876@apii{?,?,-}
3877
3878Starts and resumes a coroutine in the given thread @id{L}.
3879
3880To start a coroutine,
3881you push onto the thread stack the main function plus any arguments;
3882then you call @Lid{lua_resume},
3883with @id{nargs} being the number of arguments.
3884This call returns when the coroutine suspends or finishes its execution.
3885When it returns,
3886@id{nresults} is updated and
3887the top of the stack contains
3888the @id{nresults} values passed to @Lid{lua_yield}
3889or returned by the body function.
3890@Lid{lua_resume} returns
3891@Lid{LUA_YIELD} if the coroutine yields,
3892@Lid{LUA_OK} if the coroutine finishes its execution
3893without errors,
3894or an error code in case of errors @seeC{lua_pcall}.
3895
3896In case of errors,
3897the stack is not unwound,
3898so you can use the debug API over it.
3899The error object is on the top of the stack.
3900
3901To resume a coroutine,
3902you remove all results from the last @Lid{lua_yield},
3903put on its stack only the values to
3904be passed as results from @id{yield},
3905and then call @Lid{lua_resume}.
3906
3907The parameter @id{from} represents the coroutine that is resuming @id{L}.
3908If there is no such coroutine,
3909this parameter can be @id{NULL}.
3910
3911}
3912
3913@APIEntry{void lua_rotate (lua_State *L, int idx, int n);|
3914@apii{0,0,-}
3915
3916Rotates the stack elements between the valid index @id{idx}
3917and the top of the stack.
3918The elements are rotated @id{n} positions in the direction of the top,
3919for a positive @id{n},
3920or @T{-n} positions in the direction of the bottom,
3921for a negative @id{n}.
3922The absolute value of @id{n} must not be greater than the size
3923of the slice being rotated.
3924This function cannot be called with a pseudo-index,
3925because a pseudo-index is not an actual stack position.
3926
3927}
3928
3929@APIEntry{void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);|
3930@apii{0,0,-}
3931
3932Changes the @x{allocator function} of a given state to @id{f}
3933with user data @id{ud}.
3934
3935}
3936
3937@APIEntry{void lua_setfield (lua_State *L, int index, const char *k);|
3938@apii{1,0,e}
3939
3940Does the equivalent to @T{t[k] = v},
3941where @id{t} is the value at the given index
3942and @id{v} is the value at the top of the stack.
3943
3944This function pops the value from the stack.
3945As in Lua, this function may trigger a metamethod
3946for the @Q{newindex} event @see{metatable}.
3947
3948}
3949
3950@APIEntry{void lua_setglobal (lua_State *L, const char *name);|
3951@apii{1,0,e}
3952
3953Pops a value from the stack and
3954sets it as the new value of global @id{name}.
3955
3956}
3957
3958@APIEntry{void lua_seti (lua_State *L, int index, lua_Integer n);|
3959@apii{1,0,e}
3960
3961Does the equivalent to @T{t[n] = v},
3962where @id{t} is the value at the given index
3963and @id{v} is the value at the top of the stack.
3964
3965This function pops the value from the stack.
3966As in Lua, this function may trigger a metamethod
3967for the @Q{newindex} event @see{metatable}.
3968
3969}
3970
3971@APIEntry{void lua_setmetatable (lua_State *L, int index);|
3972@apii{1,0,-}
3973
3974Pops a table from the stack and
3975sets it as the new metatable for the value at the given index.
3976
3977}
3978
3979@APIEntry{void lua_settable (lua_State *L, int index);|
3980@apii{2,0,e}
3981
3982Does the equivalent to @T{t[k] = v},
3983where @id{t} is the value at the given index,
3984@id{v} is the value at the top of the stack,
3985and @id{k} is the value just below the top.
3986
3987This function pops both the key and the value from the stack.
3988As in Lua, this function may trigger a metamethod
3989for the @Q{newindex} event @see{metatable}.
3990
3991}
3992
3993@APIEntry{void lua_settop (lua_State *L, int index);|
3994@apii{?,?,-}
3995
3996Accepts any index, @N{or 0},
3997and sets the stack top to this index.
3998If the new top is larger than the old one,
3999then the new elements are filled with @nil.
4000If @id{index} @N{is 0}, then all stack elements are removed.
4001
4002}
4003
4004@APIEntry{int lua_setiuservalue (lua_State *L, int index, int n);|
4005@apii{1,0,-}
4006
4007Pops a value from the stack and sets it as
4008the new @id{n}-th user value associated to the
4009full userdata at the given index.
4010Returns 0 if the userdata does not have that value.
4011
4012}
4013
4014@APIEntry{typedef struct lua_State lua_State;|
4015
4016An opaque structure that points to a thread and indirectly
4017(through the thread) to the whole state of a Lua interpreter.
4018The Lua library is fully reentrant:
4019it has no global variables.
4020All information about a state is accessible through this structure.
4021
4022A pointer to this structure must be passed as the first argument to
4023every function in the library, except to @Lid{lua_newstate},
4024which creates a Lua state from scratch.
4025
4026}
4027
4028@APIEntry{int lua_status (lua_State *L);|
4029@apii{0,0,-}
4030
4031Returns the status of the thread @id{L}.
4032
4033The status can be 0 (@Lid{LUA_OK}) for a normal thread,
4034an error code if the thread finished the execution
4035of a @Lid{lua_resume} with an error,
4036or @defid{LUA_YIELD} if the thread is suspended.
4037
4038You can only call functions in threads with status @Lid{LUA_OK}.
4039You can resume threads with status @Lid{LUA_OK}
4040(to start a new coroutine) or @Lid{LUA_YIELD}
4041(to resume a coroutine).
4042
4043}
4044
4045@APIEntry{size_t lua_stringtonumber (lua_State *L, const char *s);|
4046@apii{0,1,-}
4047
4048Converts the zero-terminated string @id{s} to a number,
4049pushes that number into the stack,
4050and returns the total size of the string,
4051that is, its length plus one.
4052The conversion can result in an integer or a float,
4053according to the lexical conventions of Lua @see{lexical}.
4054The string may have leading and trailing spaces and a sign.
4055If the string is not a valid numeral,
4056returns 0 and pushes nothing.
4057(Note that the result can be used as a boolean,
4058true if the conversion succeeds.)
4059
4060}
4061
4062@APIEntry{int lua_toboolean (lua_State *L, int index);|
4063@apii{0,0,-}
4064
4065Converts the Lua value at the given index to a @N{C boolean}
4066value (@N{0 or 1}).
4067Like all tests in Lua,
4068@Lid{lua_toboolean} returns true for any Lua value
4069different from @false and @nil;
4070otherwise it returns false.
4071(If you want to accept only actual boolean values,
4072use @Lid{lua_isboolean} to test the value's type.)
4073
4074}
4075
4076@APIEntry{lua_CFunction lua_tocfunction (lua_State *L, int index);|
4077@apii{0,0,-}
4078
4079Converts a value at the given index to a @N{C function}.
4080That value must be a @N{C function};
4081otherwise, returns @id{NULL}.
4082
4083}
4084
4085@APIEntry{lua_Integer lua_tointeger (lua_State *L, int index);|
4086@apii{0,0,-}
4087
4088Equivalent to @Lid{lua_tointegerx} with @id{isnum} equal to @id{NULL}.
4089
4090}
4091
4092@APIEntry{lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);|
4093@apii{0,0,-}
4094
4095Converts the Lua value at the given index
4096to the signed integral type @Lid{lua_Integer}.
4097The Lua value must be an integer,
4098or a number or string convertible to an integer @see{coercion};
4099otherwise, @id{lua_tointegerx} @N{returns 0}.
4100
4101If @id{isnum} is not @id{NULL},
4102its referent is assigned a boolean value that
4103indicates whether the operation succeeded.
4104
4105}
4106
4107@APIEntry{const char *lua_tolstring (lua_State *L, int index, size_t *len);|
4108@apii{0,0,m}
4109
4110Converts the Lua value at the given index to a @N{C string}.
4111If @id{len} is not @id{NULL},
4112it sets @T{*len} with the string length.
4113The Lua value must be a string or a number;
4114otherwise, the function returns @id{NULL}.
4115If the value is a number,
4116then @id{lua_tolstring} also
4117@emph{changes the actual value in the stack to a string}.
4118(This change confuses @Lid{lua_next}
4119when @id{lua_tolstring} is applied to keys during a table traversal.)
4120
4121@id{lua_tolstring} returns a pointer
4122to a string inside the Lua state.
4123This string always has a zero (@Char{\0})
4124after its last character (as @N{in C}),
4125but can contain other zeros in its body.
4126
4127Because Lua has garbage collection,
4128there is no guarantee that the pointer returned by @id{lua_tolstring}
4129will be valid after the corresponding Lua value is removed from the stack.
4130
4131}
4132
4133@APIEntry{lua_Number lua_tonumber (lua_State *L, int index);|
4134@apii{0,0,-}
4135
4136Equivalent to @Lid{lua_tonumberx} with @id{isnum} equal to @id{NULL}.
4137
4138}
4139
4140@APIEntry{lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);|
4141@apii{0,0,-}
4142
4143Converts the Lua value at the given index
4144to the @N{C type} @Lid{lua_Number} @seeC{lua_Number}.
4145The Lua value must be a number or a string convertible to a number
4146@see{coercion};
4147otherwise, @Lid{lua_tonumberx} @N{returns 0}.
4148
4149If @id{isnum} is not @id{NULL},
4150its referent is assigned a boolean value that
4151indicates whether the operation succeeded.
4152
4153}
4154
4155@APIEntry{const void *lua_topointer (lua_State *L, int index);|
4156@apii{0,0,-}
4157
4158Converts the value at the given index to a generic
4159@N{C pointer} (@T{void*}).
4160The value can be a userdata, a table, a thread, or a function;
4161otherwise, @id{lua_topointer} returns @id{NULL}.
4162Different objects will give different pointers.
4163There is no way to convert the pointer back to its original value.
4164
4165Typically this function is used only for hashing and debug information.
4166
4167}
4168
4169@APIEntry{const char *lua_tostring (lua_State *L, int index);|
4170@apii{0,0,m}
4171
4172Equivalent to @Lid{lua_tolstring} with @id{len} equal to @id{NULL}.
4173
4174}
4175
4176@APIEntry{lua_State *lua_tothread (lua_State *L, int index);|
4177@apii{0,0,-}
4178
4179Converts the value at the given index to a Lua thread
4180(represented as @T{lua_State*}).
4181This value must be a thread;
4182otherwise, the function returns @id{NULL}.
4183
4184}
4185
4186@APIEntry{void *lua_touserdata (lua_State *L, int index);|
4187@apii{0,0,-}
4188
4189If the value at the given index is a full userdata,
4190returns its memory-block address.
4191If the value is a light userdata,
4192returns its pointer.
4193Otherwise, returns @id{NULL}.
4194
4195}
4196
4197@APIEntry{int lua_type (lua_State *L, int index);|
4198@apii{0,0,-}
4199
4200Returns the type of the value in the given valid index,
4201or @id{LUA_TNONE} for a non-valid (but acceptable) index.
4202The types returned by @Lid{lua_type} are coded by the following constants
4203defined in @id{lua.h}:
4204@defid{LUA_TNIL},
4205@defid{LUA_TNUMBER},
4206@defid{LUA_TBOOLEAN},
4207@defid{LUA_TSTRING},
4208@defid{LUA_TTABLE},
4209@defid{LUA_TFUNCTION},
4210@defid{LUA_TUSERDATA},
4211@defid{LUA_TTHREAD},
4212and
4213@defid{LUA_TLIGHTUSERDATA}.
4214
4215}
4216
4217@APIEntry{const char *lua_typename (lua_State *L, int tp);|
4218@apii{0,0,-}
4219
4220Returns the name of the type encoded by the value @id{tp},
4221which must be one the values returned by @Lid{lua_type}.
4222
4223}
4224
4225@APIEntry{typedef @ldots lua_Unsigned;|
4226
4227The unsigned version of @Lid{lua_Integer}.
4228
4229}
4230
4231@APIEntry{int lua_upvalueindex (int i);|
4232@apii{0,0,-}
4233
4234Returns the pseudo-index that represents the @id{i}-th upvalue of
4235the running function @see{c-closure}.
4236
4237}
4238
4239@APIEntry{lua_Number lua_version (lua_State *L);|
4240@apii{0,0,-}
4241
4242Returns the version number of this core.
4243
4244}
4245
4246@APIEntry{
4247typedef int (*lua_Writer) (lua_State *L,
4248 const void* p,
4249 size_t sz,
4250 void* ud);|
4251
4252The type of the writer function used by @Lid{lua_dump}.
4253Every time it produces another piece of chunk,
4254@Lid{lua_dump} calls the writer,
4255passing along the buffer to be written (@id{p}),
4256its size (@id{sz}),
4257and the @id{data} parameter supplied to @Lid{lua_dump}.
4258
4259The writer returns an error code:
4260@N{0 means} no errors;
4261any other value means an error and stops @Lid{lua_dump} from
4262calling the writer again.
4263
4264}
4265
4266@APIEntry{void lua_xmove (lua_State *from, lua_State *to, int n);|
4267@apii{?,?,-}
4268
4269Exchange values between different threads of the same state.
4270
4271This function pops @id{n} values from the stack @id{from},
4272and pushes them onto the stack @id{to}.
4273
4274}
4275
4276@APIEntry{int lua_yield (lua_State *L, int nresults);|
4277@apii{?,?,v}
4278
4279This function is equivalent to @Lid{lua_yieldk},
4280but it has no continuation @see{continuations}.
4281Therefore, when the thread resumes,
4282it continues the function that called
4283the function calling @id{lua_yield}.
4284To avoid surprises,
4285this function should be called only in a tail call.
4286
4287}
4288
4289
4290@APIEntry{
4291int lua_yieldk (lua_State *L,
4292 int nresults,
4293 lua_KContext ctx,
4294 lua_KFunction k);|
4295@apii{?,?,v}
4296
4297Yields a coroutine (thread).
4298
4299When a @N{C function} calls @Lid{lua_yieldk},
4300the running coroutine suspends its execution,
4301and the call to @Lid{lua_resume} that started this coroutine returns.
4302The parameter @id{nresults} is the number of values from the stack
4303that will be passed as results to @Lid{lua_resume}.
4304
4305When the coroutine is resumed again,
4306Lua calls the given @x{continuation function} @id{k} to continue
4307the execution of the @N{C function} that yielded @see{continuations}.
4308This continuation function receives the same stack
4309from the previous function,
4310with the @id{n} results removed and
4311replaced by the arguments passed to @Lid{lua_resume}.
4312Moreover,
4313the continuation function receives the value @id{ctx}
4314that was passed to @Lid{lua_yieldk}.
4315
4316Usually, this function does not return;
4317when the coroutine eventually resumes,
4318it continues executing the continuation function.
4319However, there is one special case,
4320which is when this function is called
4321from inside a line or a count hook @see{debugI}.
4322In that case, @id{lua_yieldk} should be called with no continuation
4323(probably in the form of @Lid{lua_yield}) and no results,
4324and the hook should return immediately after the call.
4325Lua will yield and,
4326when the coroutine resumes again,
4327it will continue the normal execution
4328of the (Lua) function that triggered the hook.
4329
4330This function can raise an error if it is called from a thread
4331with a pending C call with no continuation function
4332(what is called a @emphx{C-call boundary},
4333or it is called from a thread that is not running inside a resume
4334(typically the main thread).
4335
4336}
4337
4338}
4339
4340@sect2{debugI| @title{The Debug Interface}
4341
4342Lua has no built-in debugging facilities.
4343Instead, it offers a special interface
4344by means of functions and @emph{hooks}.
4345This interface allows the construction of different
4346kinds of debuggers, profilers, and other tools
4347that need @Q{inside information} from the interpreter.
4348
4349
4350@APIEntry{
4351typedef struct lua_Debug {
4352 int event;
4353 const char *name; /* (n) */
4354 const char *namewhat; /* (n) */
4355 const char *what; /* (S) */
4356 const char *source; /* (S) */
4357 int currentline; /* (l) */
4358 int linedefined; /* (S) */
4359 int lastlinedefined; /* (S) */
4360 unsigned char nups; /* (u) number of upvalues */
4361 unsigned char nparams; /* (u) number of parameters */
4362 char isvararg; /* (u) */
4363 char istailcall; /* (t) */
4364 unsigned short ftransfer; /* (r) index of first value transferred */
4365 unsigned short ntransfer; /* (r) number of transferred values */
4366 char short_src[LUA_IDSIZE]; /* (S) */
4367 /* private part */
4368 @rep{other fields}
4369} lua_Debug;
4370|
4371
4372A structure used to carry different pieces of
4373information about a function or an activation record.
4374@Lid{lua_getstack} fills only the private part
4375of this structure, for later use.
4376To fill the other fields of @Lid{lua_Debug} with useful information,
4377call @Lid{lua_getinfo}.
4378
4379The fields of @Lid{lua_Debug} have the following meaning:
4380@description{
4381
4382@item{@id{source}|
4383the name of the chunk that created the function.
4384If @T{source} starts with a @Char{@At},
4385it means that the function was defined in a file where
4386the file name follows the @Char{@At}.
4387If @T{source} starts with a @Char{=},
4388the remainder of its contents describe the source in a user-dependent manner.
4389Otherwise,
4390the function was defined in a string where
4391@T{source} is that string.
4392}
4393
4394@item{@id{short_src}|
4395a @Q{printable} version of @T{source}, to be used in error messages.
4396}
4397
4398@item{@id{linedefined}|
4399the line number where the definition of the function starts.
4400}
4401
4402@item{@id{lastlinedefined}|
4403the line number where the definition of the function ends.
4404}
4405
4406@item{@id{what}|
4407the string @T{"Lua"} if the function is a Lua function,
4408@T{"C"} if it is a @N{C function},
4409@T{"main"} if it is the main part of a chunk.
4410}
4411
4412@item{@id{currentline}|
4413the current line where the given function is executing.
4414When no line information is available,
4415@T{currentline} is set to @num{-1}.
4416}
4417
4418@item{@id{name}|
4419a reasonable name for the given function.
4420Because functions in Lua are first-class values,
4421they do not have a fixed name:
4422some functions can be the value of multiple global variables,
4423while others can be stored only in a table field.
4424The @T{lua_getinfo} function checks how the function was
4425called to find a suitable name.
4426If it cannot find a name,
4427then @id{name} is set to @id{NULL}.
4428}
4429
4430@item{@id{namewhat}|
4431explains the @T{name} field.
4432The value of @T{namewhat} can be
4433@T{"global"}, @T{"local"}, @T{"method"},
4434@T{"field"}, @T{"upvalue"}, or @T{""} (the empty string),
4435according to how the function was called.
4436(Lua uses the empty string when no other option seems to apply.)
4437}
4438
4439@item{@id{istailcall}|
4440true if this function invocation was called by a tail call.
4441In this case, the caller of this level is not in the stack.
4442}
4443
4444@item{@id{nups}|
4445the number of upvalues of the function.
4446}
4447
4448@item{@id{nparams}|
4449the number of parameters of the function
4450(always @N{0 for} @N{C functions}).
4451}
4452
4453@item{@id{isvararg}|
4454true if the function is a vararg function
4455(always true for @N{C functions}).
4456}
4457
4458@item{@id{ftransfer}|
4459the index on the stack of the first value being @Q{transferred},
4460that is, parameters in a call or return values in a return.
4461(The other values are in consecutive indices.)
4462Using this index, you can access and modify these values
4463through @Lid{lua_getlocal} and @Lid{lua_setlocal}.
4464This field is only meaningful during a
4465call hook, denoting the first parameter,
4466or a return hook, denoting the first value being returned.
4467(For call hooks, this value is always 1.)
4468}
4469
4470@item{@id{ntransfer}|
4471The number of values being transferred (see previous item).
4472(For calls of Lua functions,
4473this value is always equal to @id{nparams}.)
4474}
4475
4476}
4477
4478}
4479
4480@APIEntry{lua_Hook lua_gethook (lua_State *L);|
4481@apii{0,0,-}
4482
4483Returns the current hook function.
4484
4485}
4486
4487@APIEntry{int lua_gethookcount (lua_State *L);|
4488@apii{0,0,-}
4489
4490Returns the current hook count.
4491
4492}
4493
4494@APIEntry{int lua_gethookmask (lua_State *L);|
4495@apii{0,0,-}
4496
4497Returns the current hook mask.
4498
4499}
4500
4501@APIEntry{int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);|
4502@apii{0|1,0|1|2,m}
4503
4504Gets information about a specific function or function invocation.
4505
4506To get information about a function invocation,
4507the parameter @id{ar} must be a valid activation record that was
4508filled by a previous call to @Lid{lua_getstack} or
4509given as argument to a hook @seeC{lua_Hook}.
4510
4511To get information about a function, you push it onto the stack
4512and start the @id{what} string with the character @Char{>}.
4513(In that case,
4514@id{lua_getinfo} pops the function from the top of the stack.)
4515For instance, to know in which line a function @id{f} was defined,
4516you can write the following code:
4517@verbatim{
4518lua_Debug ar;
4519lua_getglobal(L, "f"); /* get global 'f' */
4520lua_getinfo(L, ">S", &ar);
4521printf("%d\n", ar.linedefined);
4522}
4523
4524Each character in the string @id{what}
4525selects some fields of the structure @id{ar} to be filled or
4526a value to be pushed on the stack:
4527@description{
4528
4529@item{@Char{n}| fills in the field @id{name} and @id{namewhat};
4530}
4531
4532@item{@Char{S}|
4533fills in the fields @id{source}, @id{short_src},
4534@id{linedefined}, @id{lastlinedefined}, and @id{what};
4535}
4536
4537@item{@Char{l}| fills in the field @id{currentline};
4538}
4539
4540@item{@Char{t}| fills in the field @id{istailcall};
4541}
4542
4543@item{@Char{u}| fills in the fields
4544@id{nups}, @id{nparams}, and @id{isvararg};
4545}
4546
4547@item{@Char{f}|
4548pushes onto the stack the function that is
4549running at the given level;
4550}
4551
4552@item{@Char{L}|
4553pushes onto the stack a table whose indices are the
4554numbers of the lines that are valid on the function.
4555(A @emph{valid line} is a line with some associated code,
4556that is, a line where you can put a break point.
4557Non-valid lines include empty lines and comments.)
4558
4559If this option is given together with option @Char{f},
4560its table is pushed after the function.
4561
4562This is the only option that can raise a memory error.
4563}
4564
4565}
4566
4567This function returns 0 if given an invalid option in @id{what}.
4568
4569}
4570
4571@APIEntry{const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);|
4572@apii{0,0|1,-}
4573
4574Gets information about a local variable or a temporary value
4575of a given activation record or a given function.
4576
4577In the first case,
4578the parameter @id{ar} must be a valid activation record that was
4579filled by a previous call to @Lid{lua_getstack} or
4580given as argument to a hook @seeC{lua_Hook}.
4581The index @id{n} selects which local variable to inspect;
4582see @Lid{debug.getlocal} for details about variable indices
4583and names.
4584
4585@Lid{lua_getlocal} pushes the variable's value onto the stack
4586and returns its name.
4587
4588In the second case, @id{ar} must be @id{NULL} and the function
4589to be inspected must be at the top of the stack.
4590In this case, only parameters of Lua functions are visible
4591(as there is no information about what variables are active)
4592and no values are pushed onto the stack.
4593
4594Returns @id{NULL} (and pushes nothing)
4595when the index is greater than
4596the number of active local variables.
4597
4598}
4599
4600@APIEntry{int lua_getstack (lua_State *L, int level, lua_Debug *ar);|
4601@apii{0,0,-}
4602
4603Gets information about the interpreter runtime stack.
4604
4605This function fills parts of a @Lid{lua_Debug} structure with
4606an identification of the @emph{activation record}
4607of the function executing at a given level.
4608@N{Level 0} is the current running function,
4609whereas level @M{n+1} is the function that has called level @M{n}
4610(except for tail calls, which do not count on the stack).
4611When there are no errors, @Lid{lua_getstack} returns 1;
4612when called with a level greater than the stack depth,
4613it returns 0.
4614
4615}
4616
4617@APIEntry{const char *lua_getupvalue (lua_State *L, int funcindex, int n);|
4618@apii{0,0|1,-}
4619
4620Gets information about the @id{n}-th upvalue
4621of the closure at index @id{funcindex}.
4622It pushes the upvalue's value onto the stack
4623and returns its name.
4624Returns @id{NULL} (and pushes nothing)
4625when the index @id{n} is greater than the number of upvalues.
4626
4627For @N{C functions}, this function uses the empty string @T{""}
4628as a name for all upvalues.
4629(For Lua functions,
4630upvalues are the external local variables that the function uses,
4631and that are consequently included in its closure.)
4632
4633Upvalues have no particular order,
4634as they are active through the whole function.
4635They are numbered in an arbitrary order.
4636
4637}
4638
4639@APIEntry{typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);|
4640
4641Type for debugging hook functions.
4642
4643Whenever a hook is called, its @id{ar} argument has its field
4644@id{event} set to the specific event that triggered the hook.
4645Lua identifies these events with the following constants:
4646@defid{LUA_HOOKCALL}, @defid{LUA_HOOKRET},
4647@defid{LUA_HOOKTAILCALL}, @defid{LUA_HOOKLINE},
4648and @defid{LUA_HOOKCOUNT}.
4649Moreover, for line events, the field @id{currentline} is also set.
4650To get the value of any other field in @id{ar},
4651the hook must call @Lid{lua_getinfo}.
4652
4653For call events, @id{event} can be @id{LUA_HOOKCALL},
4654the normal value, or @id{LUA_HOOKTAILCALL}, for a tail call;
4655in this case, there will be no corresponding return event.
4656
4657While Lua is running a hook, it disables other calls to hooks.
4658Therefore, if a hook calls back Lua to execute a function or a chunk,
4659this execution occurs without any calls to hooks.
4660
4661Hook functions cannot have continuations,
4662that is, they cannot call @Lid{lua_yieldk},
4663@Lid{lua_pcallk}, or @Lid{lua_callk} with a non-null @id{k}.
4664
4665Hook functions can yield under the following conditions:
4666Only count and line events can yield;
4667to yield, a hook function must finish its execution
4668calling @Lid{lua_yield} with @id{nresults} equal to zero
4669(that is, with no values).
4670
4671}
4672
4673@APIEntry{void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);|
4674@apii{0,0,-}
4675
4676Sets the debugging hook function.
4677
4678Argument @id{f} is the hook function.
4679@id{mask} specifies on which events the hook will be called:
4680it is formed by a bitwise OR of the constants
4681@defid{LUA_MASKCALL},
4682@defid{LUA_MASKRET},
4683@defid{LUA_MASKLINE},
4684and @defid{LUA_MASKCOUNT}.
4685The @id{count} argument is only meaningful when the mask
4686includes @id{LUA_MASKCOUNT}.
4687For each event, the hook is called as explained below:
4688@description{
4689
4690@item{The call hook| is called when the interpreter calls a function.
4691The hook is called just after Lua enters the new function,
4692before the function gets its arguments.
4693}
4694
4695@item{The return hook| is called when the interpreter returns from a function.
4696The hook is called just before Lua leaves the function.
4697There is no standard way to access the values
4698to be returned by the function.
4699}
4700
4701@item{The line hook| is called when the interpreter is about to
4702start the execution of a new line of code,
4703or when it jumps back in the code (even to the same line).
4704(This event only happens while Lua is executing a Lua function.)
4705}
4706
4707@item{The count hook| is called after the interpreter executes every
4708@T{count} instructions.
4709(This event only happens while Lua is executing a Lua function.)
4710}
4711
4712}
4713
4714A hook is disabled by setting @id{mask} to zero.
4715
4716}
4717
4718@APIEntry{const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);|
4719@apii{0|1,0,-}
4720
4721Sets the value of a local variable of a given activation record.
4722It assigns the value at the top of the stack
4723to the variable and returns its name.
4724It also pops the value from the stack.
4725
4726Returns @id{NULL} (and pops nothing)
4727when the index is greater than
4728the number of active local variables.
4729
4730Parameters @id{ar} and @id{n} are as in function @Lid{lua_getlocal}.
4731
4732}
4733
4734@APIEntry{const char *lua_setupvalue (lua_State *L, int funcindex, int n);|
4735@apii{0|1,0,-}
4736
4737Sets the value of a closure's upvalue.
4738It assigns the value at the top of the stack
4739to the upvalue and returns its name.
4740It also pops the value from the stack.
4741
4742Returns @id{NULL} (and pops nothing)
4743when the index @id{n} is greater than the number of upvalues.
4744
4745Parameters @id{funcindex} and @id{n} are as in function @Lid{lua_getupvalue}.
4746
4747}
4748
4749@APIEntry{void *lua_upvalueid (lua_State *L, int funcindex, int n);|
4750@apii{0,0,-}
4751
4752Returns a unique identifier for the upvalue numbered @id{n}
4753from the closure at index @id{funcindex}.
4754
4755These unique identifiers allow a program to check whether different
4756closures share upvalues.
4757Lua closures that share an upvalue
4758(that is, that access a same external local variable)
4759will return identical ids for those upvalue indices.
4760
4761Parameters @id{funcindex} and @id{n} are as in function @Lid{lua_getupvalue},
4762but @id{n} cannot be greater than the number of upvalues.
4763
4764}
4765
4766@APIEntry{
4767void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
4768 int funcindex2, int n2);|
4769@apii{0,0,-}
4770
4771Make the @id{n1}-th upvalue of the Lua closure at index @id{funcindex1}
4772refer to the @id{n2}-th upvalue of the Lua closure at index @id{funcindex2}.
4773
4774}
4775
4776}
4777
4778}
4779
4780
4781@C{-------------------------------------------------------------------------}
4782@sect1{@title{The Auxiliary Library}
4783
4784@index{lauxlib.h}
4785The @def{auxiliary library} provides several convenient functions
4786to interface C with Lua.
4787While the basic API provides the primitive functions for all
4788interactions between C and Lua,
4789the auxiliary library provides higher-level functions for some
4790common tasks.
4791
4792All functions and types from the auxiliary library
4793are defined in header file @id{lauxlib.h} and
4794have a prefix @id{luaL_}.
4795
4796All functions in the auxiliary library are built on
4797top of the basic API,
4798and so they provide nothing that cannot be done with that API.
4799Nevertheless, the use of the auxiliary library ensures
4800more consistency to your code.
4801
4802
4803Several functions in the auxiliary library use internally some
4804extra stack slots.
4805When a function in the auxiliary library uses less than five slots,
4806it does not check the stack size;
4807it simply assumes that there are enough slots.
4808
4809Several functions in the auxiliary library are used to
4810check @N{C function} arguments.
4811Because the error message is formatted for arguments
4812(e.g., @St{bad argument #1}),
4813you should not use these functions for other stack values.
4814
4815Functions called @id{luaL_check*}
4816always raise an error if the check is not satisfied.
4817
4818@sect2{@title{Functions and Types}
4819
4820Here we list all functions and types from the auxiliary library
4821in alphabetical order.
4822
4823
4824@APIEntry{void luaL_addchar (luaL_Buffer *B, char c);|
4825@apii{?,?,m}
4826
4827Adds the byte @id{c} to the buffer @id{B}
4828@seeC{luaL_Buffer}.
4829
4830}
4831
4832@APIEntry{void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);|
4833@apii{?,?,m}
4834
4835Adds the string pointed to by @id{s} with length @id{l} to
4836the buffer @id{B}
4837@seeC{luaL_Buffer}.
4838The string can contain @x{embedded zeros}.
4839
4840}
4841
4842@APIEntry{void luaL_addsize (luaL_Buffer *B, size_t n);|
4843@apii{?,?,-}
4844
4845Adds to the buffer @id{B} @seeC{luaL_Buffer}
4846a string of length @id{n} previously copied to the
4847buffer area @seeC{luaL_prepbuffer}.
4848
4849}
4850
4851@APIEntry{void luaL_addstring (luaL_Buffer *B, const char *s);|
4852@apii{?,?,m}
4853
4854Adds the zero-terminated string pointed to by @id{s}
4855to the buffer @id{B}
4856@seeC{luaL_Buffer}.
4857
4858}
4859
4860@APIEntry{void luaL_addvalue (luaL_Buffer *B);|
4861@apii{1,?,m}
4862
4863Adds the value at the top of the stack
4864to the buffer @id{B}
4865@seeC{luaL_Buffer}.
4866Pops the value.
4867
4868This is the only function on string buffers that can (and must)
4869be called with an extra element on the stack,
4870which is the value to be added to the buffer.
4871
4872}
4873
4874@APIEntry{
4875void luaL_argcheck (lua_State *L,
4876 int cond,
4877 int arg,
4878 const char *extramsg);|
4879@apii{0,0,v}
4880
4881Checks whether @id{cond} is true.
4882If it is not, raises an error with a standard message @seeF{luaL_argerror}.
4883
4884}
4885
4886@APIEntry{int luaL_argerror (lua_State *L, int arg, const char *extramsg);|
4887@apii{0,0,v}
4888
4889Raises an error reporting a problem with argument @id{arg}
4890of the @N{C function} that called it,
4891using a standard message
4892that includes @id{extramsg} as a comment:
4893@verbatim{
4894bad argument #@rep{arg} to '@rep{funcname}' (@rep{extramsg})
4895}
4896This function never returns.
4897
4898}
4899
4900@APIEntry{typedef struct luaL_Buffer luaL_Buffer;|
4901
4902Type for a @def{string buffer}.
4903
4904A string buffer allows @N{C code} to build Lua strings piecemeal.
4905Its pattern of use is as follows:
4906@itemize{
4907
4908@item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
4909
4910@item{Then initialize it with a call @T{luaL_buffinit(L, &b)}.}
4911
4912@item{
4913Then add string pieces to the buffer calling any of
4914the @id{luaL_add*} functions.
4915}
4916
4917@item{
4918Finish by calling @T{luaL_pushresult(&b)}.
4919This call leaves the final string on the top of the stack.
4920}
4921
4922}
4923
4924If you know beforehand the total size of the resulting string,
4925you can use the buffer like this:
4926@itemize{
4927
4928@item{First declare a variable @id{b} of type @Lid{luaL_Buffer}.}
4929
4930@item{Then initialize it and preallocate a space of
4931size @id{sz} with a call @T{luaL_buffinitsize(L, &b, sz)}.}
4932
4933@item{Then produce the string into that space.}
4934
4935@item{
4936Finish by calling @T{luaL_pushresultsize(&b, sz)},
4937where @id{sz} is the total size of the resulting string
4938copied into that space.
4939}
4940
4941}
4942
4943During its normal operation,
4944a string buffer uses a variable number of stack slots.
4945So, while using a buffer, you cannot assume that you know where
4946the top of the stack is.
4947You can use the stack between successive calls to buffer operations
4948as long as that use is balanced;
4949that is,
4950when you call a buffer operation,
4951the stack is at the same level
4952it was immediately after the previous buffer operation.
4953(The only exception to this rule is @Lid{luaL_addvalue}.)
4954After calling @Lid{luaL_pushresult} the stack is back to its
4955level when the buffer was initialized,
4956plus the final string on its top.
4957
4958}
4959
4960@APIEntry{void luaL_buffinit (lua_State *L, luaL_Buffer *B);|
4961@apii{0,0,-}
4962
4963Initializes a buffer @id{B}.
4964This function does not allocate any space;
4965the buffer must be declared as a variable
4966@seeC{luaL_Buffer}.
4967
4968}
4969
4970@APIEntry{char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);|
4971@apii{?,?,m}
4972
4973Equivalent to the sequence
4974@Lid{luaL_buffinit}, @Lid{luaL_prepbuffsize}.
4975
4976}
4977
4978@APIEntry{int luaL_callmeta (lua_State *L, int obj, const char *e);|
4979@apii{0,0|1,e}
4980
4981Calls a metamethod.
4982
4983If the object at index @id{obj} has a metatable and this
4984metatable has a field @id{e},
4985this function calls this field passing the object as its only argument.
4986In this case this function returns true and pushes onto the
4987stack the value returned by the call.
4988If there is no metatable or no metamethod,
4989this function returns false (without pushing any value on the stack).
4990
4991}
4992
4993@APIEntry{void luaL_checkany (lua_State *L, int arg);|
4994@apii{0,0,v}
4995
4996Checks whether the function has an argument
4997of any type (including @nil) at position @id{arg}.
4998
4999}
5000
5001@APIEntry{lua_Integer luaL_checkinteger (lua_State *L, int arg);|
5002@apii{0,0,v}
5003
5004Checks whether the function argument @id{arg} is an integer
5005(or can be converted to an integer)
5006and returns this integer cast to a @Lid{lua_Integer}.
5007
5008}
5009
5010@APIEntry{const char *luaL_checklstring (lua_State *L, int arg, size_t *l);|
5011@apii{0,0,v}
5012
5013Checks whether the function argument @id{arg} is a string
5014and returns this string;
5015if @id{l} is not @id{NULL} fills @T{*l}
5016with the string's length.
5017
5018This function uses @Lid{lua_tolstring} to get its result,
5019so all conversions and caveats of that function apply here.
5020
5021}
5022
5023@APIEntry{lua_Number luaL_checknumber (lua_State *L, int arg);|
5024@apii{0,0,v}
5025
5026Checks whether the function argument @id{arg} is a number
5027and returns this number.
5028
5029}
5030
5031@APIEntry{
5032int luaL_checkoption (lua_State *L,
5033 int arg,
5034 const char *def,
5035 const char *const lst[]);|
5036@apii{0,0,v}
5037
5038Checks whether the function argument @id{arg} is a string and
5039searches for this string in the array @id{lst}
5040(which must be NULL-terminated).
5041Returns the index in the array where the string was found.
5042Raises an error if the argument is not a string or
5043if the string cannot be found.
5044
5045If @id{def} is not @id{NULL},
5046the function uses @id{def} as a default value when
5047there is no argument @id{arg} or when this argument is @nil.
5048
5049This is a useful function for mapping strings to @N{C enums}.
5050(The usual convention in Lua libraries is
5051to use strings instead of numbers to select options.)
5052
5053}
5054
5055@APIEntry{void luaL_checkstack (lua_State *L, int sz, const char *msg);|
5056@apii{0,0,v}
5057
5058Grows the stack size to @T{top + sz} elements,
5059raising an error if the stack cannot grow to that size.
5060@id{msg} is an additional text to go into the error message
5061(or @id{NULL} for no additional text).
5062
5063}
5064
5065@APIEntry{const char *luaL_checkstring (lua_State *L, int arg);|
5066@apii{0,0,v}
5067
5068Checks whether the function argument @id{arg} is a string
5069and returns this string.
5070
5071This function uses @Lid{lua_tolstring} to get its result,
5072so all conversions and caveats of that function apply here.
5073
5074}
5075
5076@APIEntry{void luaL_checktype (lua_State *L, int arg, int t);|
5077@apii{0,0,v}
5078
5079Checks whether the function argument @id{arg} has type @id{t}.
5080See @Lid{lua_type} for the encoding of types for @id{t}.
5081
5082}
5083
5084@APIEntry{void *luaL_checkudata (lua_State *L, int arg, const char *tname);|
5085@apii{0,0,v}
5086
5087Checks whether the function argument @id{arg} is a userdata
5088of the type @id{tname} @seeC{luaL_newmetatable} and
5089returns the userdata's memory-block address @seeC{lua_touserdata}.
5090
5091}
5092
5093@APIEntry{void luaL_checkversion (lua_State *L);|
5094@apii{0,0,v}
5095
5096Checks whether the code making the call and the Lua library being called
5097are using the same version of Lua and the same numeric types.
5098
5099}
5100
5101@APIEntry{int luaL_dofile (lua_State *L, const char *filename);|
5102@apii{0,?,m}
5103
5104Loads and runs the given file.
5105It is defined as the following macro:
5106@verbatim{
5107(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
5108}
5109It returns false if there are no errors
5110or true in case of errors.
5111
5112}
5113
5114@APIEntry{int luaL_dostring (lua_State *L, const char *str);|
5115@apii{0,?,-}
5116
5117Loads and runs the given string.
5118It is defined as the following macro:
5119@verbatim{
5120(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
5121}
5122It returns false if there are no errors
5123or true in case of errors.
5124
5125}
5126
5127@APIEntry{int luaL_error (lua_State *L, const char *fmt, ...);|
5128@apii{0,0,v}
5129
5130Raises an error.
5131The error message format is given by @id{fmt}
5132plus any extra arguments,
5133following the same rules of @Lid{lua_pushfstring}.
5134It also adds at the beginning of the message the file name and
5135the line number where the error occurred,
5136if this information is available.
5137
5138This function never returns,
5139but it is an idiom to use it in @N{C functions}
5140as @T{return luaL_error(@rep{args})}.
5141
5142}
5143
5144@APIEntry{int luaL_execresult (lua_State *L, int stat);|
5145@apii{0,3,m}
5146
5147This function produces the return values for
5148process-related functions in the standard library
5149(@Lid{os.execute} and @Lid{io.close}).
5150
5151}
5152
5153@APIEntry{
5154int luaL_fileresult (lua_State *L, int stat, const char *fname);|
5155@apii{0,1|3,m}
5156
5157This function produces the return values for
5158file-related functions in the standard library
5159(@Lid{io.open}, @Lid{os.rename}, @Lid{file:seek}, etc.).
5160
5161}
5162
5163@APIEntry{int luaL_getmetafield (lua_State *L, int obj, const char *e);|
5164@apii{0,0|1,m}
5165
5166Pushes onto the stack the field @id{e} from the metatable
5167of the object at index @id{obj} and returns the type of the pushed value.
5168If the object does not have a metatable,
5169or if the metatable does not have this field,
5170pushes nothing and returns @id{LUA_TNIL}.
5171
5172}
5173
5174@APIEntry{int luaL_getmetatable (lua_State *L, const char *tname);|
5175@apii{0,1,m}
5176
5177Pushes onto the stack the metatable associated with the name @id{tname}
5178in the registry @seeC{luaL_newmetatable},
5179or @nil if there is no metatable associated with that name.
5180Returns the type of the pushed value.
5181
5182}
5183
5184@APIEntry{int luaL_getsubtable (lua_State *L, int idx, const char *fname);|
5185@apii{0,1,e}
5186
5187Ensures that the value @T{t[fname]},
5188where @id{t} is the value at index @id{idx},
5189is a table,
5190and pushes that table onto the stack.
5191Returns true if it finds a previous table there
5192and false if it creates a new table.
5193
5194}
5195
5196@APIEntry{
5197const char *luaL_gsub (lua_State *L,
5198 const char *s,
5199 const char *p,
5200 const char *r);|
5201@apii{0,1,m}
5202
5203Creates a copy of string @id{s} by replacing
5204any occurrence of the string @id{p}
5205with the string @id{r}.
5206Pushes the resulting string on the stack and returns it.
5207
5208}
5209
5210@APIEntry{lua_Integer luaL_len (lua_State *L, int index);|
5211@apii{0,0,e}
5212
5213Returns the @Q{length} of the value at the given index
5214as a number;
5215it is equivalent to the @Char{#} operator in Lua @see{len-op}.
5216Raises an error if the result of the operation is not an integer.
5217(This case only can happen through metamethods.)
5218
5219}
5220
5221@APIEntry{
5222int luaL_loadbuffer (lua_State *L,
5223 const char *buff,
5224 size_t sz,
5225 const char *name);|
5226@apii{0,1,-}
5227
5228Equivalent to @Lid{luaL_loadbufferx} with @id{mode} equal to @id{NULL}.
5229
5230}
5231
5232
5233@APIEntry{
5234int luaL_loadbufferx (lua_State *L,
5235 const char *buff,
5236 size_t sz,
5237 const char *name,
5238 const char *mode);|
5239@apii{0,1,-}
5240
5241Loads a buffer as a Lua chunk.
5242This function uses @Lid{lua_load} to load the chunk in the
5243buffer pointed to by @id{buff} with size @id{sz}.
5244
5245This function returns the same results as @Lid{lua_load}.
5246@id{name} is the chunk name,
5247used for debug information and error messages.
5248The string @id{mode} works as in function @Lid{lua_load}.
5249
5250}
5251
5252
5253@APIEntry{int luaL_loadfile (lua_State *L, const char *filename);|
5254@apii{0,1,m}
5255
5256Equivalent to @Lid{luaL_loadfilex} with @id{mode} equal to @id{NULL}.
5257
5258}
5259
5260@APIEntry{int luaL_loadfilex (lua_State *L, const char *filename,
5261 const char *mode);|
5262@apii{0,1,m}
5263
5264Loads a file as a Lua chunk.
5265This function uses @Lid{lua_load} to load the chunk in the file
5266named @id{filename}.
5267If @id{filename} is @id{NULL},
5268then it loads from the standard input.
5269The first line in the file is ignored if it starts with a @T{#}.
5270
5271The string @id{mode} works as in function @Lid{lua_load}.
5272
5273This function returns the same results as @Lid{lua_load},
5274but it has an extra error code @defid{LUA_ERRFILE}
5275for file-related errors
5276(e.g., it cannot open or read the file).
5277
5278As @Lid{lua_load}, this function only loads the chunk;
5279it does not run it.
5280
5281}
5282
5283@APIEntry{int luaL_loadstring (lua_State *L, const char *s);|
5284@apii{0,1,-}
5285
5286Loads a string as a Lua chunk.
5287This function uses @Lid{lua_load} to load the chunk in
5288the zero-terminated string @id{s}.
5289
5290This function returns the same results as @Lid{lua_load}.
5291
5292Also as @Lid{lua_load}, this function only loads the chunk;
5293it does not run it.
5294
5295}
5296
5297
5298@APIEntry{void luaL_newlib (lua_State *L, const luaL_Reg l[]);|
5299@apii{0,1,m}
5300
5301Creates a new table and registers there
5302the functions in list @id{l}.
5303
5304It is implemented as the following macro:
5305@verbatim{
5306(luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
5307}
5308The array @id{l} must be the actual array,
5309not a pointer to it.
5310
5311}
5312
5313@APIEntry{void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);|
5314@apii{0,1,m}
5315
5316Creates a new table with a size optimized
5317to store all entries in the array @id{l}
5318(but does not actually store them).
5319It is intended to be used in conjunction with @Lid{luaL_setfuncs}
5320@seeF{luaL_newlib}.
5321
5322It is implemented as a macro.
5323The array @id{l} must be the actual array,
5324not a pointer to it.
5325
5326}
5327
5328@APIEntry{int luaL_newmetatable (lua_State *L, const char *tname);|
5329@apii{0,1,m}
5330
5331If the registry already has the key @id{tname},
5332returns 0.
5333Otherwise,
5334creates a new table to be used as a metatable for userdata,
5335adds to this new table the pair @T{__name = tname},
5336adds to the registry the pair @T{[tname] = new table},
5337and returns 1.
5338(The entry @idx{__name} is used by some error-reporting functions.)
5339
5340In both cases pushes onto the stack the final value associated
5341with @id{tname} in the registry.
5342
5343}
5344
5345@APIEntry{lua_State *luaL_newstate (void);|
5346@apii{0,0,-}
5347
5348Creates a new Lua state.
5349It calls @Lid{lua_newstate} with an
5350allocator based on the @N{standard C} @id{realloc} function
5351and then sets a panic function @see{C-error} that prints
5352an error message to the standard error output in case of fatal
5353errors.
5354
5355Returns the new state,
5356or @id{NULL} if there is a @x{memory allocation error}.
5357
5358}
5359
5360@APIEntry{void luaL_openlibs (lua_State *L);|
5361@apii{0,0,e}
5362
5363Opens all standard Lua libraries into the given state.
5364
5365}
5366
5367@APIEntry{
5368T luaL_opt (L, func, arg, dflt);|
5369@apii{0,0,-}
5370
5371This macro is defined as follows:
5372@verbatim{
5373(lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
5374}
5375In words, if the argument @id{arg} is nil or absent,
5376the macro results in the default @id{dflt}.
5377Otherwise, it results in the result of calling @id{func}
5378with the state @id{L} and the argument index @id{arg} as
5379parameters.
5380Note that it evaluates the expression @id{dflt} only if needed.
5381
5382}
5383
5384@APIEntry{
5385lua_Integer luaL_optinteger (lua_State *L,
5386 int arg,
5387 lua_Integer d);|
5388@apii{0,0,v}
5389
5390If the function argument @id{arg} is an integer
5391(or convertible to an integer),
5392returns this integer.
5393If this argument is absent or is @nil,
5394returns @id{d}.
5395Otherwise, raises an error.
5396
5397}
5398
5399@APIEntry{
5400const char *luaL_optlstring (lua_State *L,
5401 int arg,
5402 const char *d,
5403 size_t *l);|
5404@apii{0,0,v}
5405
5406If the function argument @id{arg} is a string,
5407returns this string.
5408If this argument is absent or is @nil,
5409returns @id{d}.
5410Otherwise, raises an error.
5411
5412If @id{l} is not @id{NULL},
5413fills the position @T{*l} with the result's length.
5414If the result is @id{NULL}
5415(only possible when returning @id{d} and @T{d == NULL}),
5416its length is considered zero.
5417
5418This function uses @Lid{lua_tolstring} to get its result,
5419so all conversions and caveats of that function apply here.
5420
5421}
5422
5423@APIEntry{lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);|
5424@apii{0,0,v}
5425
5426If the function argument @id{arg} is a number,
5427returns this number.
5428If this argument is absent or is @nil,
5429returns @id{d}.
5430Otherwise, raises an error.
5431
5432}
5433
5434@APIEntry{
5435const char *luaL_optstring (lua_State *L,
5436 int arg,
5437 const char *d);|
5438@apii{0,0,v}
5439
5440If the function argument @id{arg} is a string,
5441returns this string.
5442If this argument is absent or is @nil,
5443returns @id{d}.
5444Otherwise, raises an error.
5445
5446}
5447
5448@APIEntry{char *luaL_prepbuffer (luaL_Buffer *B);|
5449@apii{?,?,m}
5450
5451Equivalent to @Lid{luaL_prepbuffsize}
5452with the predefined size @defid{LUAL_BUFFERSIZE}.
5453
5454}
5455
5456@APIEntry{char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);|
5457@apii{?,?,m}
5458
5459Returns an address to a space of size @id{sz}
5460where you can copy a string to be added to buffer @id{B}
5461@seeC{luaL_Buffer}.
5462After copying the string into this space you must call
5463@Lid{luaL_addsize} with the size of the string to actually add
5464it to the buffer.
5465
5466}
5467
5468@APIEntry{void luaL_pushresult (luaL_Buffer *B);|
5469@apii{?,1,m}
5470
5471Finishes the use of buffer @id{B} leaving the final string on
5472the top of the stack.
5473
5474}
5475
5476@APIEntry{void luaL_pushresultsize (luaL_Buffer *B, size_t sz);|
5477@apii{?,1,m}
5478
5479Equivalent to the sequence @Lid{luaL_addsize}, @Lid{luaL_pushresult}.
5480
5481}
5482
5483@APIEntry{int luaL_ref (lua_State *L, int t);|
5484@apii{1,0,m}
5485
5486Creates and returns a @def{reference},
5487in the table at index @id{t},
5488for the object at the top of the stack (and pops the object).
5489
5490A reference is a unique integer key.
5491As long as you do not manually add integer keys into table @id{t},
5492@Lid{luaL_ref} ensures the uniqueness of the key it returns.
5493You can retrieve an object referred by reference @id{r}
5494by calling @T{lua_rawgeti(L, t, r)}.
5495Function @Lid{luaL_unref} frees a reference and its associated object.
5496
5497If the object at the top of the stack is @nil,
5498@Lid{luaL_ref} returns the constant @defid{LUA_REFNIL}.
5499The constant @defid{LUA_NOREF} is guaranteed to be different
5500from any reference returned by @Lid{luaL_ref}.
5501
5502}
5503
5504@APIEntry{
5505typedef struct luaL_Reg {
5506 const char *name;
5507 lua_CFunction func;
5508} luaL_Reg;
5509|
5510
5511Type for arrays of functions to be registered by
5512@Lid{luaL_setfuncs}.
5513@id{name} is the function name and @id{func} is a pointer to
5514the function.
5515Any array of @Lid{luaL_Reg} must end with a sentinel entry
5516in which both @id{name} and @id{func} are @id{NULL}.
5517
5518}
5519
5520@APIEntry{
5521void luaL_requiref (lua_State *L, const char *modname,
5522 lua_CFunction openf, int glb);|
5523@apii{0,1,e}
5524
5525If @T{package.loaded[modname]} is not true,
5526calls function @id{openf} with string @id{modname} as an argument
5527and sets the call result to @T{package.loaded[modname]},
5528as if that function has been called through @Lid{require}.
5529
5530If @id{glb} is true,
5531also stores the module into global @id{modname}.
5532
5533Leaves a copy of the module on the stack.
5534
5535}
5536
5537@APIEntry{void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);|
5538@apii{nup,0,m}
5539
5540Registers all functions in the array @id{l}
5541@seeC{luaL_Reg} into the table on the top of the stack
5542(below optional upvalues, see next).
5543
5544When @id{nup} is not zero,
5545all functions are created with @id{nup} upvalues,
5546initialized with copies of the @id{nup} values
5547previously pushed on the stack
5548on top of the library table.
5549These values are popped from the stack after the registration.
5550
5551}
5552
5553@APIEntry{void luaL_setmetatable (lua_State *L, const char *tname);|
5554@apii{0,0,-}
5555
5556Sets the metatable of the object at the top of the stack
5557as the metatable associated with name @id{tname}
5558in the registry @seeC{luaL_newmetatable}.
5559
5560}
5561
5562@APIEntry{
5563typedef struct luaL_Stream {
5564 FILE *f;
5565 lua_CFunction closef;
5566} luaL_Stream;
5567|
5568
5569The standard representation for @x{file handles},
5570which is used by the standard I/O library.
5571
5572A file handle is implemented as a full userdata,
5573with a metatable called @id{LUA_FILEHANDLE}
5574(where @id{LUA_FILEHANDLE} is a macro with the actual metatable's name).
5575The metatable is created by the I/O library
5576@seeF{luaL_newmetatable}.
5577
5578This userdata must start with the structure @id{luaL_Stream};
5579it can contain other data after this initial structure.
5580Field @id{f} points to the corresponding C stream
5581(or it can be @id{NULL} to indicate an incompletely created handle).
5582Field @id{closef} points to a Lua function
5583that will be called to close the stream
5584when the handle is closed or collected;
5585this function receives the file handle as its sole argument and
5586must return either @true (in case of success)
5587or @nil plus an error message (in case of error).
5588Once Lua calls this field,
5589it changes the field value to @id{NULL}
5590to signal that the handle is closed.
5591
5592}
5593
5594@APIEntry{void *luaL_testudata (lua_State *L, int arg, const char *tname);|
5595@apii{0,0,m}
5596
5597This function works like @Lid{luaL_checkudata},
5598except that, when the test fails,
5599it returns @id{NULL} instead of raising an error.
5600
5601}
5602
5603@APIEntry{const char *luaL_tolstring (lua_State *L, int idx, size_t *len);|
5604@apii{0,1,e}
5605
5606Converts any Lua value at the given index to a @N{C string}
5607in a reasonable format.
5608The resulting string is pushed onto the stack and also
5609returned by the function.
5610If @id{len} is not @id{NULL},
5611the function also sets @T{*len} with the string length.
5612
5613If the value has a metatable with a @idx{__tostring} field,
5614then @id{luaL_tolstring} calls the corresponding metamethod
5615with the value as argument,
5616and uses the result of the call as its result.
5617
5618}
5619
5620@APIEntry{
5621void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
5622 int level);|
5623@apii{0,1,m}
5624
5625Creates and pushes a traceback of the stack @id{L1}.
5626If @id{msg} is not @id{NULL} it is appended
5627at the beginning of the traceback.
5628The @id{level} parameter tells at which level
5629to start the traceback.
5630
5631}
5632
5633@APIEntry{const char *luaL_typename (lua_State *L, int index);|
5634@apii{0,0,-}
5635
5636Returns the name of the type of the value at the given index.
5637
5638}
5639
5640@APIEntry{void luaL_unref (lua_State *L, int t, int ref);|
5641@apii{0,0,-}
5642
5643Releases reference @id{ref} from the table at index @id{t}
5644@seeC{luaL_ref}.
5645The entry is removed from the table,
5646so that the referred object can be collected.
5647The reference @id{ref} is also freed to be used again.
5648
5649If @id{ref} is @Lid{LUA_NOREF} or @Lid{LUA_REFNIL},
5650@Lid{luaL_unref} does nothing.
5651
5652}
5653
5654@APIEntry{void luaL_where (lua_State *L, int lvl);|
5655@apii{0,1,m}
5656
5657Pushes onto the stack a string identifying the current position
5658of the control at level @id{lvl} in the call stack.
5659Typically this string has the following format:
5660@verbatim{
5661@rep{chunkname}:@rep{currentline}:
5662}
5663@N{Level 0} is the running function,
5664@N{level 1} is the function that called the running function,
5665etc.
5666
5667This function is used to build a prefix for error messages.
5668
5669}
5670
5671}
5672
5673}
5674
5675
5676@C{-------------------------------------------------------------------------}
5677@sect1{libraries| @title{Standard Libraries}
5678
5679The standard Lua libraries provide useful functions
5680that are implemented directly through the @N{C API}.
5681Some of these functions provide essential services to the language
5682(e.g., @Lid{type} and @Lid{getmetatable});
5683others provide access to @Q{outside} services (e.g., I/O);
5684and others could be implemented in Lua itself,
5685but are quite useful or have critical performance requirements that
5686deserve an implementation in C (e.g., @Lid{table.sort}).
5687
5688All libraries are implemented through the official @N{C API}
5689and are provided as separate @N{C modules}.
5690Unless otherwise noted,
5691these library functions do not adjust its number of arguments
5692to its expected parameters.
5693For instance, a function documented as @T{foo(arg)}
5694should not be called without an argument.
5695
5696Currently, Lua has the following standard libraries:
5697@itemize{
5698
5699@item{@link{predefined|basic library};}
5700
5701@item{@link{corolib|coroutine library};}
5702
5703@item{@link{packlib|package library};}
5704
5705@item{@link{strlib|string manipulation};}
5706
5707@item{@link{utf8|basic UTF-8 support};}
5708
5709@item{@link{tablib|table manipulation};}
5710
5711@item{@link{mathlib|mathematical functions} (sin, log, etc.);}
5712
5713@item{@link{iolib|input and output};}
5714
5715@item{@link{oslib|operating system facilities};}
5716
5717@item{@link{debuglib|debug facilities}.}
5718
5719}
5720Except for the basic and the package libraries,
5721each library provides all its functions as fields of a global table
5722or as methods of its objects.
5723
5724To have access to these libraries,
5725the @N{C host} program should call the @Lid{luaL_openlibs} function,
5726which opens all standard libraries.
5727Alternatively,
5728the host program can open them individually by using
5729@Lid{luaL_requiref} to call
5730@defid{luaopen_base} (for the basic library),
5731@defid{luaopen_package} (for the package library),
5732@defid{luaopen_coroutine} (for the coroutine library),
5733@defid{luaopen_string} (for the string library),
5734@defid{luaopen_utf8} (for the UTF8 library),
5735@defid{luaopen_table} (for the table library),
5736@defid{luaopen_math} (for the mathematical library),
5737@defid{luaopen_io} (for the I/O library),
5738@defid{luaopen_os} (for the operating system library),
5739and @defid{luaopen_debug} (for the debug library).
5740These functions are declared in @defid{lualib.h}.
5741
5742@sect2{predefined| @title{Basic Functions}
5743
5744The basic library provides core functions to Lua.
5745If you do not include this library in your application,
5746you should check carefully whether you need to provide
5747implementations for some of its facilities.
5748
5749
5750@LibEntry{assert (v [, message])|
5751
5752Calls @Lid{error} if
5753the value of its argument @id{v} is false (i.e., @nil or @false);
5754otherwise, returns all its arguments.
5755In case of error,
5756@id{message} is the error object;
5757when absent, it defaults to @St{assertion failed!}
5758
5759}
5760
5761@LibEntry{collectgarbage ([opt [, arg]])|
5762
5763This function is a generic interface to the garbage collector.
5764It performs different functions according to its first argument, @id{opt}:
5765@description{
5766
5767@item{@St{collect}|
5768performs a full garbage-collection cycle.
5769This is the default option.
5770}
5771
5772@item{@St{stop}|
5773stops automatic execution of the garbage collector.
5774The collector will run only when explicitly invoked,
5775until a call to restart it.
5776}
5777
5778@item{@St{restart}|
5779restarts automatic execution of the garbage collector.
5780}
5781
5782@item{@St{count}|
5783returns the total memory in use by Lua in Kbytes.
5784The value has a fractional part,
5785so that it multiplied by 1024
5786gives the exact number of bytes in use by Lua
5787(except for overflows).
5788}
5789
5790@item{@St{step}|
5791performs a garbage-collection step.
5792The step @Q{size} is controlled by @id{arg}.
5793With a zero value,
5794the collector will perform one basic (indivisible) step.
5795For non-zero values,
5796the collector will perform as if that amount of memory
5797(in KBytes) had been allocated by Lua.
5798Returns @true if the step finished a collection cycle.
5799}
5800
5801@item{@St{setpause}|
5802sets @id{arg} as the new value for the @emph{pause} of
5803the collector @see{GC}.
5804Returns the previous value for @emph{pause}.
5805}
5806
5807@item{@St{incremental}|
5808Change the collector mode to incremental.
5809This option can be followed by three numbers:
5810the garbage-collector pause,
5811the step multiplier,
5812and the step size.
5813}
5814
5815@item{@St{generational}|
5816Change the collector mode to generational.
5817This option can be followed by two numbers:
5818the garbage-collector minor multiplier
5819and the major multiplier.
5820}
5821
5822@item{@St{isrunning}|
5823returns a boolean that tells whether the collector is running
5824(i.e., not stopped).
5825}
5826
5827}
5828
5829}
5830
5831@LibEntry{dofile ([filename])|
5832Opens the named file and executes its contents as a Lua chunk.
5833When called without arguments,
5834@id{dofile} executes the contents of the standard input (@id{stdin}).
5835Returns all values returned by the chunk.
5836In case of errors, @id{dofile} propagates the error
5837to its caller (that is, @id{dofile} does not run in protected mode).
5838
5839}
5840
5841@LibEntry{error (message [, level])|
5842Terminates the last protected function called
5843and returns @id{message} as the error object.
5844Function @id{error} never returns.
5845
5846Usually, @id{error} adds some information about the error position
5847at the beginning of the message, if the message is a string.
5848The @id{level} argument specifies how to get the error position.
5849With @N{level 1} (the default), the error position is where the
5850@id{error} function was called.
5851@N{Level 2} points the error to where the function
5852that called @id{error} was called; and so on.
5853Passing a @N{level 0} avoids the addition of error position information
5854to the message.
5855
5856}
5857
5858@LibEntry{_G|
5859A global variable (not a function) that
5860holds the @x{global environment} @see{globalenv}.
5861Lua itself does not use this variable;
5862changing its value does not affect any environment,
5863nor vice versa.
5864
5865}
5866
5867@LibEntry{getmetatable (object)|
5868
5869If @id{object} does not have a metatable, returns @nil.
5870Otherwise,
5871if the object's metatable has a @idx{__metatable} field,
5872returns the associated value.
5873Otherwise, returns the metatable of the given object.
5874
5875}
5876
5877@LibEntry{ipairs (t)|
5878
5879Returns three values (an iterator function, the table @id{t}, and 0)
5880so that the construction
5881@verbatim{
5882for i,v in ipairs(t) do @rep{body} end
5883}
5884will iterate over the key@En{}value pairs
5885(@T{1,t[1]}), (@T{2,t[2]}), @ldots,
5886up to the first absent index.
5887
5888}
5889
5890@LibEntry{load (chunk [, chunkname [, mode [, env]]])|
5891
5892Loads a chunk.
5893
5894If @id{chunk} is a string, the chunk is this string.
5895If @id{chunk} is a function,
5896@id{load} calls it repeatedly to get the chunk pieces.
5897Each call to @id{chunk} must return a string that concatenates
5898with previous results.
5899A return of an empty string, @nil, or no value signals the end of the chunk.
5900
5901If there are no syntactic errors,
5902returns the compiled chunk as a function;
5903otherwise, returns @nil plus the error message.
5904
5905If the resulting function has upvalues,
5906the first upvalue is set to the value of @id{env},
5907if that parameter is given,
5908or to the value of the @x{global environment}.
5909Other upvalues are initialized with @nil.
5910(When you load a main chunk,
5911the resulting function will always have exactly one upvalue,
5912the @id{_ENV} variable @see{globalenv}.
5913However,
5914when you load a binary chunk created from a function @seeF{string.dump},
5915the resulting function can have an arbitrary number of upvalues.)
5916All upvalues are fresh, that is,
5917they are not shared with any other function.
5918
5919@id{chunkname} is used as the name of the chunk for error messages
5920and debug information @see{debugI}.
5921When absent,
5922it defaults to @id{chunk}, if @id{chunk} is a string,
5923or to @St{=(load)} otherwise.
5924
5925The string @id{mode} controls whether the chunk can be text or binary
5926(that is, a precompiled chunk).
5927It may be the string @St{b} (only @x{binary chunk}s),
5928@St{t} (only text chunks),
5929or @St{bt} (both binary and text).
5930The default is @St{bt}.
5931
5932Lua does not check the consistency of binary chunks.
5933Maliciously crafted binary chunks can crash
5934the interpreter.
5935
5936}
5937
5938@LibEntry{loadfile ([filename [, mode [, env]]])|
5939
5940Similar to @Lid{load},
5941but gets the chunk from file @id{filename}
5942or from the standard input,
5943if no file name is given.
5944
5945}
5946
5947@LibEntry{next (table [, index])|
5948
5949Allows a program to traverse all fields of a table.
5950Its first argument is a table and its second argument
5951is an index in this table.
5952@id{next} returns the next index of the table
5953and its associated value.
5954When called with @nil as its second argument,
5955@id{next} returns an initial index
5956and its associated value.
5957When called with the last index,
5958or with @nil in an empty table,
5959@id{next} returns @nil.
5960If the second argument is absent, then it is interpreted as @nil.
5961In particular,
5962you can use @T{next(t)} to check whether a table is empty.
5963
5964The order in which the indices are enumerated is not specified,
5965@emph{even for numeric indices}.
5966(To traverse a table in numerical order,
5967use a numerical @Rw{for}.)
5968
5969The behavior of @id{next} is undefined if,
5970during the traversal,
5971you assign any value to a non-existent field in the table.
5972You may however modify existing fields.
5973In particular, you may set existing fields to nil.
5974
5975}
5976
5977@LibEntry{pairs (t)|
5978
5979If @id{t} has a metamethod @idx{__pairs},
5980calls it with @id{t} as argument and returns the first three
5981results from the call.
5982
5983Otherwise,
5984returns three values: the @Lid{next} function, the table @id{t}, and @nil,
5985so that the construction
5986@verbatim{
5987for k,v in pairs(t) do @rep{body} end
5988}
5989will iterate over all key@En{}value pairs of table @id{t}.
5990
5991See function @Lid{next} for the caveats of modifying
5992the table during its traversal.
5993
5994}
5995
5996@LibEntry{pcall (f [, arg1, @Cdots])|
5997
5998Calls function @id{f} with
5999the given arguments in @def{protected mode}.
6000This means that any error @N{inside @T{f}} is not propagated;
6001instead, @id{pcall} catches the error
6002and returns a status code.
6003Its first result is the status code (a boolean),
6004which is true if the call succeeds without errors.
6005In such case, @id{pcall} also returns all results from the call,
6006after this first result.
6007In case of any error, @id{pcall} returns @false plus the error message.
6008
6009}
6010
6011@LibEntry{print (@Cdots)|
6012Receives any number of arguments
6013and prints their values to @id{stdout},
6014using the @Lid{tostring} function to convert each argument to a string.
6015@id{print} is not intended for formatted output,
6016but only as a quick way to show a value,
6017for instance for debugging.
6018For complete control over the output,
6019use @Lid{string.format} and @Lid{io.write}.
6020
6021}
6022
6023@LibEntry{rawequal (v1, v2)|
6024Checks whether @id{v1} is equal to @id{v2},
6025without invoking the @idx{__eq} metamethod.
6026Returns a boolean.
6027
6028}
6029
6030@LibEntry{rawget (table, index)|
6031Gets the real value of @T{table[index]},
6032without invoking the @idx{__index} metamethod.
6033@id{table} must be a table;
6034@id{index} may be any value.
6035
6036}
6037
6038@LibEntry{rawlen (v)|
6039Returns the length of the object @id{v},
6040which must be a table or a string,
6041without invoking the @idx{__len} metamethod.
6042Returns an integer.
6043
6044}
6045
6046@LibEntry{rawset (table, index, value)|
6047Sets the real value of @T{table[index]} to @id{value},
6048without invoking the @idx{__newindex} metamethod.
6049@id{table} must be a table,
6050@id{index} any value different from @nil and @x{NaN},
6051and @id{value} any Lua value.
6052
6053This function returns @id{table}.
6054
6055}
6056
6057@LibEntry{select (index, @Cdots)|
6058
6059If @id{index} is a number,
6060returns all arguments after argument number @id{index};
6061a negative number indexes from the end (@num{-1} is the last argument).
6062Otherwise, @id{index} must be the string @T{"#"},
6063and @id{select} returns the total number of extra arguments it received.
6064
6065}
6066
6067@LibEntry{setmetatable (table, metatable)|
6068
6069Sets the metatable for the given table.
6070(To change the metatable of other types from Lua code,
6071you must use the @link{debuglib|debug library}.)
6072If @id{metatable} is @nil,
6073removes the metatable of the given table.
6074If the original metatable has a @idx{__metatable} field,
6075raises an error.
6076
6077This function returns @id{table}.
6078
6079}
6080
6081@LibEntry{tonumber (e [, base])|
6082
6083When called with no @id{base},
6084@id{tonumber} tries to convert its argument to a number.
6085If the argument is already a number or
6086a string convertible to a number,
6087then @id{tonumber} returns this number;
6088otherwise, it returns @nil.
6089
6090The conversion of strings can result in integers or floats,
6091according to the lexical conventions of Lua @see{lexical}.
6092(The string may have leading and trailing spaces and a sign.)
6093
6094When called with @id{base},
6095then @id{e} must be a string to be interpreted as
6096an integer numeral in that base.
6097The base may be any integer between 2 and 36, inclusive.
6098In bases @N{above 10}, the letter @Char{A} (in either upper or lower case)
6099@N{represents 10}, @Char{B} @N{represents 11}, and so forth,
6100with @Char{Z} representing 35.
6101If the string @id{e} is not a valid numeral in the given base,
6102the function returns @nil.
6103
6104}
6105
6106@LibEntry{tostring (v)|
6107Receives a value of any type and
6108converts it to a string in a human-readable format.
6109(For complete control of how numbers are converted,
6110use @Lid{string.format}.)
6111
6112If the metatable of @id{v} has a @idx{__tostring} field,
6113then @id{tostring} calls the corresponding value
6114with @id{v} as argument,
6115and uses the result of the call as its result.
6116
6117}
6118
6119@LibEntry{type (v)|
6120Returns the type of its only argument, coded as a string.
6121The possible results of this function are
6122@St{nil} (a string, not the value @nil),
6123@St{number},
6124@St{string},
6125@St{boolean},
6126@St{table},
6127@St{function},
6128@St{thread},
6129and @St{userdata}.
6130
6131}
6132
6133@LibEntry{_VERSION|
6134
6135A global variable (not a function) that
6136holds a string containing the running Lua version.
6137The current value of this variable is @St{Lua 5.4}.
6138
6139}
6140
6141@LibEntry{xpcall (f, msgh [, arg1, @Cdots])|
6142
6143This function is similar to @Lid{pcall},
6144except that it sets a new @x{message handler} @id{msgh}.
6145
6146}
6147
6148}
6149
6150@sect2{corolib| @title{Coroutine Manipulation}
6151
6152This library comprises the operations to manipulate coroutines,
6153which come inside the table @defid{coroutine}.
6154See @See{coroutine} for a general description of coroutines.
6155
6156
6157@LibEntry{coroutine.create (f)|
6158
6159Creates a new coroutine, with body @id{f}.
6160@id{f} must be a function.
6161Returns this new coroutine,
6162an object with type @T{"thread"}.
6163
6164}
6165
6166@LibEntry{coroutine.isyieldable ()|
6167
6168Returns true when the running coroutine can yield.
6169
6170A running coroutine is yieldable if it is not the main thread and
6171it is not inside a non-yieldable @N{C function}.
6172
6173}
6174
6175@LibEntry{coroutine.resume (co [, val1, @Cdots])|
6176
6177Starts or continues the execution of coroutine @id{co}.
6178The first time you resume a coroutine,
6179it starts running its body.
6180The values @id{val1}, @ldots are passed
6181as the arguments to the body function.
6182If the coroutine has yielded,
6183@id{resume} restarts it;
6184the values @id{val1}, @ldots are passed
6185as the results from the yield.
6186
6187If the coroutine runs without any errors,
6188@id{resume} returns @true plus any values passed to @id{yield}
6189(when the coroutine yields) or any values returned by the body function
6190(when the coroutine terminates).
6191If there is any error,
6192@id{resume} returns @false plus the error message.
6193
6194}
6195
6196@LibEntry{coroutine.running ()|
6197
6198Returns the running coroutine plus a boolean,
6199true when the running coroutine is the main one.
6200
6201}
6202
6203@LibEntry{coroutine.status (co)|
6204
6205Returns the status of coroutine @id{co}, as a string:
6206@T{"running"},
6207if the coroutine is running (that is, it called @id{status});
6208@T{"suspended"}, if the coroutine is suspended in a call to @id{yield},
6209or if it has not started running yet;
6210@T{"normal"} if the coroutine is active but not running
6211(that is, it has resumed another coroutine);
6212and @T{"dead"} if the coroutine has finished its body function,
6213or if it has stopped with an error.
6214
6215}
6216
6217@LibEntry{coroutine.wrap (f)|
6218
6219Creates a new coroutine, with body @id{f}.
6220@id{f} must be a function.
6221Returns a function that resumes the coroutine each time it is called.
6222Any arguments passed to the function behave as the
6223extra arguments to @id{resume}.
6224Returns the same values returned by @id{resume},
6225except the first boolean.
6226In case of error, propagates the error.
6227
6228}
6229
6230@LibEntry{coroutine.yield (@Cdots)|
6231
6232Suspends the execution of the calling coroutine.
6233Any arguments to @id{yield} are passed as extra results to @id{resume}.
6234
6235}
6236
6237}
6238
6239@sect2{packlib| @title{Modules}
6240
6241The package library provides basic
6242facilities for loading modules in Lua.
6243It exports one function directly in the global environment:
6244@Lid{require}.
6245Everything else is exported in a table @defid{package}.
6246
6247
6248@LibEntry{require (modname)|
6249
6250Loads the given module.
6251The function starts by looking into the @Lid{package.loaded} table
6252to determine whether @id{modname} is already loaded.
6253If it is, then @id{require} returns the value stored
6254at @T{package.loaded[modname]}.
6255Otherwise, it tries to find a @emph{loader} for the module.
6256
6257To find a loader,
6258@id{require} is guided by the @Lid{package.searchers} sequence.
6259By changing this sequence,
6260we can change how @id{require} looks for a module.
6261The following explanation is based on the default configuration
6262for @Lid{package.searchers}.
6263
6264First @id{require} queries @T{package.preload[modname]}.
6265If it has a value,
6266this value (which must be a function) is the loader.
6267Otherwise @id{require} searches for a Lua loader using the
6268path stored in @Lid{package.path}.
6269If that also fails, it searches for a @N{C loader} using the
6270path stored in @Lid{package.cpath}.
6271If that also fails,
6272it tries an @emph{all-in-one} loader @seeF{package.searchers}.
6273
6274Once a loader is found,
6275@id{require} calls the loader with two arguments:
6276@id{modname} and an extra value dependent on how it got the loader.
6277(If the loader came from a file,
6278this extra value is the file name.)
6279If the loader returns any non-nil value,
6280@id{require} assigns the returned value to @T{package.loaded[modname]}.
6281If the loader does not return a non-nil value and
6282has not assigned any value to @T{package.loaded[modname]},
6283then @id{require} assigns @Rw{true} to this entry.
6284In any case, @id{require} returns the
6285final value of @T{package.loaded[modname]}.
6286
6287If there is any error loading or running the module,
6288or if it cannot find any loader for the module,
6289then @id{require} raises an error.
6290
6291}
6292
6293@LibEntry{package.config|
6294
6295A string describing some compile-time configurations for packages.
6296This string is a sequence of lines:
6297@itemize{
6298
6299@item{The first line is the @x{directory separator} string.
6300Default is @Char{\} for @x{Windows} and @Char{/} for all other systems.}
6301
6302@item{The second line is the character that separates templates in a path.
6303Default is @Char{;}.}
6304
6305@item{The third line is the string that marks the
6306substitution points in a template.
6307Default is @Char{?}.}
6308
6309@item{The fourth line is a string that, in a path in @x{Windows},
6310is replaced by the executable's directory.
6311Default is @Char{!}.}
6312
6313@item{The fifth line is a mark to ignore all text after it
6314when building the @id{luaopen_} function name.
6315Default is @Char{-}.}
6316
6317}
6318
6319}
6320
6321@LibEntry{package.cpath|
6322
6323The path used by @Lid{require} to search for a @N{C loader}.
6324
6325Lua initializes the @N{C path} @Lid{package.cpath} in the same way
6326it initializes the Lua path @Lid{package.path},
6327using the environment variable @defid{LUA_CPATH_5_4},
6328or the environment variable @defid{LUA_CPATH},
6329or a default path defined in @id{luaconf.h}.
6330
6331}
6332
6333@LibEntry{package.loaded|
6334
6335A table used by @Lid{require} to control which
6336modules are already loaded.
6337When you require a module @id{modname} and
6338@T{package.loaded[modname]} is not false,
6339@Lid{require} simply returns the value stored there.
6340
6341This variable is only a reference to the real table;
6342assignments to this variable do not change the
6343table used by @Lid{require}.
6344
6345}
6346
6347@LibEntry{package.loadlib (libname, funcname)|
6348
6349Dynamically links the host program with the @N{C library} @id{libname}.
6350
6351If @id{funcname} is @St{*},
6352then it only links with the library,
6353making the symbols exported by the library
6354available to other dynamically linked libraries.
6355Otherwise,
6356it looks for a function @id{funcname} inside the library
6357and returns this function as a @N{C function}.
6358So, @id{funcname} must follow the @Lid{lua_CFunction} prototype
6359@seeC{lua_CFunction}.
6360
6361This is a low-level function.
6362It completely bypasses the package and module system.
6363Unlike @Lid{require},
6364it does not perform any path searching and
6365does not automatically adds extensions.
6366@id{libname} must be the complete file name of the @N{C library},
6367including if necessary a path and an extension.
6368@id{funcname} must be the exact name exported by the @N{C library}
6369(which may depend on the @N{C compiler} and linker used).
6370
6371This function is not supported by @N{Standard C}.
6372As such, it is only available on some platforms
6373(Windows, Linux, Mac OS X, Solaris, BSD,
6374plus other Unix systems that support the @id{dlfcn} standard).
6375
6376}
6377
6378@LibEntry{package.path|
6379
6380The path used by @Lid{require} to search for a Lua loader.
6381
6382At start-up, Lua initializes this variable with
6383the value of the environment variable @defid{LUA_PATH_5_4} or
6384the environment variable @defid{LUA_PATH} or
6385with a default path defined in @id{luaconf.h},
6386if those environment variables are not defined.
6387Any @St{;;} in the value of the environment variable
6388is replaced by the default path.
6389
6390}
6391
6392@LibEntry{package.preload|
6393
6394A table to store loaders for specific modules
6395@seeF{require}.
6396
6397This variable is only a reference to the real table;
6398assignments to this variable do not change the
6399table used by @Lid{require}.
6400
6401}
6402
6403@LibEntry{package.searchers|
6404
6405A table used by @Lid{require} to control how to load modules.
6406
6407Each entry in this table is a @def{searcher function}.
6408When looking for a module,
6409@Lid{require} calls each of these searchers in ascending order,
6410with the module name (the argument given to @Lid{require}) as its
6411sole parameter.
6412The function can return another function (the module @def{loader})
6413plus an extra value that will be passed to that loader,
6414or a string explaining why it did not find that module
6415(or @nil if it has nothing to say).
6416
6417Lua initializes this table with four searcher functions.
6418
6419The first searcher simply looks for a loader in the
6420@Lid{package.preload} table.
6421
6422The second searcher looks for a loader as a Lua library,
6423using the path stored at @Lid{package.path}.
6424The search is done as described in function @Lid{package.searchpath}.
6425
6426The third searcher looks for a loader as a @N{C library},
6427using the path given by the variable @Lid{package.cpath}.
6428Again,
6429the search is done as described in function @Lid{package.searchpath}.
6430For instance,
6431if the @N{C path} is the string
6432@verbatim{
6433"./?.so;./?.dll;/usr/local/?/init.so"
6434}
6435the searcher for module @id{foo}
6436will try to open the files @T{./foo.so}, @T{./foo.dll},
6437and @T{/usr/local/foo/init.so}, in that order.
6438Once it finds a @N{C library},
6439this searcher first uses a dynamic link facility to link the
6440application with the library.
6441Then it tries to find a @N{C function} inside the library to
6442be used as the loader.
6443The name of this @N{C function} is the string @St{luaopen_}
6444concatenated with a copy of the module name where each dot
6445is replaced by an underscore.
6446Moreover, if the module name has a hyphen,
6447its suffix after (and including) the first hyphen is removed.
6448For instance, if the module name is @id{a.b.c-v2.1},
6449the function name will be @id{luaopen_a_b_c}.
6450
6451The fourth searcher tries an @def{all-in-one loader}.
6452It searches the @N{C path} for a library for
6453the root name of the given module.
6454For instance, when requiring @id{a.b.c},
6455it will search for a @N{C library} for @id{a}.
6456If found, it looks into it for an open function for
6457the submodule;
6458in our example, that would be @id{luaopen_a_b_c}.
6459With this facility, a package can pack several @N{C submodules}
6460into one single library,
6461with each submodule keeping its original open function.
6462
6463All searchers except the first one (preload) return as the extra value
6464the file name where the module was found,
6465as returned by @Lid{package.searchpath}.
6466The first searcher returns no extra value.
6467
6468}
6469
6470@LibEntry{package.searchpath (name, path [, sep [, rep]])|
6471
6472Searches for the given @id{name} in the given @id{path}.
6473
6474A path is a string containing a sequence of
6475@emph{templates} separated by semicolons.
6476For each template,
6477the function replaces each interrogation mark (if any)
6478in the template with a copy of @id{name}
6479wherein all occurrences of @id{sep}
6480(a dot, by default)
6481were replaced by @id{rep}
6482(the system's directory separator, by default),
6483and then tries to open the resulting file name.
6484
6485For instance, if the path is the string
6486@verbatim{
6487"./?.lua;./?.lc;/usr/local/?/init.lua"
6488}
6489the search for the name @id{foo.a}
6490will try to open the files
6491@T{./foo/a.lua}, @T{./foo/a.lc}, and
6492@T{/usr/local/foo/a/init.lua}, in that order.
6493
6494Returns the resulting name of the first file that it can
6495open in read mode (after closing the file),
6496or @nil plus an error message if none succeeds.
6497(This error message lists all file names it tried to open.)
6498
6499}
6500
6501}
6502
6503@sect2{strlib| @title{String Manipulation}
6504
6505This library provides generic functions for string manipulation,
6506such as finding and extracting substrings, and pattern matching.
6507When indexing a string in Lua, the first character is at @N{position 1}
6508(not @N{at 0}, as in C).
6509Indices are allowed to be negative and are interpreted as indexing backwards,
6510from the end of the string.
6511Thus, the last character is at position @num{-1}, and so on.
6512
6513The string library provides all its functions inside the table
6514@defid{string}.
6515It also sets a @x{metatable for strings}
6516where the @idx{__index} field points to the @id{string} table.
6517Therefore, you can use the string functions in object-oriented style.
6518For instance, @T{string.byte(s,i)}
6519can be written as @T{s:byte(i)}.
6520
6521The string library assumes one-byte character encodings.
6522
6523
6524@LibEntry{string.byte (s [, i [, j]])|
6525Returns the internal numeric codes of the characters @T{s[i]},
6526@T{s[i+1]}, @ldots, @T{s[j]}.
6527The default value for @id{i} @N{is 1};
6528the default value for @id{j} @N{is @id{i}}.
6529These indices are corrected
6530following the same rules of function @Lid{string.sub}.
6531
6532Numeric codes are not necessarily portable across platforms.
6533
6534}
6535
6536@LibEntry{string.char (@Cdots)|
6537Receives zero or more integers.
6538Returns a string with length equal to the number of arguments,
6539in which each character has the internal numeric code equal
6540to its corresponding argument.
6541
6542Numeric codes are not necessarily portable across platforms.
6543
6544}
6545
6546@LibEntry{string.dump (function [, strip])|
6547
6548Returns a string containing a binary representation
6549(a @emph{binary chunk})
6550of the given function,
6551so that a later @Lid{load} on this string returns
6552a copy of the function (but with new upvalues).
6553If @id{strip} is a true value,
6554the binary representation may not include all debug information
6555about the function,
6556to save space.
6557
6558Functions with upvalues have only their number of upvalues saved.
6559When (re)loaded,
6560those upvalues receive fresh instances containing @nil.
6561(You can use the debug library to serialize
6562and reload the upvalues of a function
6563in a way adequate to your needs.)
6564
6565}
6566
6567@LibEntry{string.find (s, pattern [, init [, plain]])|
6568
6569Looks for the first match of
6570@id{pattern} @see{pm} in the string @id{s}.
6571If it finds a match, then @id{find} returns the indices @N{of @T{s}}
6572where this occurrence starts and ends;
6573otherwise, it returns @nil.
6574A third, optional numeric argument @id{init} specifies
6575where to start the search;
6576its default value @N{is 1} and can be negative.
6577A value of @true as a fourth, optional argument @id{plain}
6578turns off the pattern matching facilities,
6579so the function does a plain @Q{find substring} operation,
6580with no characters in @id{pattern} being considered magic.
6581Note that if @id{plain} is given, then @id{init} must be given as well.
6582
6583If the pattern has captures,
6584then in a successful match
6585the captured values are also returned,
6586after the two indices.
6587
6588}
6589
6590@LibEntry{string.format (formatstring, @Cdots)|
6591
6592Returns a formatted version of its variable number of arguments
6593following the description given in its first argument (which must be a string).
6594The format string follows the same rules as the @ANSI{sprintf}.
6595The only differences are that the options/modifiers
6596@T{*}, @id{h}, @id{L}, @id{l}, @id{n},
6597and @id{p} are not supported
6598and that there is an extra option, @id{q}.
6599
6600The @id{q} option formats booleans, nil, numbers, and strings
6601in a way that the result is a valid constant in Lua source code.
6602Booleans and nil are written in the obvious way
6603(@id{true}, @id{false}, @id{nil}).
6604Floats are written in hexadecimal,
6605to preserve full precision.
6606A string is written between double quotes,
6607using escape sequences when necessary to ensure that
6608it can safely be read back by the Lua interpreter.
6609For instance, the call
6610@verbatim{
6611string.format('%q', 'a string with "quotes" and \n new line')
6612}
6613may produce the string:
6614@verbatim{
6615"a string with \"quotes\" and \
6616 new line"
6617}
6618
6619Options
6620@id{A}, @id{a}, @id{E}, @id{e}, @id{f},
6621@id{G}, and @id{g} all expect a number as argument.
6622Options @id{c}, @id{d},
6623@id{i}, @id{o}, @id{u}, @id{X}, and @id{x}
6624expect an integer.
6625When Lua is compiled with a C89 compiler,
6626options @id{A} and @id{a} (hexadecimal floats)
6627do not support any modifier (flags, width, length).
6628
6629Option @id{s} expects a string;
6630if its argument is not a string,
6631it is converted to one following the same rules of @Lid{tostring}.
6632If the option has any modifier (flags, width, length),
6633the string argument should not contain @x{embedded zeros}.
6634
6635}
6636
6637@LibEntry{string.gmatch (s, pattern)|
6638Returns an iterator function that,
6639each time it is called,
6640returns the next captures from @id{pattern} @see{pm}
6641over the string @id{s}.
6642If @id{pattern} specifies no captures,
6643then the whole match is produced in each call.
6644
6645As an example, the following loop
6646will iterate over all the words from string @id{s},
6647printing one per line:
6648@verbatim{
6649s = "hello world from Lua"
6650for w in string.gmatch(s, "%a+") do
6651 print(w)
6652end
6653}
6654The next example collects all pairs @T{key=value} from the
6655given string into a table:
6656@verbatim{
6657t = {}
6658s = "from=world, to=Lua"
6659for k, v in string.gmatch(s, "(%w+)=(%w+)") do
6660 t[k] = v
6661end
6662}
6663
6664For this function, a caret @Char{^} at the start of a pattern does not
6665work as an anchor, as this would prevent the iteration.
6666
6667}
6668
6669@LibEntry{string.gsub (s, pattern, repl [, n])|
6670Returns a copy of @id{s}
6671in which all (or the first @id{n}, if given)
6672occurrences of the @id{pattern} @see{pm} have been
6673replaced by a replacement string specified by @id{repl},
6674which can be a string, a table, or a function.
6675@id{gsub} also returns, as its second value,
6676the total number of matches that occurred.
6677The name @id{gsub} comes from @emph{Global SUBstitution}.
6678
6679If @id{repl} is a string, then its value is used for replacement.
6680The @N{character @T{%}} works as an escape character:
6681any sequence in @id{repl} of the form @T{%@rep{d}},
6682with @rep{d} between 1 and 9,
6683stands for the value of the @rep{d}-th captured substring.
6684The sequence @T{%0} stands for the whole match.
6685The sequence @T{%%} stands for a @N{single @T{%}}.
6686
6687If @id{repl} is a table, then the table is queried for every match,
6688using the first capture as the key.
6689
6690If @id{repl} is a function, then this function is called every time a
6691match occurs, with all captured substrings passed as arguments,
6692in order.
6693
6694In any case,
6695if the pattern specifies no captures,
6696then it behaves as if the whole pattern was inside a capture.
6697
6698If the value returned by the table query or by the function call
6699is a string or a number,
6700then it is used as the replacement string;
6701otherwise, if it is @Rw{false} or @nil,
6702then there is no replacement
6703(that is, the original match is kept in the string).
6704
6705Here are some examples:
6706@verbatim{
6707x = string.gsub("hello world", "(%w+)", "%1 %1")
6708--> x="hello hello world world"
6709
6710x = string.gsub("hello world", "%w+", "%0 %0", 1)
6711--> x="hello hello world"
6712
6713x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
6714--> x="world hello Lua from"
6715
6716x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
6717--> x="home = /home/roberto, user = roberto"
6718
6719x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
6720 return load(s)()
6721 end)
6722--> x="4+5 = 9"
6723
6724local t = {name="lua", version="5.4"}
6725x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
6726--> x="lua-5.4.tar.gz"
6727}
6728
6729}
6730
6731@LibEntry{string.len (s)|
6732Receives a string and returns its length.
6733The empty string @T{""} has length 0.
6734Embedded zeros are counted,
6735so @T{"a\000bc\000"} has length 5.
6736
6737}
6738
6739@LibEntry{string.lower (s)|
6740Receives a string and returns a copy of this string with all
6741uppercase letters changed to lowercase.
6742All other characters are left unchanged.
6743The definition of what an uppercase letter is depends on the current locale.
6744
6745}
6746
6747@LibEntry{string.match (s, pattern [, init])|
6748Looks for the first @emph{match} of
6749@id{pattern} @see{pm} in the string @id{s}.
6750If it finds one, then @id{match} returns
6751the captures from the pattern;
6752otherwise it returns @nil.
6753If @id{pattern} specifies no captures,
6754then the whole match is returned.
6755A third, optional numeric argument @id{init} specifies
6756where to start the search;
6757its default value @N{is 1} and can be negative.
6758
6759}
6760
6761@LibEntry{string.pack (fmt, v1, v2, @Cdots)|
6762
6763Returns a binary string containing the values @id{v1}, @id{v2}, etc.
6764packed (that is, serialized in binary form)
6765according to the format string @id{fmt} @see{pack}.
6766
6767}
6768
6769@LibEntry{string.packsize (fmt)|
6770
6771Returns the size of a string resulting from @Lid{string.pack}
6772with the given format.
6773The format string cannot have the variable-length options
6774@Char{s} or @Char{z} @see{pack}.
6775
6776}
6777
6778@LibEntry{string.rep (s, n [, sep])|
6779Returns a string that is the concatenation of @id{n} copies of
6780the string @id{s} separated by the string @id{sep}.
6781The default value for @id{sep} is the empty string
6782(that is, no separator).
6783Returns the empty string if @id{n} is not positive.
6784
6785(Note that it is very easy to exhaust the memory of your machine
6786with a single call to this function.)
6787
6788}
6789
6790@LibEntry{string.reverse (s)|
6791Returns a string that is the string @id{s} reversed.
6792
6793}
6794
6795@LibEntry{string.sub (s, i [, j])|
6796Returns the substring of @id{s} that
6797starts at @id{i} and continues until @id{j};
6798@id{i} and @id{j} can be negative.
6799If @id{j} is absent, then it is assumed to be equal to @num{-1}
6800(which is the same as the string length).
6801In particular,
6802the call @T{string.sub(s,1,j)} returns a prefix of @id{s}
6803with length @id{j},
6804and @T{string.sub(s, -i)} (for a positive @id{i})
6805returns a suffix of @id{s}
6806with length @id{i}.
6807
6808If, after the translation of negative indices,
6809@id{i} is less than 1,
6810it is corrected to 1.
6811If @id{j} is greater than the string length,
6812it is corrected to that length.
6813If, after these corrections,
6814@id{i} is greater than @id{j},
6815the function returns the empty string.
6816
6817}
6818
6819@LibEntry{string.unpack (fmt, s [, pos])|
6820
6821Returns the values packed in string @id{s} @seeF{string.pack}
6822according to the format string @id{fmt} @see{pack}.
6823An optional @id{pos} marks where
6824to start reading in @id{s} (default is 1).
6825After the read values,
6826this function also returns the index of the first unread byte in @id{s}.
6827
6828}
6829
6830@LibEntry{string.upper (s)|
6831Receives a string and returns a copy of this string with all
6832lowercase letters changed to uppercase.
6833All other characters are left unchanged.
6834The definition of what a lowercase letter is depends on the current locale.
6835
6836}
6837
6838
6839@sect3{pm| @title{Patterns}
6840
6841Patterns in Lua are described by regular strings,
6842which are interpreted as patterns by the pattern-matching functions
6843@Lid{string.find},
6844@Lid{string.gmatch},
6845@Lid{string.gsub},
6846and @Lid{string.match}.
6847This section describes the syntax and the meaning
6848(that is, what they match) of these strings.
6849
6850@sect4{@title{Character Class:}
6851A @def{character class} is used to represent a set of characters.
6852The following combinations are allowed in describing a character class:
6853@description{
6854
6855@item{@rep{x}|
6856(where @rep{x} is not one of the @emphx{magic characters}
6857@T{^$()%.[]*+-?})
6858represents the character @emph{x} itself.
6859}
6860
6861@item{@T{.}| (a dot) represents all characters.}
6862
6863@item{@T{%a}| represents all letters.}
6864
6865@item{@T{%c}| represents all control characters.}
6866
6867@item{@T{%d}| represents all digits.}
6868
6869@item{@T{%g}| represents all printable characters except space.}
6870
6871@item{@T{%l}| represents all lowercase letters.}
6872
6873@item{@T{%p}| represents all punctuation characters.}
6874
6875@item{@T{%s}| represents all space characters.}
6876
6877@item{@T{%u}| represents all uppercase letters.}
6878
6879@item{@T{%w}| represents all alphanumeric characters.}
6880
6881@item{@T{%x}| represents all hexadecimal digits.}
6882
6883@item{@T{%@rep{x}}| (where @rep{x} is any non-alphanumeric character)
6884represents the character @rep{x}.
6885This is the standard way to escape the magic characters.
6886Any non-alphanumeric character
6887(including all punctuation characters, even the non-magical)
6888can be preceded by a @Char{%}
6889when used to represent itself in a pattern.
6890}
6891
6892@item{@T{[@rep{set}]}|
6893represents the class which is the union of all
6894characters in @rep{set}.
6895A range of characters can be specified by
6896separating the end characters of the range,
6897in ascending order, with a @Char{-}.
6898All classes @T{%}@emph{x} described above can also be used as
6899components in @rep{set}.
6900All other characters in @rep{set} represent themselves.
6901For example, @T{[%w_]} (or @T{[_%w]})
6902represents all alphanumeric characters plus the underscore,
6903@T{[0-7]} represents the octal digits,
6904and @T{[0-7%l%-]} represents the octal digits plus
6905the lowercase letters plus the @Char{-} character.
6906
6907You can put a closing square bracket in a set
6908by positioning it as the first character in the set.
6909You can put a hyphen in a set
6910by positioning it as the first or the last character in the set.
6911(You can also use an escape for both cases.)
6912
6913The interaction between ranges and classes is not defined.
6914Therefore, patterns like @T{[%a-z]} or @T{[a-%%]}
6915have no meaning.
6916}
6917
6918@item{@T{[^@rep{set}]}|
6919represents the complement of @rep{set},
6920where @rep{set} is interpreted as above.
6921}
6922
6923}
6924For all classes represented by single letters (@T{%a}, @T{%c}, etc.),
6925the corresponding uppercase letter represents the complement of the class.
6926For instance, @T{%S} represents all non-space characters.
6927
6928The definitions of letter, space, and other character groups
6929depend on the current locale.
6930In particular, the class @T{[a-z]} may not be equivalent to @T{%l}.
6931
6932}
6933
6934@sect4{@title{Pattern Item:}
6935A @def{pattern item} can be
6936@itemize{
6937
6938@item{
6939a single character class,
6940which matches any single character in the class;
6941}
6942
6943@item{
6944a single character class followed by @Char{*},
6945which matches zero or more repetitions of characters in the class.
6946These repetition items will always match the longest possible sequence;
6947}
6948
6949@item{
6950a single character class followed by @Char{+},
6951which matches one or more repetitions of characters in the class.
6952These repetition items will always match the longest possible sequence;
6953}
6954
6955@item{
6956a single character class followed by @Char{-},
6957which also matches zero or more repetitions of characters in the class.
6958Unlike @Char{*},
6959these repetition items will always match the shortest possible sequence;
6960}
6961
6962@item{
6963a single character class followed by @Char{?},
6964which matches zero or one occurrence of a character in the class.
6965It always matches one occurrence if possible;
6966}
6967
6968@item{
6969@T{%@rep{n}}, for @rep{n} between 1 and 9;
6970such item matches a substring equal to the @rep{n}-th captured string
6971(see below);
6972}
6973
6974@item{
6975@T{%b@rep{xy}}, where @rep{x} and @rep{y} are two distinct characters;
6976such item matches strings that start @N{with @rep{x}}, end @N{with @rep{y}},
6977and where the @rep{x} and @rep{y} are @emph{balanced}.
6978This means that, if one reads the string from left to right,
6979counting @M{+1} for an @rep{x} and @M{-1} for a @rep{y},
6980the ending @rep{y} is the first @rep{y} where the count reaches 0.
6981For instance, the item @T{%b()} matches expressions with
6982balanced parentheses.
6983}
6984
6985@item{
6986@T{%f[@rep{set}]}, a @def{frontier pattern};
6987such item matches an empty string at any position such that
6988the next character belongs to @rep{set}
6989and the previous character does not belong to @rep{set}.
6990The set @rep{set} is interpreted as previously described.
6991The beginning and the end of the subject are handled as if
6992they were the character @Char{\0}.
6993}
6994
6995}
6996
6997}
6998
6999@sect4{@title{Pattern:}
7000A @def{pattern} is a sequence of pattern items.
7001A caret @Char{^} at the beginning of a pattern anchors the match at the
7002beginning of the subject string.
7003A @Char{$} at the end of a pattern anchors the match at the
7004end of the subject string.
7005At other positions,
7006@Char{^} and @Char{$} have no special meaning and represent themselves.
7007
7008}
7009
7010@sect4{@title{Captures:}
7011A pattern can contain sub-patterns enclosed in parentheses;
7012they describe @def{captures}.
7013When a match succeeds, the substrings of the subject string
7014that match captures are stored (@emph{captured}) for future use.
7015Captures are numbered according to their left parentheses.
7016For instance, in the pattern @T{"(a*(.)%w(%s*))"},
7017the part of the string matching @T{"a*(.)%w(%s*)"} is
7018stored as the first capture (and therefore has @N{number 1});
7019the character matching @St{.} is captured with @N{number 2},
7020and the part matching @St{%s*} has @N{number 3}.
7021
7022As a special case, the empty capture @T{()} captures
7023the current string position (a number).
7024For instance, if we apply the pattern @T{"()aa()"} on the
7025string @T{"flaaap"}, there will be two captures: @N{3 and 5}.
7026
7027}
7028
7029@sect4{@title{Multiple matches:}
7030The function @Lid{string.gsub} and the iterator @Lid{string.gmatch}
7031match multiple occurrences of the given pattern in the subject.
7032For these functions,
7033a new match is considered valid only
7034if it ends at least one byte after the previous match.
7035In other words, the pattern machine never accepts the
7036empty string as a match immediately after another match.
7037As an example,
7038consider the results of the following code:
7039@verbatim{
7040> string.gsub("abc", "()a*()", print)
7041--> 1 2
7042--> 3 3
7043--> 4 4
7044}
7045The second and third results come from Lua matching an empty
7046string after @Char{b} and another one after @Char{c}.
7047Lua does not match an empty string after @Char{a},
7048because it would end at the same position of the previous match.
7049
7050}
7051
7052}
7053
7054@sect3{pack| @title{Format Strings for Pack and Unpack}
7055
7056The first argument to @Lid{string.pack},
7057@Lid{string.packsize}, and @Lid{string.unpack}
7058is a format string,
7059which describes the layout of the structure being created or read.
7060
7061A format string is a sequence of conversion options.
7062The conversion options are as follows:
7063@description{
7064@item{@T{<}|sets little endian}
7065@item{@T{>}|sets big endian}
7066@item{@T{=}|sets native endian}
7067@item{@T{![@rep{n}]}|sets maximum alignment to @id{n}
7068(default is native alignment)}
7069@item{@T{b}|a signed byte (@id{char})}
7070@item{@T{B}|an unsigned byte (@id{char})}
7071@item{@T{h}|a signed @id{short} (native size)}
7072@item{@T{H}|an unsigned @id{short} (native size)}
7073@item{@T{l}|a signed @id{long} (native size)}
7074@item{@T{L}|an unsigned @id{long} (native size)}
7075@item{@T{j}|a @id{lua_Integer}}
7076@item{@T{J}|a @id{lua_Unsigned}}
7077@item{@T{T}|a @id{size_t} (native size)}
7078@item{@T{i[@rep{n}]}|a signed @id{int} with @id{n} bytes
7079(default is native size)}
7080@item{@T{I[@rep{n}]}|an unsigned @id{int} with @id{n} bytes
7081(default is native size)}
7082@item{@T{f}|a @id{float} (native size)}
7083@item{@T{d}|a @id{double} (native size)}
7084@item{@T{n}|a @id{lua_Number}}
7085@item{@T{c@rep{n}}|a fixed-sized string with @id{n} bytes}
7086@item{@T{z}|a zero-terminated string}
7087@item{@T{s[@emph{n}]}|a string preceded by its length
7088coded as an unsigned integer with @id{n} bytes
7089(default is a @id{size_t})}
7090@item{@T{x}|one byte of padding}
7091@item{@T{X@rep{op}}|an empty item that aligns
7092according to option @id{op}
7093(which is otherwise ignored)}
7094@item{@Char{ }|(empty space) ignored}
7095}
7096(A @St{[@rep{n}]} means an optional integral numeral.)
7097Except for padding, spaces, and configurations
7098(options @St{xX <=>!}),
7099each option corresponds to an argument (in @Lid{string.pack})
7100or a result (in @Lid{string.unpack}).
7101
7102For options @St{!@rep{n}}, @St{s@rep{n}}, @St{i@rep{n}}, and @St{I@rep{n}},
7103@id{n} can be any integer between 1 and 16.
7104All integral options check overflows;
7105@Lid{string.pack} checks whether the given value fits in the given size;
7106@Lid{string.unpack} checks whether the read value fits in a Lua integer.
7107
7108Any format string starts as if prefixed by @St{!1=},
7109that is,
7110with maximum alignment of 1 (no alignment)
7111and native endianness.
7112
7113Alignment works as follows:
7114For each option,
7115the format gets extra padding until the data starts
7116at an offset that is a multiple of the minimum between the
7117option size and the maximum alignment;
7118this minimum must be a power of 2.
7119Options @St{c} and @St{z} are not aligned;
7120option @St{s} follows the alignment of its starting integer.
7121
7122All padding is filled with zeros by @Lid{string.pack}
7123(and ignored by @Lid{string.unpack}).
7124
7125}
7126
7127}
7128
7129@sect2{utf8| @title{UTF-8 Support}
7130
7131This library provides basic support for @x{UTF-8} encoding.
7132It provides all its functions inside the table @defid{utf8}.
7133This library does not provide any support for @x{Unicode} other
7134than the handling of the encoding.
7135Any operation that needs the meaning of a character,
7136such as character classification, is outside its scope.
7137
7138Unless stated otherwise,
7139all functions that expect a byte position as a parameter
7140assume that the given position is either the start of a byte sequence
7141or one plus the length of the subject string.
7142As in the string library,
7143negative indices count from the end of the string.
7144
7145
7146@LibEntry{utf8.char (@Cdots)|
7147Receives zero or more integers,
7148converts each one to its corresponding UTF-8 byte sequence
7149and returns a string with the concatenation of all these sequences.
7150
7151}
7152
7153@LibEntry{utf8.charpattern|
7154The pattern (a string, not a function) @St{[\0-\x7F\xC2-\xF4][\x80-\xBF]*}
7155@see{pm},
7156which matches exactly one UTF-8 byte sequence,
7157assuming that the subject is a valid UTF-8 string.
7158
7159}
7160
7161@LibEntry{utf8.codes (s)|
7162
7163Returns values so that the construction
7164@verbatim{
7165for p, c in utf8.codes(s) do @rep{body} end
7166}
7167will iterate over all characters in string @id{s},
7168with @id{p} being the position (in bytes) and @id{c} the code point
7169of each character.
7170It raises an error if it meets any invalid byte sequence.
7171
7172}
7173
7174@LibEntry{utf8.codepoint (s [, i [, j]])|
7175Returns the codepoints (as integers) from all characters in @id{s}
7176that start between byte position @id{i} and @id{j} (both included).
7177The default for @id{i} is 1 and for @id{j} is @id{i}.
7178It raises an error if it meets any invalid byte sequence.
7179
7180}
7181
7182@LibEntry{utf8.len (s [, i [, j]])|
7183Returns the number of UTF-8 characters in string @id{s}
7184that start between positions @id{i} and @id{j} (both inclusive).
7185The default for @id{i} is @num{1} and for @id{j} is @num{-1}.
7186If it finds any invalid byte sequence,
7187returns a false value plus the position of the first invalid byte.
7188
7189}
7190
7191@LibEntry{utf8.offset (s, n [, i])|
7192Returns the position (in bytes) where the encoding of the
7193@id{n}-th character of @id{s}
7194(counting from position @id{i}) starts.
7195A negative @id{n} gets characters before position @id{i}.
7196The default for @id{i} is 1 when @id{n} is non-negative
7197and @T{#s + 1} otherwise,
7198so that @T{utf8.offset(s, -n)} gets the offset of the
7199@id{n}-th character from the end of the string.
7200If the specified character is neither in the subject
7201nor right after its end,
7202the function returns @nil.
7203
7204As a special case,
7205when @id{n} is 0 the function returns the start of the encoding
7206of the character that contains the @id{i}-th byte of @id{s}.
7207
7208This function assumes that @id{s} is a valid UTF-8 string.
7209
7210}
7211
7212}
7213
7214@sect2{tablib| @title{Table Manipulation}
7215
7216This library provides generic functions for table manipulation.
7217It provides all its functions inside the table @defid{table}.
7218
7219Remember that, whenever an operation needs the length of a table,
7220all caveats about the length operator apply @see{len-op}.
7221All functions ignore non-numeric keys
7222in the tables given as arguments.
7223
7224
7225@LibEntry{table.concat (list [, sep [, i [, j]]])|
7226
7227Given a list where all elements are strings or numbers,
7228returns the string @T{list[i]..sep..list[i+1] @Cdots sep..list[j]}.
7229The default value for @id{sep} is the empty string,
7230the default for @id{i} is 1,
7231and the default for @id{j} is @T{#list}.
7232If @id{i} is greater than @id{j}, returns the empty string.
7233
7234}
7235
7236@LibEntry{table.insert (list, [pos,] value)|
7237
7238Inserts element @id{value} at position @id{pos} in @id{list},
7239shifting up the elements
7240@T{list[pos], list[pos+1], @Cdots, list[#list]}.
7241The default value for @id{pos} is @T{#list+1},
7242so that a call @T{table.insert(t,x)} inserts @id{x} at the end
7243of list @id{t}.
7244
7245}
7246
7247@LibEntry{table.move (a1, f, e, t [,a2])|
7248
7249Moves elements from table @id{a1} to table @id{a2},
7250performing the equivalent to the following
7251multiple assignment:
7252@T{a2[t],@Cdots = a1[f],@Cdots,a1[e]}.
7253The default for @id{a2} is @id{a1}.
7254The destination range can overlap with the source range.
7255The number of elements to be moved must fit in a Lua integer.
7256
7257Returns the destination table @id{a2}.
7258
7259}
7260
7261@LibEntry{table.pack (@Cdots)|
7262
7263Returns a new table with all arguments stored into keys 1, 2, etc.
7264and with a field @St{n} with the total number of arguments.
7265Note that the resulting table may not be a sequence,
7266if some arguments are @nil.
7267
7268}
7269
7270@LibEntry{table.remove (list [, pos])|
7271
7272Removes from @id{list} the element at position @id{pos},
7273returning the value of the removed element.
7274When @id{pos} is an integer between 1 and @T{#list},
7275it shifts down the elements
7276@T{list[pos+1], list[pos+2], @Cdots, list[#list]}
7277and erases element @T{list[#list]};
7278The index @id{pos} can also be 0 when @T{#list} is 0,
7279or @T{#list + 1}.
7280
7281The default value for @id{pos} is @T{#list},
7282so that a call @T{table.remove(l)} removes the last element
7283of list @id{l}.
7284
7285}
7286
7287@LibEntry{table.sort (list [, comp])|
7288
7289Sorts list elements in a given order, @emph{in-place},
7290from @T{list[1]} to @T{list[#list]}.
7291If @id{comp} is given,
7292then it must be a function that receives two list elements
7293and returns true when the first element must come
7294before the second in the final order
7295(so that, after the sort,
7296@T{i < j} implies @T{not comp(list[j],list[i])}).
7297If @id{comp} is not given,
7298then the standard Lua operator @T{<} is used instead.
7299
7300Note that the @id{comp} function must define
7301a strict partial order over the elements in the list;
7302that is, it must be asymmetric and transitive.
7303Otherwise, no valid sort may be possible.
7304
7305The sort algorithm is not stable:
7306elements considered equal by the given order
7307may have their relative positions changed by the sort.
7308
7309}
7310
7311@LibEntry{table.unpack (list [, i [, j]])|
7312
7313Returns the elements from the given list.
7314This function is equivalent to
7315@verbatim{
7316return list[i], list[i+1], @Cdots, list[j]
7317}
7318By default, @id{i} @N{is 1} and @id{j} is @T{#list}.
7319
7320}
7321
7322}
7323
7324@sect2{mathlib| @title{Mathematical Functions}
7325
7326This library provides basic mathematical functions.
7327It provides all its functions and constants inside the table @defid{math}.
7328Functions with the annotation @St{integer/float} give
7329integer results for integer arguments
7330and float results for float (or mixed) arguments.
7331Rounding functions
7332(@Lid{math.ceil}, @Lid{math.floor}, and @Lid{math.modf})
7333return an integer when the result fits in the range of an integer,
7334or a float otherwise.
7335
7336@LibEntry{math.abs (x)|
7337
7338Returns the absolute value of @id{x}. (integer/float)
7339
7340}
7341
7342@LibEntry{math.acos (x)|
7343
7344Returns the arc cosine of @id{x} (in radians).
7345
7346}
7347
7348@LibEntry{math.asin (x)|
7349
7350Returns the arc sine of @id{x} (in radians).
7351
7352}
7353
7354@LibEntry{math.atan (y [, x])|
7355
7356@index{atan2}
7357Returns the arc tangent of @T{y/x} (in radians),
7358but uses the signs of both parameters to find the
7359quadrant of the result.
7360(It also handles correctly the case of @id{x} being zero.)
7361
7362The default value for @id{x} is 1,
7363so that the call @T{math.atan(y)}
7364returns the arc tangent of @id{y}.
7365
7366}
7367
7368@LibEntry{math.ceil (x)|
7369
7370Returns the smallest integral value larger than or equal to @id{x}.
7371
7372}
7373
7374@LibEntry{math.cos (x)|
7375
7376Returns the cosine of @id{x} (assumed to be in radians).
7377
7378}
7379
7380@LibEntry{math.deg (x)|
7381
7382Converts the angle @id{x} from radians to degrees.
7383
7384}
7385
7386@LibEntry{math.exp (x)|
7387
7388Returns the value @M{e@sp{x}}
7389(where @id{e} is the base of natural logarithms).
7390
7391}
7392
7393@LibEntry{math.floor (x)|
7394
7395Returns the largest integral value smaller than or equal to @id{x}.
7396
7397}
7398
7399@LibEntry{math.fmod (x, y)|
7400
7401Returns the remainder of the division of @id{x} by @id{y}
7402that rounds the quotient towards zero. (integer/float)
7403
7404}
7405
7406@LibEntry{math.huge|
7407
7408The float value @idx{HUGE_VAL},
7409a value larger than any other numeric value.
7410
7411}
7412
7413@LibEntry{math.log (x [, base])|
7414
7415Returns the logarithm of @id{x} in the given base.
7416The default for @id{base} is @M{e}
7417(so that the function returns the natural logarithm of @id{x}).
7418
7419}
7420
7421@LibEntry{math.max (x, @Cdots)|
7422
7423Returns the argument with the maximum value,
7424according to the Lua operator @T{<}. (integer/float)
7425
7426}
7427
7428@LibEntry{math.maxinteger|
7429An integer with the maximum value for an integer.
7430
7431}
7432
7433@LibEntry{math.min (x, @Cdots)|
7434
7435Returns the argument with the minimum value,
7436according to the Lua operator @T{<}. (integer/float)
7437
7438}
7439
7440@LibEntry{math.mininteger|
7441An integer with the minimum value for an integer.
7442
7443}
7444
7445@LibEntry{math.modf (x)|
7446
7447Returns the integral part of @id{x} and the fractional part of @id{x}.
7448Its second result is always a float.
7449
7450}
7451
7452@LibEntry{math.pi|
7453
7454The value of @M{@pi}.
7455
7456}
7457
7458@LibEntry{math.rad (x)|
7459
7460Converts the angle @id{x} from degrees to radians.
7461
7462}
7463
7464@LibEntry{math.random ([m [, n]])|
7465
7466When called without arguments,
7467returns a pseudo-random float with uniform distribution
7468in the range @C{(} @M{[0,1)}. @C{]}
7469When called with two integers @id{m} and @id{n},
7470@id{math.random} returns a pseudo-random integer
7471with uniform distribution in the range @M{[m, n]}.
7472The call @T{math.random(n)}, for a positive @id{n},
7473is equivalent to @T{math.random(1,n)}.
7474The call @T{math.random(0)} produces an integer with
7475all bits (pseudo)random.
7476
7477Lua initializes its pseudo-random generator with
7478a weak attempt for ``randomness'',
7479so that @id{math.random} should generate
7480different sequences of results each time the program runs.
7481To ensure a required level of randomness to the initial state
7482(or contrarily, to have a deterministic sequence,
7483for instance when debugging a program),
7484you should call @Lid{math.randomseed} explicitly.
7485
7486The results from this function have good statistical qualities,
7487but they are not cryptographically secure.
7488(For instance, there are no garanties that it is hard
7489to predict future results based on the observation of
7490some number of previous results.)
7491
7492}
7493
7494@LibEntry{math.randomseed (x [, y])|
7495
7496Sets @id{x} and @id{y} as the @Q{seed}
7497for the pseudo-random generator:
7498equal seeds produce equal sequences of numbers.
7499The default for @id{y} is zero.
7500
7501}
7502
7503@LibEntry{math.sin (x)|
7504
7505Returns the sine of @id{x} (assumed to be in radians).
7506
7507}
7508
7509@LibEntry{math.sqrt (x)|
7510
7511Returns the square root of @id{x}.
7512(You can also use the expression @T{x^0.5} to compute this value.)
7513
7514}
7515
7516@LibEntry{math.tan (x)|
7517
7518Returns the tangent of @id{x} (assumed to be in radians).
7519
7520}
7521
7522@LibEntry{math.tointeger (x)|
7523
7524If the value @id{x} is convertible to an integer,
7525returns that integer.
7526Otherwise, returns @nil.
7527
7528}
7529
7530@LibEntry{math.type (x)|
7531
7532Returns @St{integer} if @id{x} is an integer,
7533@St{float} if it is a float,
7534or @nil if @id{x} is not a number.
7535
7536}
7537
7538@LibEntry{math.ult (m, n)|
7539
7540Returns a boolean,
7541true if and only if integer @id{m} is below integer @id{n} when
7542they are compared as @x{unsigned integers}.
7543
7544}
7545
7546}
7547
7548
7549@sect2{iolib| @title{Input and Output Facilities}
7550
7551The I/O library provides two different styles for file manipulation.
7552The first one uses implicit file handles;
7553that is, there are operations to set a default input file and a
7554default output file,
7555and all input/output operations are over these default files.
7556The second style uses explicit file handles.
7557
7558When using implicit file handles,
7559all operations are supplied by table @defid{io}.
7560When using explicit file handles,
7561the operation @Lid{io.open} returns a file handle
7562and then all operations are supplied as methods of the file handle.
7563
7564The table @id{io} also provides
7565three predefined file handles with their usual meanings from C:
7566@defid{io.stdin}, @defid{io.stdout}, and @defid{io.stderr}.
7567The I/O library never closes these files.
7568
7569Unless otherwise stated,
7570all I/O functions return @nil on failure
7571(plus an error message as a second result and
7572a system-dependent error code as a third result)
7573and some value different from @nil on success.
7574On non-POSIX systems,
7575the computation of the error message and error code
7576in case of errors
7577may be not @x{thread safe},
7578because they rely on the global C variable @id{errno}.
7579
7580@LibEntry{io.close ([file])|
7581
7582Equivalent to @T{file:close()}.
7583Without a @id{file}, closes the default output file.
7584
7585}
7586
7587@LibEntry{io.flush ()|
7588
7589Equivalent to @T{io.output():flush()}.
7590
7591}
7592
7593@LibEntry{io.input ([file])|
7594
7595When called with a file name, it opens the named file (in text mode),
7596and sets its handle as the default input file.
7597When called with a file handle,
7598it simply sets this file handle as the default input file.
7599When called without parameters,
7600it returns the current default input file.
7601
7602In case of errors this function raises the error,
7603instead of returning an error code.
7604
7605}
7606
7607@LibEntry{io.lines ([filename, @Cdots])|
7608
7609Opens the given file name in read mode
7610and returns an iterator function that
7611works like @T{file:lines(@Cdots)} over the opened file.
7612When the iterator function detects the end of file,
7613it returns no values (to finish the loop) and automatically closes the file.
7614
7615The call @T{io.lines()} (with no file name) is equivalent
7616to @T{io.input():lines("l")};
7617that is, it iterates over the lines of the default input file.
7618In this case, the iterator does not close the file when the loop ends.
7619
7620In case of errors this function raises the error,
7621instead of returning an error code.
7622
7623}
7624
7625@LibEntry{io.open (filename [, mode])|
7626
7627This function opens a file,
7628in the mode specified in the string @id{mode}.
7629In case of success,
7630it returns a new file handle.
7631
7632The @id{mode} string can be any of the following:
7633@description{
7634@item{@St{r}| read mode (the default);}
7635@item{@St{w}| write mode;}
7636@item{@St{a}| append mode;}
7637@item{@St{r+}| update mode, all previous data is preserved;}
7638@item{@St{w+}| update mode, all previous data is erased;}
7639@item{@St{a+}| append update mode, previous data is preserved,
7640 writing is only allowed at the end of file.}
7641}
7642The @id{mode} string can also have a @Char{b} at the end,
7643which is needed in some systems to open the file in binary mode.
7644
7645}
7646
7647@LibEntry{io.output ([file])|
7648
7649Similar to @Lid{io.input}, but operates over the default output file.
7650
7651}
7652
7653@LibEntry{io.popen (prog [, mode])|
7654
7655This function is system dependent and is not available
7656on all platforms.
7657
7658Starts program @id{prog} in a separated process and returns
7659a file handle that you can use to read data from this program
7660(if @id{mode} is @T{"r"}, the default)
7661or to write data to this program
7662(if @id{mode} is @T{"w"}).
7663
7664}
7665
7666@LibEntry{io.read (@Cdots)|
7667
7668Equivalent to @T{io.input():read(@Cdots)}.
7669
7670}
7671
7672@LibEntry{io.tmpfile ()|
7673
7674In case of success,
7675returns a handle for a temporary file.
7676This file is opened in update mode
7677and it is automatically removed when the program ends.
7678
7679}
7680
7681@LibEntry{io.type (obj)|
7682
7683Checks whether @id{obj} is a valid file handle.
7684Returns the string @T{"file"} if @id{obj} is an open file handle,
7685@T{"closed file"} if @id{obj} is a closed file handle,
7686or @nil if @id{obj} is not a file handle.
7687
7688}
7689
7690@LibEntry{io.write (@Cdots)|
7691
7692Equivalent to @T{io.output():write(@Cdots)}.
7693
7694
7695}
7696
7697@LibEntry{file:close ()|
7698
7699Closes @id{file}.
7700Note that files are automatically closed when
7701their handles are garbage collected,
7702but that takes an unpredictable amount of time to happen.
7703
7704When closing a file handle created with @Lid{io.popen},
7705@Lid{file:close} returns the same values
7706returned by @Lid{os.execute}.
7707
7708}
7709
7710@LibEntry{file:flush ()|
7711
7712Saves any written data to @id{file}.
7713
7714}
7715
7716@LibEntry{file:lines (@Cdots)|
7717
7718Returns an iterator function that,
7719each time it is called,
7720reads the file according to the given formats.
7721When no format is given,
7722uses @St{l} as a default.
7723As an example, the construction
7724@verbatim{
7725for c in file:lines(1) do @rep{body} end
7726}
7727will iterate over all characters of the file,
7728starting at the current position.
7729Unlike @Lid{io.lines}, this function does not close the file
7730when the loop ends.
7731
7732In case of errors this function raises the error,
7733instead of returning an error code.
7734
7735}
7736
7737@LibEntry{file:read (@Cdots)|
7738
7739Reads the file @id{file},
7740according to the given formats, which specify what to read.
7741For each format,
7742the function returns a string or a number with the characters read,
7743or @nil if it cannot read data with the specified format.
7744(In this latter case,
7745the function does not read subsequent formats.)
7746When called without parameters,
7747it uses a default format that reads the next line
7748(see below).
7749
7750The available formats are
7751@description{
7752
7753@item{@St{n}|
7754reads a numeral and returns it as a float or an integer,
7755following the lexical conventions of Lua.
7756(The numeral may have leading spaces and a sign.)
7757This format always reads the longest input sequence that
7758is a valid prefix for a numeral;
7759if that prefix does not form a valid numeral
7760(e.g., an empty string, @St{0x}, or @St{3.4e-}),
7761it is discarded and the format returns @nil.
7762}
7763
7764@item{@St{a}|
7765reads the whole file, starting at the current position.
7766On end of file, it returns the empty string.
7767}
7768
7769@item{@St{l}|
7770reads the next line skipping the end of line,
7771returning @nil on end of file.
7772This is the default format.
7773}
7774
7775@item{@St{L}|
7776reads the next line keeping the end-of-line character (if present),
7777returning @nil on end of file.
7778}
7779
7780@item{@emph{number}|
7781reads a string with up to this number of bytes,
7782returning @nil on end of file.
7783If @id{number} is zero,
7784it reads nothing and returns an empty string,
7785or @nil on end of file.
7786}
7787
7788}
7789The formats @St{l} and @St{L} should be used only for text files.
7790
7791}
7792
7793@LibEntry{file:seek ([whence [, offset]])|
7794
7795Sets and gets the file position,
7796measured from the beginning of the file,
7797to the position given by @id{offset} plus a base
7798specified by the string @id{whence}, as follows:
7799@description{
7800@item{@St{set}| base is position 0 (beginning of the file);}
7801@item{@St{cur}| base is current position;}
7802@item{@St{end}| base is end of file;}
7803}
7804In case of success, @id{seek} returns the final file position,
7805measured in bytes from the beginning of the file.
7806If @id{seek} fails, it returns @nil,
7807plus a string describing the error.
7808
7809The default value for @id{whence} is @T{"cur"},
7810and for @id{offset} is 0.
7811Therefore, the call @T{file:seek()} returns the current
7812file position, without changing it;
7813the call @T{file:seek("set")} sets the position to the
7814beginning of the file (and returns 0);
7815and the call @T{file:seek("end")} sets the position to the
7816end of the file, and returns its size.
7817
7818}
7819
7820@LibEntry{file:setvbuf (mode [, size])|
7821
7822Sets the buffering mode for an output file.
7823There are three available modes:
7824@description{
7825
7826@item{@St{no}|
7827no buffering; the result of any output operation appears immediately.
7828}
7829
7830@item{@St{full}|
7831full buffering; output operation is performed only
7832when the buffer is full or when
7833you explicitly @T{flush} the file @seeF{io.flush}.
7834}
7835
7836@item{@St{line}|
7837line buffering; output is buffered until a newline is output
7838or there is any input from some special files
7839(such as a terminal device).
7840}
7841
7842}
7843For the last two cases, @id{size}
7844specifies the size of the buffer, in bytes.
7845The default is an appropriate size.
7846
7847}
7848
7849@LibEntry{file:write (@Cdots)|
7850
7851Writes the value of each of its arguments to @id{file}.
7852The arguments must be strings or numbers.
7853
7854In case of success, this function returns @id{file}.
7855Otherwise it returns @nil plus a string describing the error.
7856
7857}
7858
7859}
7860
7861@sect2{oslib| @title{Operating System Facilities}
7862
7863This library is implemented through table @defid{os}.
7864
7865
7866@LibEntry{os.clock ()|
7867
7868Returns an approximation of the amount in seconds of CPU time
7869used by the program.
7870
7871}
7872
7873@LibEntry{os.date ([format [, time]])|
7874
7875Returns a string or a table containing date and time,
7876formatted according to the given string @id{format}.
7877
7878If the @id{time} argument is present,
7879this is the time to be formatted
7880(see the @Lid{os.time} function for a description of this value).
7881Otherwise, @id{date} formats the current time.
7882
7883If @id{format} starts with @Char{!},
7884then the date is formatted in Coordinated Universal Time.
7885After this optional character,
7886if @id{format} is the string @St{*t},
7887then @id{date} returns a table with the following fields:
7888@id{year}, @id{month} (1@En{}12), @id{day} (1@En{}31),
7889@id{hour} (0@En{}23), @id{min} (0@En{}59),
7890@id{sec} (0@En{}61, due to leap seconds),
7891@id{wday} (weekday, 1@En{}7, Sunday @N{is 1}),
7892@id{yday} (day of the year, 1@En{}366),
7893and @id{isdst} (daylight saving flag, a boolean).
7894This last field may be absent
7895if the information is not available.
7896
7897If @id{format} is not @St{*t},
7898then @id{date} returns the date as a string,
7899formatted according to the same rules as the @ANSI{strftime}.
7900
7901When called without arguments,
7902@id{date} returns a reasonable date and time representation that depends on
7903the host system and on the current locale.
7904(More specifically, @T{os.date()} is equivalent to @T{os.date("%c")}.)
7905
7906On non-POSIX systems,
7907this function may be not @x{thread safe}
7908because of its reliance on @CId{gmtime} and @CId{localtime}.
7909
7910}
7911
7912@LibEntry{os.difftime (t2, t1)|
7913
7914Returns the difference, in seconds,
7915from time @id{t1} to time @id{t2}
7916(where the times are values returned by @Lid{os.time}).
7917In @x{POSIX}, @x{Windows}, and some other systems,
7918this value is exactly @id{t2}@M{-}@id{t1}.
7919
7920}
7921
7922@LibEntry{os.execute ([command])|
7923
7924This function is equivalent to the @ANSI{system}.
7925It passes @id{command} to be executed by an operating system shell.
7926Its first result is @true
7927if the command terminated successfully,
7928or @nil otherwise.
7929After this first result
7930the function returns a string plus a number,
7931as follows:
7932@description{
7933
7934@item{@St{exit}|
7935the command terminated normally;
7936the following number is the exit status of the command.
7937}
7938
7939@item{@St{signal}|
7940the command was terminated by a signal;
7941the following number is the signal that terminated the command.
7942}
7943
7944}
7945
7946When called without a @id{command},
7947@id{os.execute} returns a boolean that is true if a shell is available.
7948
7949}
7950
7951@LibEntry{os.exit ([code [, close]])|
7952
7953Calls the @ANSI{exit} to terminate the host program.
7954If @id{code} is @Rw{true},
7955the returned status is @idx{EXIT_SUCCESS};
7956if @id{code} is @Rw{false},
7957the returned status is @idx{EXIT_FAILURE};
7958if @id{code} is a number,
7959the returned status is this number.
7960The default value for @id{code} is @Rw{true}.
7961
7962If the optional second argument @id{close} is true,
7963closes the Lua state before exiting.
7964
7965}
7966
7967@LibEntry{os.getenv (varname)|
7968
7969Returns the value of the process environment variable @id{varname},
7970or @nil if the variable is not defined.
7971
7972}
7973
7974@LibEntry{os.remove (filename)|
7975
7976Deletes the file (or empty directory, on @x{POSIX} systems)
7977with the given name.
7978If this function fails, it returns @nil,
7979plus a string describing the error and the error code.
7980Otherwise, it returns true.
7981
7982}
7983
7984@LibEntry{os.rename (oldname, newname)|
7985
7986Renames the file or directory named @id{oldname} to @id{newname}.
7987If this function fails, it returns @nil,
7988plus a string describing the error and the error code.
7989Otherwise, it returns true.
7990
7991}
7992
7993@LibEntry{os.setlocale (locale [, category])|
7994
7995Sets the current locale of the program.
7996@id{locale} is a system-dependent string specifying a locale;
7997@id{category} is an optional string describing which category to change:
7998@T{"all"}, @T{"collate"}, @T{"ctype"},
7999@T{"monetary"}, @T{"numeric"}, or @T{"time"};
8000the default category is @T{"all"}.
8001The function returns the name of the new locale,
8002or @nil if the request cannot be honored.
8003
8004If @id{locale} is the empty string,
8005the current locale is set to an implementation-defined native locale.
8006If @id{locale} is the string @St{C},
8007the current locale is set to the standard C locale.
8008
8009When called with @nil as the first argument,
8010this function only returns the name of the current locale
8011for the given category.
8012
8013This function may be not @x{thread safe}
8014because of its reliance on @CId{setlocale}.
8015
8016}
8017
8018@LibEntry{os.time ([table])|
8019
8020Returns the current time when called without arguments,
8021or a time representing the local date and time specified by the given table.
8022This table must have fields @id{year}, @id{month}, and @id{day},
8023and may have fields
8024@id{hour} (default is 12),
8025@id{min} (default is 0),
8026@id{sec} (default is 0),
8027and @id{isdst} (default is @nil).
8028Other fields are ignored.
8029For a description of these fields, see the @Lid{os.date} function.
8030
8031When the function is called,
8032the values in these fields do not need to be inside their valid ranges.
8033For instance, if @id{sec} is -10,
8034it means 10 seconds before the time specified by the other fields;
8035if @id{hour} is 1000,
8036it means 1000 hours after the time specified by the other fields.
8037
8038The returned value is a number, whose meaning depends on your system.
8039In @x{POSIX}, @x{Windows}, and some other systems,
8040this number counts the number
8041of seconds since some given start time (the @Q{epoch}).
8042In other systems, the meaning is not specified,
8043and the number returned by @id{time} can be used only as an argument to
8044@Lid{os.date} and @Lid{os.difftime}.
8045
8046When called with a table,
8047@id{os.time} also normalizes all the fields
8048documented in the @Lid{os.date} function,
8049so that they represent the same time as before the call
8050but with values inside their valid ranges.
8051
8052}
8053
8054@LibEntry{os.tmpname ()|
8055
8056Returns a string with a file name that can
8057be used for a temporary file.
8058The file must be explicitly opened before its use
8059and explicitly removed when no longer needed.
8060
8061In @x{POSIX} systems,
8062this function also creates a file with that name,
8063to avoid security risks.
8064(Someone else might create the file with wrong permissions
8065in the time between getting the name and creating the file.)
8066You still have to open the file to use it
8067and to remove it (even if you do not use it).
8068
8069When possible,
8070you may prefer to use @Lid{io.tmpfile},
8071which automatically removes the file when the program ends.
8072
8073}
8074
8075}
8076
8077@sect2{debuglib| @title{The Debug Library}
8078
8079This library provides
8080the functionality of the @link{debugI|debug interface} to Lua programs.
8081You should exert care when using this library.
8082Several of its functions
8083violate basic assumptions about Lua code
8084(e.g., that variables local to a function
8085cannot be accessed from outside;
8086that userdata metatables cannot be changed by Lua code;
8087that Lua programs do not crash)
8088and therefore can compromise otherwise secure code.
8089Moreover, some functions in this library may be slow.
8090
8091All functions in this library are provided
8092inside the @defid{debug} table.
8093All functions that operate over a thread
8094have an optional first argument which is the
8095thread to operate over.
8096The default is always the current thread.
8097
8098
8099@LibEntry{debug.debug ()|
8100
8101Enters an interactive mode with the user,
8102running each string that the user enters.
8103Using simple commands and other debug facilities,
8104the user can inspect global and local variables,
8105change their values, evaluate expressions, and so on.
8106A line containing only the word @id{cont} finishes this function,
8107so that the caller continues its execution.
8108
8109Note that commands for @id{debug.debug} are not lexically nested
8110within any function and so have no direct access to local variables.
8111
8112}
8113
8114@LibEntry{debug.gethook ([thread])|
8115
8116Returns the current hook settings of the thread, as three values:
8117the current hook function, the current hook mask,
8118and the current hook count
8119(as set by the @Lid{debug.sethook} function).
8120
8121}
8122
8123@LibEntry{debug.getinfo ([thread,] f [, what])|
8124
8125Returns a table with information about a function.
8126You can give the function directly
8127or you can give a number as the value of @id{f},
8128which means the function running at level @id{f} of the call stack
8129of the given thread:
8130@N{level 0} is the current function (@id{getinfo} itself);
8131@N{level 1} is the function that called @id{getinfo}
8132(except for tail calls, which do not count on the stack);
8133and so on.
8134If @id{f} is a number larger than the number of active functions,
8135then @id{getinfo} returns @nil.
8136
8137The returned table can contain all the fields returned by @Lid{lua_getinfo},
8138with the string @id{what} describing which fields to fill in.
8139The default for @id{what} is to get all information available,
8140except the table of valid lines.
8141If present,
8142the option @Char{f}
8143adds a field named @id{func} with the function itself.
8144If present,
8145the option @Char{L}
8146adds a field named @id{activelines} with the table of
8147valid lines.
8148
8149For instance, the expression @T{debug.getinfo(1,"n").name} returns
8150a name for the current function,
8151if a reasonable name can be found,
8152and the expression @T{debug.getinfo(print)}
8153returns a table with all available information
8154about the @Lid{print} function.
8155
8156}
8157
8158@LibEntry{debug.getlocal ([thread,] f, local)|
8159
8160This function returns the name and the value of the local variable
8161with index @id{local} of the function at level @id{f} of the stack.
8162This function accesses not only explicit local variables,
8163but also parameters, temporaries, etc.
8164
8165The first parameter or local variable has @N{index 1}, and so on,
8166following the order that they are declared in the code,
8167counting only the variables that are active
8168in the current scope of the function.
8169Negative indices refer to vararg parameters;
8170@num{-1} is the first vararg parameter.
8171The function returns @nil if there is no variable with the given index,
8172and raises an error when called with a level out of range.
8173(You can call @Lid{debug.getinfo} to check whether the level is valid.)
8174
8175Variable names starting with @Char{(} (open parenthesis) @C{)}
8176represent variables with no known names
8177(internal variables such as loop control variables,
8178and variables from chunks saved without debug information).
8179
8180The parameter @id{f} may also be a function.
8181In that case, @id{getlocal} returns only the name of function parameters.
8182
8183}
8184
8185@LibEntry{debug.getmetatable (value)|
8186
8187Returns the metatable of the given @id{value}
8188or @nil if it does not have a metatable.
8189
8190}
8191
8192@LibEntry{debug.getregistry ()|
8193
8194Returns the registry table @see{registry}.
8195
8196}
8197
8198@LibEntry{debug.getupvalue (f, up)|
8199
8200This function returns the name and the value of the upvalue
8201with index @id{up} of the function @id{f}.
8202The function returns @nil if there is no upvalue with the given index.
8203
8204Variable names starting with @Char{(} (open parenthesis) @C{)}
8205represent variables with no known names
8206(variables from chunks saved without debug information).
8207
8208}
8209
8210@LibEntry{debug.getuservalue (u, n)|
8211
8212Returns the @id{n}-th user value associated
8213to the userdata @id{u} plus a boolean,
8214@false if the userdata does not have that value.
8215
8216}
8217
8218@LibEntry{debug.sethook ([thread,] hook, mask [, count])|
8219
8220Sets the given function as a hook.
8221The string @id{mask} and the number @id{count} describe
8222when the hook will be called.
8223The string mask may have any combination of the following characters,
8224with the given meaning:
8225@description{
8226@item{@Char{c}| the hook is called every time Lua calls a function;}
8227@item{@Char{r}| the hook is called every time Lua returns from a function;}
8228@item{@Char{l}| the hook is called every time Lua enters a new line of code.}
8229}
8230Moreover,
8231with a @id{count} different from zero,
8232the hook is called also after every @id{count} instructions.
8233
8234When called without arguments,
8235@Lid{debug.sethook} turns off the hook.
8236
8237When the hook is called, its first parameter is a string
8238describing the event that has triggered its call:
8239@T{"call"} (or @T{"tail call"}),
8240@T{"return"},
8241@T{"line"}, and @T{"count"}.
8242For line events,
8243the hook also gets the new line number as its second parameter.
8244Inside a hook,
8245you can call @id{getinfo} with @N{level 2} to get more information about
8246the running function
8247(@N{level 0} is the @id{getinfo} function,
8248and @N{level 1} is the hook function).
8249
8250}
8251
8252@LibEntry{debug.setlocal ([thread,] level, local, value)|
8253
8254This function assigns the value @id{value} to the local variable
8255with index @id{local} of the function at level @id{level} of the stack.
8256The function returns @nil if there is no local
8257variable with the given index,
8258and raises an error when called with a @id{level} out of range.
8259(You can call @id{getinfo} to check whether the level is valid.)
8260Otherwise, it returns the name of the local variable.
8261
8262See @Lid{debug.getlocal} for more information about
8263variable indices and names.
8264
8265}
8266
8267@LibEntry{debug.setmetatable (value, table)|
8268
8269Sets the metatable for the given @id{value} to the given @id{table}
8270(which can be @nil).
8271Returns @id{value}.
8272
8273}
8274
8275@LibEntry{debug.setupvalue (f, up, value)|
8276
8277This function assigns the value @id{value} to the upvalue
8278with index @id{up} of the function @id{f}.
8279The function returns @nil if there is no upvalue
8280with the given index.
8281Otherwise, it returns the name of the upvalue.
8282
8283}
8284
8285@LibEntry{debug.setuservalue (udata, value, n)|
8286
8287Sets the given @id{value} as
8288the @id{n}-th user value associated to the given @id{udata}.
8289@id{udata} must be a full userdata.
8290
8291Returns @id{udata},
8292or @nil if the userdata does not have that value.
8293
8294}
8295
8296@LibEntry{debug.traceback ([thread,] [message [, level]])|
8297
8298If @id{message} is present but is neither a string nor @nil,
8299this function returns @id{message} without further processing.
8300Otherwise,
8301it returns a string with a traceback of the call stack.
8302The optional @id{message} string is appended
8303at the beginning of the traceback.
8304An optional @id{level} number tells at which level
8305to start the traceback
8306(default is 1, the function calling @id{traceback}).
8307
8308}
8309
8310@LibEntry{debug.upvalueid (f, n)|
8311
8312Returns a unique identifier (as a light userdata)
8313for the upvalue numbered @id{n}
8314from the given function.
8315
8316These unique identifiers allow a program to check whether different
8317closures share upvalues.
8318Lua closures that share an upvalue
8319(that is, that access a same external local variable)
8320will return identical ids for those upvalue indices.
8321
8322}
8323
8324@LibEntry{debug.upvaluejoin (f1, n1, f2, n2)|
8325
8326Make the @id{n1}-th upvalue of the Lua closure @id{f1}
8327refer to the @id{n2}-th upvalue of the Lua closure @id{f2}.
8328
8329}
8330
8331}
8332
8333}
8334
8335
8336@C{-------------------------------------------------------------------------}
8337@sect1{lua-sa| @title{Lua Standalone}
8338
8339Although Lua has been designed as an extension language,
8340to be embedded in a host @N{C program},
8341it is also frequently used as a standalone language.
8342An interpreter for Lua as a standalone language,
8343called simply @id{lua},
8344is provided with the standard distribution.
8345The @x{standalone interpreter} includes
8346all standard libraries, including the debug library.
8347Its usage is:
8348@verbatim{
8349lua [options] [script [args]]
8350}
8351The options are:
8352@description{
8353@item{@T{-e @rep{stat}}| executes string @rep{stat};}
8354@item{@T{-l @rep{mod}}| @Q{requires} @rep{mod} and assigns the
8355 result to global @rep{mod};}
8356@item{@T{-i}| enters interactive mode after running @rep{script};}
8357@item{@T{-v}| prints version information;}
8358@item{@T{-E}| ignores environment variables;}
8359@item{@T{--}| stops handling options;}
8360@item{@T{-}| executes @id{stdin} as a file and stops handling options.}
8361}
8362After handling its options, @id{lua} runs the given @emph{script}.
8363When called without arguments,
8364@id{lua} behaves as @T{lua -v -i}
8365when the standard input (@id{stdin}) is a terminal,
8366and as @T{lua -} otherwise.
8367
8368When called without option @T{-E},
8369the interpreter checks for an environment variable @defid{LUA_INIT_5_4}
8370(or @defid{LUA_INIT} if the versioned name is not defined)
8371before running any argument.
8372If the variable content has the format @T{@At@rep{filename}},
8373then @id{lua} executes the file.
8374Otherwise, @id{lua} executes the string itself.
8375
8376When called with option @T{-E},
8377besides ignoring @id{LUA_INIT},
8378Lua also ignores
8379the values of @id{LUA_PATH} and @id{LUA_CPATH},
8380setting the values of
8381@Lid{package.path} and @Lid{package.cpath}
8382with the default paths defined in @id{luaconf.h}.
8383
8384All options are handled in order, except @T{-i} and @T{-E}.
8385For instance, an invocation like
8386@verbatim{
8387$ lua -e'a=1' -e 'print(a)' script.lua
8388}
8389will first set @id{a} to 1, then print the value of @id{a},
8390and finally run the file @id{script.lua} with no arguments.
8391(Here @T{$} is the shell prompt. Your prompt may be different.)
8392
8393Before running any code,
8394@id{lua} collects all command-line arguments
8395in a global table called @id{arg}.
8396The script name goes to index 0,
8397the first argument after the script name goes to index 1,
8398and so on.
8399Any arguments before the script name
8400(that is, the interpreter name plus its options)
8401go to negative indices.
8402For instance, in the call
8403@verbatim{
8404$ lua -la b.lua t1 t2
8405}
8406the table is like this:
8407@verbatim{
8408arg = { [-2] = "lua", [-1] = "-la",
8409 [0] = "b.lua",
8410 [1] = "t1", [2] = "t2" }
8411}
8412If there is no script in the call,
8413the interpreter name goes to index 0,
8414followed by the other arguments.
8415For instance, the call
8416@verbatim{
8417$ lua -e "print(arg[1])"
8418}
8419will print @St{-e}.
8420If there is a script,
8421the script is called with parameters
8422@T{arg[1]}, @Cdots, @T{arg[#arg]}.
8423(Like all chunks in Lua,
8424the script is compiled as a vararg function.)
8425
8426In interactive mode,
8427Lua repeatedly prompts and waits for a line.
8428After reading a line,
8429Lua first try to interpret the line as an expression.
8430If it succeeds, it prints its value.
8431Otherwise, it interprets the line as a statement.
8432If you write an incomplete statement,
8433the interpreter waits for its completion
8434by issuing a different prompt.
8435
8436If the global variable @defid{_PROMPT} contains a string,
8437then its value is used as the prompt.
8438Similarly, if the global variable @defid{_PROMPT2} contains a string,
8439its value is used as the secondary prompt
8440(issued during incomplete statements).
8441
8442In case of unprotected errors in the script,
8443the interpreter reports the error to the standard error stream.
8444If the error object is not a string but
8445has a metamethod @idx{__tostring},
8446the interpreter calls this metamethod to produce the final message.
8447Otherwise, the interpreter converts the error object to a string
8448and adds a stack traceback to it.
8449
8450When finishing normally,
8451the interpreter closes its main Lua state
8452@seeF{lua_close}.
8453The script can avoid this step by
8454calling @Lid{os.exit} to terminate.
8455
8456To allow the use of Lua as a
8457script interpreter in Unix systems,
8458the standalone interpreter skips
8459the first line of a chunk if it starts with @T{#}.
8460Therefore, Lua scripts can be made into executable programs
8461by using @T{chmod +x} and @N{the @T{#!}} form,
8462as in
8463@verbatim{
8464#!/usr/local/bin/lua
8465}
8466(Of course,
8467the location of the Lua interpreter may be different in your machine.
8468If @id{lua} is in your @id{PATH},
8469then
8470@verbatim{
8471#!/usr/bin/env lua
8472}
8473is a more portable solution.)
8474
8475}
8476
8477
8478@sect1{incompat| @title{Incompatibilities with the Previous Version}
8479
8480Here we list the incompatibilities that you may find when moving a program
8481from @N{Lua 5.3} to @N{Lua 5.4}.
8482You can avoid some incompatibilities by compiling Lua with
8483appropriate options (see file @id{luaconf.h}).
8484However,
8485all these compatibility options will be removed in the future.
8486
8487Lua versions can always change the C API in ways that
8488do not imply source-code changes in a program,
8489such as the numeric values for constants
8490or the implementation of functions as macros.
8491Therefore,
8492you should not assume that binaries are compatible between
8493different Lua versions.
8494Always recompile clients of the Lua API when
8495using a new version.
8496
8497Similarly, Lua versions can always change the internal representation
8498of precompiled chunks;
8499precompiled chunks are not compatible between different Lua versions.
8500
8501The standard paths in the official distribution may
8502change between versions.
8503
8504@sect2{@title{Changes in the Language}
8505@itemize{
8506
8507@item{
8508The coercion of strings to numbers in
8509arithmetic and bitwise operations
8510has been removed from the core language.
8511The string library does a similar job
8512for arithmetic (but not for bitwise) operations
8513using the string metamethods.
8514However, unlike in previous versions,
8515the new implementation preserves the implicit type of the numeral
8516in the string.
8517For instance, the result of @T{"1" + "2"} now is an integer,
8518not a float.
8519}
8520
8521}
8522
8523}
8524
8525@sect2{@title{Changes in the Libraries}
8526@itemize{
8527
8528@item{
8529The pseudo-random number generator used by the function @Lid{math.random}
8530now starts with a somewhat random seed.
8531Moreover, it uses a different algorithm.
8532}
8533
8534}
8535
8536}
8537
8538@sect2{@title{Changes in the API}
8539
8540@itemize{
8541
8542@item{
8543Full userdata now has an arbitrary number of associated user values.
8544Therefore, the functions @id{lua_newuserdata},
8545@id{lua_setuservalue}, and @id{lua_getuservalue} were
8546replaced by @Lid{lua_newuserdatauv},
8547@Lid{lua_setiuservalue}, and @Lid{lua_getiuservalue},
8548which have an extra argument.
8549
8550(For compatibility, the old names still work as macros assuming
8551one single user value.)
8552}
8553
8554@item{
8555The function @Lid{lua_resume} has an extra parameter.
8556This out parameter returns the number of values on
8557the top of the stack that were yielded or returned by the coroutine.
8558(In older versions,
8559those values were the entire stack.)
8560}
8561
8562@item{
8563The function @Lid{lua_version} returns the version number,
8564instead of an address of the version number.
8565(The Lua core should work correctly with libraries using their
8566own static copies of the same core,
8567so there is no need to check whether they are using the same
8568address space.)
8569}
8570
8571}
8572
8573}
8574
8575}
8576
8577
8578@C{[===============================================================}
8579
8580@sect1{BNF| @title{The Complete Syntax of Lua}
8581
8582Here is the complete syntax of Lua in extended BNF.
8583As usual in extended BNF,
8584@bnfNter{{A}} means 0 or more @bnfNter{A}s,
8585and @bnfNter{[A]} means an optional @bnfNter{A}.
8586(For operator precedences, see @See{prec};
8587for a description of the terminals
8588@bnfNter{Name}, @bnfNter{Numeral},
8589and @bnfNter{LiteralString}, see @See{lexical}.)
8590@index{grammar}
8591
8592@Produc{
8593
8594@producname{chunk}@producbody{block}
8595
8596@producname{block}@producbody{@bnfrep{stat} @bnfopt{retstat}}
8597
8598@producname{stat}@producbody{
8599 @bnfter{;}
8600@OrNL varlist @bnfter{=} explist
8601@OrNL functioncall
8602@OrNL label
8603@OrNL @Rw{break}
8604@OrNL @Rw{goto} Name
8605@OrNL @Rw{do} block @Rw{end}
8606@OrNL @Rw{while} exp @Rw{do} block @Rw{end}
8607@OrNL @Rw{repeat} block @Rw{until} exp
8608@OrNL @Rw{if} exp @Rw{then} block
8609 @bnfrep{@Rw{elseif} exp @Rw{then} block}
8610 @bnfopt{@Rw{else} block} @Rw{end}
8611@OrNL @Rw{for} @bnfNter{Name} @bnfter{=} exp @bnfter{,} exp @bnfopt{@bnfter{,} exp}
8612 @Rw{do} block @Rw{end}
8613@OrNL @Rw{for} namelist @Rw{in} explist @Rw{do} block @Rw{end}
8614@OrNL @Rw{function} funcname funcbody
8615@OrNL @Rw{local} @Rw{function} @bnfNter{Name} funcbody
8616@OrNL @Rw{local} namelist @bnfopt{@bnfter{=} explist}
8617}
8618
8619@producname{retstat}@producbody{@Rw{return}
8620 @bnfopt{explist} @bnfopt{@bnfter{;}}}
8621
8622@producname{label}@producbody{@bnfter{::} Name @bnfter{::}}
8623
8624@producname{funcname}@producbody{@bnfNter{Name} @bnfrep{@bnfter{.} @bnfNter{Name}}
8625 @bnfopt{@bnfter{:} @bnfNter{Name}}}
8626
8627@producname{varlist}@producbody{var @bnfrep{@bnfter{,} var}}
8628
8629@producname{var}@producbody{
8630 @bnfNter{Name}
8631@Or prefixexp @bnfter{[} exp @bnfter{]}
8632@Or prefixexp @bnfter{.} @bnfNter{Name}
8633}
8634
8635@producname{namelist}@producbody{@bnfNter{Name} @bnfrep{@bnfter{,} @bnfNter{Name}}}
8636
8637
8638@producname{explist}@producbody{exp @bnfrep{@bnfter{,} exp}}
8639
8640@producname{exp}@producbody{
8641 @Rw{nil}
8642@Or @Rw{false}
8643@Or @Rw{true}
8644@Or @bnfNter{Numeral}
8645@Or @bnfNter{LiteralString}
8646@Or @bnfter{...}
8647@Or functiondef
8648@OrNL prefixexp
8649@Or tableconstructor
8650@Or exp binop exp
8651@Or unop exp
8652}
8653
8654@producname{prefixexp}@producbody{var @Or functioncall @Or @bnfter{(} exp @bnfter{)}}
8655
8656@producname{functioncall}@producbody{
8657 prefixexp args
8658@Or prefixexp @bnfter{:} @bnfNter{Name} args
8659}
8660
8661@producname{args}@producbody{
8662 @bnfter{(} @bnfopt{explist} @bnfter{)}
8663@Or tableconstructor
8664@Or @bnfNter{LiteralString}
8665}
8666
8667@producname{functiondef}@producbody{@Rw{function} funcbody}
8668
8669@producname{funcbody}@producbody{@bnfter{(} @bnfopt{parlist} @bnfter{)} block @Rw{end}}
8670
8671@producname{parlist}@producbody{namelist @bnfopt{@bnfter{,} @bnfter{...}}
8672 @Or @bnfter{...}}
8673
8674@producname{tableconstructor}@producbody{@bnfter{@Open} @bnfopt{fieldlist} @bnfter{@Close}}
8675
8676@producname{fieldlist}@producbody{field @bnfrep{fieldsep field} @bnfopt{fieldsep}}
8677
8678@producname{field}@producbody{@bnfter{[} exp @bnfter{]} @bnfter{=} exp @Or @bnfNter{Name} @bnfter{=} exp @Or exp}
8679
8680@producname{fieldsep}@producbody{@bnfter{,} @Or @bnfter{;}}
8681
8682@producname{binop}@producbody{
8683 @bnfter{+} @Or @bnfter{-} @Or @bnfter{*} @Or @bnfter{/} @Or @bnfter{//}
8684 @Or @bnfter{^} @Or @bnfter{%}
8685 @OrNL
8686 @bnfter{&} @Or @bnfter{~} @Or @bnfter{|} @Or @bnfter{>>} @Or @bnfter{<<}
8687 @Or @bnfter{..}
8688 @OrNL
8689 @bnfter{<} @Or @bnfter{<=} @Or @bnfter{>} @Or @bnfter{>=}
8690 @Or @bnfter{==} @Or @bnfter{~=}
8691 @OrNL
8692 @Rw{and} @Or @Rw{or}}
8693
8694@producname{unop}@producbody{@bnfter{-} @Or @Rw{not} @Or @bnfter{#} @Or
8695 @bnfter{~}}
8696
8697}
8698
8699}
8700
8701@C{]===============================================================}
8702
8703}
8704@C{)]-------------------------------------------------------------------------}