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