diff options
37 files changed, 22260 insertions, 0 deletions
@@ -0,0 +1,7 @@ | |||
1 | cd testes | ||
2 | ulimit -S -s 2000 | ||
3 | if { ../lua all.lua; } then | ||
4 | echo -e "\n\n final OK!!!!\n\n" | ||
5 | else | ||
6 | echo -e "\n\n >>>> BUG!!!!\n\n" | ||
7 | fi | ||
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{)]-------------------------------------------------------------------------} | ||
diff --git a/testes/all.lua b/testes/all.lua new file mode 100755 index 00000000..cfe21603 --- /dev/null +++ b/testes/all.lua | |||
@@ -0,0 +1,294 @@ | |||
1 | #!../lua | ||
2 | -- $Id: all.lua,v 1.100 2018/03/09 14:23:48 roberto Exp $ | ||
3 | -- See Copyright Notice at the end of this file | ||
4 | |||
5 | |||
6 | local version = "Lua 5.4" | ||
7 | if _VERSION ~= version then | ||
8 | io.stderr:write("\nThis test suite is for ", version, ", not for ", _VERSION, | ||
9 | "\nExiting tests\n") | ||
10 | return | ||
11 | end | ||
12 | |||
13 | |||
14 | _G.ARG = arg -- save arg for other tests | ||
15 | |||
16 | |||
17 | -- next variables control the execution of some tests | ||
18 | -- true means no test (so an undefined variable does not skip a test) | ||
19 | -- defaults are for Linux; test everything. | ||
20 | -- Make true to avoid long or memory consuming tests | ||
21 | _soft = rawget(_G, "_soft") or false | ||
22 | -- Make true to avoid non-portable tests | ||
23 | _port = rawget(_G, "_port") or false | ||
24 | -- Make true to avoid messages about tests not performed | ||
25 | _nomsg = rawget(_G, "_nomsg") or false | ||
26 | |||
27 | |||
28 | local usertests = rawget(_G, "_U") | ||
29 | |||
30 | if usertests then | ||
31 | -- tests for sissies ;) Avoid problems | ||
32 | _soft = true | ||
33 | _port = true | ||
34 | _nomsg = true | ||
35 | end | ||
36 | |||
37 | -- tests should require debug when needed | ||
38 | debug = nil | ||
39 | |||
40 | require"bwcoercion" | ||
41 | |||
42 | |||
43 | if usertests then | ||
44 | T = nil -- no "internal" tests for user tests | ||
45 | else | ||
46 | T = rawget(_G, "T") -- avoid problems with 'strict' module | ||
47 | end | ||
48 | |||
49 | math.randomseed(0) | ||
50 | |||
51 | --[=[ | ||
52 | example of a long [comment], | ||
53 | [[spanning several [lines]]] | ||
54 | |||
55 | ]=] | ||
56 | |||
57 | print("current path:\n****" .. package.path .. "****\n") | ||
58 | |||
59 | |||
60 | local initclock = os.clock() | ||
61 | local lastclock = initclock | ||
62 | local walltime = os.time() | ||
63 | |||
64 | local collectgarbage = collectgarbage | ||
65 | |||
66 | do -- ( | ||
67 | |||
68 | -- track messages for tests not performed | ||
69 | local msgs = {} | ||
70 | function Message (m) | ||
71 | if not _nomsg then | ||
72 | print(m) | ||
73 | msgs[#msgs+1] = string.sub(m, 3, -3) | ||
74 | end | ||
75 | end | ||
76 | |||
77 | assert(os.setlocale"C") | ||
78 | |||
79 | local T,print,format,write,assert,type,unpack,floor = | ||
80 | T,print,string.format,io.write,assert,type,table.unpack,math.floor | ||
81 | |||
82 | -- use K for 1000 and M for 1000000 (not 2^10 -- 2^20) | ||
83 | local function F (m) | ||
84 | local function round (m) | ||
85 | m = m + 0.04999 | ||
86 | return format("%.1f", m) -- keep one decimal digit | ||
87 | end | ||
88 | if m < 1000 then return m | ||
89 | else | ||
90 | m = m / 1000 | ||
91 | if m < 1000 then return round(m).."K" | ||
92 | else | ||
93 | return round(m/1000).."M" | ||
94 | end | ||
95 | end | ||
96 | end | ||
97 | |||
98 | local showmem | ||
99 | if not T then | ||
100 | local max = 0 | ||
101 | showmem = function () | ||
102 | local m = collectgarbage("count") * 1024 | ||
103 | max = (m > max) and m or max | ||
104 | print(format(" ---- total memory: %s, max memory: %s ----\n", | ||
105 | F(m), F(max))) | ||
106 | end | ||
107 | else | ||
108 | showmem = function () | ||
109 | T.checkmemory() | ||
110 | local total, numblocks, maxmem = T.totalmem() | ||
111 | local count = collectgarbage("count") | ||
112 | print(format( | ||
113 | "\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n", | ||
114 | F(total), count, F(maxmem), numblocks)) | ||
115 | print(format("\t(strings: %d, tables: %d, functions: %d, ".. | ||
116 | "\n\tudata: %d, threads: %d)", | ||
117 | T.totalmem"string", T.totalmem"table", T.totalmem"function", | ||
118 | T.totalmem"userdata", T.totalmem"thread")) | ||
119 | end | ||
120 | end | ||
121 | |||
122 | |||
123 | -- | ||
124 | -- redefine dofile to run files through dump/undump | ||
125 | -- | ||
126 | local function report (n) print("\n***** FILE '"..n.."'*****") end | ||
127 | local olddofile = dofile | ||
128 | local dofile = function (n, strip) | ||
129 | showmem() | ||
130 | local c = os.clock() | ||
131 | print(string.format("time: %g (+%g)", c - initclock, c - lastclock)) | ||
132 | lastclock = c | ||
133 | report(n) | ||
134 | local f = assert(loadfile(n)) | ||
135 | local b = string.dump(f, strip) | ||
136 | f = assert(load(b)) | ||
137 | return f() | ||
138 | end | ||
139 | |||
140 | dofile('main.lua') | ||
141 | |||
142 | do | ||
143 | local next, setmetatable, stderr = next, setmetatable, io.stderr | ||
144 | -- track collections | ||
145 | local mt = {} | ||
146 | -- each time a table is collected, remark it for finalization | ||
147 | -- on next cycle | ||
148 | mt.__gc = function (o) | ||
149 | stderr:write'.' -- mark progress | ||
150 | local n = setmetatable(o, mt) -- remark it | ||
151 | end | ||
152 | local n = setmetatable({}, mt) -- create object | ||
153 | end | ||
154 | |||
155 | report"gc.lua" | ||
156 | local f = assert(loadfile('gc.lua')) | ||
157 | f() | ||
158 | |||
159 | dofile('db.lua') | ||
160 | assert(dofile('calls.lua') == deep and deep) | ||
161 | olddofile('strings.lua') | ||
162 | olddofile('literals.lua') | ||
163 | dofile('tpack.lua') | ||
164 | assert(dofile('attrib.lua') == 27) | ||
165 | |||
166 | assert(dofile('locals.lua') == 5) | ||
167 | dofile('constructs.lua') | ||
168 | dofile('code.lua', true) | ||
169 | if not _G._soft then | ||
170 | report('big.lua') | ||
171 | local f = coroutine.wrap(assert(loadfile('big.lua'))) | ||
172 | assert(f() == 'b') | ||
173 | assert(f() == 'a') | ||
174 | end | ||
175 | dofile('nextvar.lua') | ||
176 | dofile('pm.lua') | ||
177 | dofile('utf8.lua') | ||
178 | dofile('api.lua') | ||
179 | assert(dofile('events.lua') == 12) | ||
180 | dofile('vararg.lua') | ||
181 | dofile('closure.lua') | ||
182 | dofile('coroutine.lua') | ||
183 | dofile('goto.lua', true) | ||
184 | dofile('errors.lua') | ||
185 | dofile('math.lua') | ||
186 | dofile('sort.lua', true) | ||
187 | dofile('bitwise.lua') | ||
188 | assert(dofile('verybig.lua', true) == 10); collectgarbage() | ||
189 | dofile('files.lua') | ||
190 | |||
191 | if #msgs > 0 then | ||
192 | print("\ntests not performed:") | ||
193 | for i=1,#msgs do | ||
194 | print(msgs[i]) | ||
195 | end | ||
196 | print() | ||
197 | end | ||
198 | |||
199 | -- no test module should define 'debug' | ||
200 | assert(debug == nil) | ||
201 | |||
202 | local debug = require "debug" | ||
203 | |||
204 | print(string.format("%d-bit integers, %d-bit floats", | ||
205 | string.packsize("j") * 8, string.packsize("n") * 8)) | ||
206 | |||
207 | debug.sethook(function (a) assert(type(a) == 'string') end, "cr") | ||
208 | |||
209 | -- to survive outside block | ||
210 | _G.showmem = showmem | ||
211 | |||
212 | end --) | ||
213 | |||
214 | local _G, showmem, print, format, clock, time, difftime, assert, open = | ||
215 | _G, showmem, print, string.format, os.clock, os.time, os.difftime, | ||
216 | assert, io.open | ||
217 | |||
218 | -- file with time of last performed test | ||
219 | local fname = T and "time-debug.txt" or "time.txt" | ||
220 | local lasttime | ||
221 | |||
222 | if not usertests then | ||
223 | -- open file with time of last performed test | ||
224 | local f = io.open(fname) | ||
225 | if f then | ||
226 | lasttime = assert(tonumber(f:read'a')) | ||
227 | f:close(); | ||
228 | else -- no such file; assume it is recording time for first time | ||
229 | lasttime = nil | ||
230 | end | ||
231 | end | ||
232 | |||
233 | -- erase (almost) all globals | ||
234 | print('cleaning all!!!!') | ||
235 | for n in pairs(_G) do | ||
236 | if not ({___Glob = 1, tostring = 1})[n] then | ||
237 | _G[n] = undef | ||
238 | end | ||
239 | end | ||
240 | |||
241 | |||
242 | collectgarbage() | ||
243 | collectgarbage() | ||
244 | collectgarbage() | ||
245 | collectgarbage() | ||
246 | collectgarbage() | ||
247 | collectgarbage();showmem() | ||
248 | |||
249 | local clocktime = clock() - initclock | ||
250 | walltime = difftime(time(), walltime) | ||
251 | |||
252 | print(format("\n\ntotal time: %.2fs (wall time: %gs)\n", clocktime, walltime)) | ||
253 | |||
254 | if not usertests then | ||
255 | lasttime = lasttime or clocktime -- if no last time, ignore difference | ||
256 | -- check whether current test time differs more than 5% from last time | ||
257 | local diff = (clocktime - lasttime) / lasttime | ||
258 | local tolerance = 0.05 -- 5% | ||
259 | if (diff >= tolerance or diff <= -tolerance) then | ||
260 | print(format("WARNING: time difference from previous test: %+.1f%%", | ||
261 | diff * 100)) | ||
262 | end | ||
263 | assert(open(fname, "w")):write(clocktime):close() | ||
264 | end | ||
265 | |||
266 | print("final OK !!!") | ||
267 | |||
268 | |||
269 | |||
270 | --[[ | ||
271 | ***************************************************************************** | ||
272 | * Copyright (C) 1994-2016 Lua.org, PUC-Rio. | ||
273 | * | ||
274 | * Permission is hereby granted, free of charge, to any person obtaining | ||
275 | * a copy of this software and associated documentation files (the | ||
276 | * "Software"), to deal in the Software without restriction, including | ||
277 | * without limitation the rights to use, copy, modify, merge, publish, | ||
278 | * distribute, sublicense, and/or sell copies of the Software, and to | ||
279 | * permit persons to whom the Software is furnished to do so, subject to | ||
280 | * the following conditions: | ||
281 | * | ||
282 | * The above copyright notice and this permission notice shall be | ||
283 | * included in all copies or substantial portions of the Software. | ||
284 | * | ||
285 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
286 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
287 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
288 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | ||
289 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | ||
290 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | ||
291 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
292 | ***************************************************************************** | ||
293 | ]] | ||
294 | |||
diff --git a/testes/api.lua b/testes/api.lua new file mode 100644 index 00000000..836a6070 --- /dev/null +++ b/testes/api.lua | |||
@@ -0,0 +1,1264 @@ | |||
1 | -- $Id: api.lua,v 1.155 2018/03/09 14:23:48 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | if T==nil then | ||
5 | (Message or print)('\n >>> testC not active: skipping API tests <<<\n') | ||
6 | return | ||
7 | end | ||
8 | |||
9 | local debug = require "debug" | ||
10 | |||
11 | local pack = table.pack | ||
12 | |||
13 | |||
14 | function tcheck (t1, t2) | ||
15 | assert(t1.n == (t2.n or #t2) + 1) | ||
16 | for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end | ||
17 | end | ||
18 | |||
19 | |||
20 | local function checkerr (msg, f, ...) | ||
21 | local stat, err = pcall(f, ...) | ||
22 | assert(not stat and string.find(err, msg)) | ||
23 | end | ||
24 | |||
25 | |||
26 | print('testing C API') | ||
27 | |||
28 | a = T.testC("pushvalue R; return 1") | ||
29 | assert(a == debug.getregistry()) | ||
30 | |||
31 | |||
32 | -- absindex | ||
33 | assert(T.testC("settop 10; absindex -1; return 1") == 10) | ||
34 | assert(T.testC("settop 5; absindex -5; return 1") == 1) | ||
35 | assert(T.testC("settop 10; absindex 1; return 1") == 1) | ||
36 | assert(T.testC("settop 10; absindex R; return 1") < -10) | ||
37 | |||
38 | -- testing alignment | ||
39 | a = T.d2s(12458954321123.0) | ||
40 | assert(a == string.pack("d", 12458954321123.0)) | ||
41 | assert(T.s2d(a) == 12458954321123.0) | ||
42 | |||
43 | a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2") | ||
44 | assert(a == 2 and b == 3 and not c) | ||
45 | |||
46 | f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2") | ||
47 | a,b,c = f() | ||
48 | assert(a == 2 and b == 3 and not c) | ||
49 | |||
50 | -- test that all trues are equal | ||
51 | a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3") | ||
52 | assert(a == b and a == true and c == false) | ||
53 | a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\ | ||
54 | tobool -3; tobool -3; tobool -3; return 3" | ||
55 | assert(a==false and b==true and c==false) | ||
56 | |||
57 | |||
58 | a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40) | ||
59 | assert(a == 40 and b == 5 and not c) | ||
60 | |||
61 | t = pack(T.testC("settop 5; return *", 2, 3)) | ||
62 | tcheck(t, {n=4,2,3}) | ||
63 | |||
64 | t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23)) | ||
65 | assert(t.n == 10 and t[1] == nil and t[10] == nil) | ||
66 | |||
67 | t = pack(T.testC("remove -2; return *", 2, 3, 4)) | ||
68 | tcheck(t, {n=2,2,4}) | ||
69 | |||
70 | t = pack(T.testC("insert -1; return *", 2, 3)) | ||
71 | tcheck(t, {n=2,2,3}) | ||
72 | |||
73 | t = pack(T.testC("insert 3; return *", 2, 3, 4, 5)) | ||
74 | tcheck(t, {n=4,2,5,3,4}) | ||
75 | |||
76 | t = pack(T.testC("replace 2; return *", 2, 3, 4, 5)) | ||
77 | tcheck(t, {n=3,5,3,4}) | ||
78 | |||
79 | t = pack(T.testC("replace -2; return *", 2, 3, 4, 5)) | ||
80 | tcheck(t, {n=3,2,3,5}) | ||
81 | |||
82 | t = pack(T.testC("remove 3; return *", 2, 3, 4, 5)) | ||
83 | tcheck(t, {n=3,2,4,5}) | ||
84 | |||
85 | t = pack(T.testC("copy 3 4; return *", 2, 3, 4, 5)) | ||
86 | tcheck(t, {n=4,2,3,3,5}) | ||
87 | |||
88 | t = pack(T.testC("copy -3 -1; return *", 2, 3, 4, 5)) | ||
89 | tcheck(t, {n=4,2,3,4,3}) | ||
90 | |||
91 | do -- testing 'rotate' | ||
92 | local t = {10, 20, 30, 40, 50, 60} | ||
93 | for i = -6, 6 do | ||
94 | local s = string.format("rotate 2 %d; return 7", i) | ||
95 | local t1 = pack(T.testC(s, 10, 20, 30, 40, 50, 60)) | ||
96 | tcheck(t1, t) | ||
97 | table.insert(t, 1, table.remove(t)) | ||
98 | end | ||
99 | |||
100 | t = pack(T.testC("rotate -2 1; return *", 10, 20, 30, 40)) | ||
101 | tcheck(t, {10, 20, 40, 30}) | ||
102 | t = pack(T.testC("rotate -2 -1; return *", 10, 20, 30, 40)) | ||
103 | tcheck(t, {10, 20, 40, 30}) | ||
104 | |||
105 | -- some corner cases | ||
106 | t = pack(T.testC("rotate -1 0; return *", 10, 20, 30, 40)) | ||
107 | tcheck(t, {10, 20, 30, 40}) | ||
108 | t = pack(T.testC("rotate -1 1; return *", 10, 20, 30, 40)) | ||
109 | tcheck(t, {10, 20, 30, 40}) | ||
110 | t = pack(T.testC("rotate 5 -1; return *", 10, 20, 30, 40)) | ||
111 | tcheck(t, {10, 20, 30, 40}) | ||
112 | end | ||
113 | |||
114 | -- testing message handlers | ||
115 | do | ||
116 | local f = T.makeCfunc[[ | ||
117 | getglobal error | ||
118 | pushstring bola | ||
119 | pcall 1 1 1 # call 'error' with given handler | ||
120 | pushstatus | ||
121 | return 2 # return error message and status | ||
122 | ]] | ||
123 | |||
124 | local msg, st = f(string.upper) -- function handler | ||
125 | assert(st == "ERRRUN" and msg == "BOLA") | ||
126 | local msg, st = f(string.len) -- function handler | ||
127 | assert(st == "ERRRUN" and msg == 4) | ||
128 | |||
129 | end | ||
130 | |||
131 | t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \ | ||
132 | insert 2; pushvalue 1; remove 1; insert 1; \ | ||
133 | insert -2; pushvalue -2; remove -3; return *", | ||
134 | 2, 3, 4, 5, 10, 40, 90)) | ||
135 | tcheck(t, {n=7,2,3,4,5,10,40,90}) | ||
136 | |||
137 | t = pack(T.testC("concat 5; return *", "alo", 2, 3, "joao", 12)) | ||
138 | tcheck(t, {n=1,"alo23joao12"}) | ||
139 | |||
140 | -- testing MULTRET | ||
141 | t = pack(T.testC("call 2,-1; return *", | ||
142 | function (a,b) return 1,2,3,4,a,b end, "alo", "joao")) | ||
143 | tcheck(t, {n=6,1,2,3,4,"alo", "joao"}) | ||
144 | |||
145 | do -- test returning more results than fit in the caller stack | ||
146 | local a = {} | ||
147 | for i=1,1000 do a[i] = true end; a[999] = 10 | ||
148 | local b = T.testC([[pcall 1 -1 0; pop 1; tostring -1; return 1]], | ||
149 | table.unpack, a) | ||
150 | assert(b == "10") | ||
151 | end | ||
152 | |||
153 | |||
154 | -- testing globals | ||
155 | _G.a = 14; _G.b = "a31" | ||
156 | local a = {T.testC[[ | ||
157 | getglobal a; | ||
158 | getglobal b; | ||
159 | getglobal b; | ||
160 | setglobal a; | ||
161 | return * | ||
162 | ]]} | ||
163 | assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.a == "a31") | ||
164 | |||
165 | |||
166 | -- testing arith | ||
167 | assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5) | ||
168 | assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10) | ||
169 | assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200) | ||
170 | assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000) | ||
171 | assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5) | ||
172 | assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10) | ||
173 | assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200) | ||
174 | assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000) | ||
175 | assert(T.testC("arith /; return 1", 2, 0) == 10.0/0) | ||
176 | a = T.testC("pushnum 10; pushint 3; arith \\; return 1") | ||
177 | assert(a == 3.0 and math.type(a) == "float") | ||
178 | a = T.testC("pushint 10; pushint 3; arith \\; return 1") | ||
179 | assert(a == 3 and math.type(a) == "integer") | ||
180 | a = assert(T.testC("pushint 10; pushint 3; arith +; return 1")) | ||
181 | assert(a == 13 and math.type(a) == "integer") | ||
182 | a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1")) | ||
183 | assert(a == 13 and math.type(a) == "float") | ||
184 | a,b,c = T.testC([[pushnum 1; | ||
185 | pushstring 10; arith _; | ||
186 | pushstring 5; return 3]]) | ||
187 | assert(a == 1 and b == -10 and c == "5") | ||
188 | mt = {__add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end, | ||
189 | __mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end, | ||
190 | __unm = function (a) return setmetatable({a[1]* 2}, mt) end} | ||
191 | a,b,c = setmetatable({4}, mt), | ||
192 | setmetatable({8}, mt), | ||
193 | setmetatable({-3}, mt) | ||
194 | x,y,z = T.testC("arith +; return 2", 10, a, b) | ||
195 | assert(x == 10 and y[1] == 12 and z == nil) | ||
196 | assert(T.testC("arith %; return 1", a, c)[1] == 4%-3) | ||
197 | assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] == | ||
198 | 8 % (4 + (-3)*2)) | ||
199 | |||
200 | -- errors in arithmetic | ||
201 | checkerr("divide by zero", T.testC, "arith \\", 10, 0) | ||
202 | checkerr("%%0", T.testC, "arith %", 10, 0) | ||
203 | |||
204 | |||
205 | -- testing lessthan and lessequal | ||
206 | assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2)) | ||
207 | assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2)) | ||
208 | assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2)) | ||
209 | assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2)) | ||
210 | assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2)) | ||
211 | assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2")) | ||
212 | assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2")) | ||
213 | |||
214 | -- non-valid indices produce false | ||
215 | assert(not T.testC("compare LT 1 4, return 1")) | ||
216 | assert(not T.testC("compare LE 9 1, return 1")) | ||
217 | assert(not T.testC("compare EQ 9 9, return 1")) | ||
218 | |||
219 | local b = {__lt = function (a,b) return a[1] < b[1] end} | ||
220 | local a1,a3,a4 = setmetatable({1}, b), | ||
221 | setmetatable({3}, b), | ||
222 | setmetatable({4}, b) | ||
223 | assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2)) | ||
224 | assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2)) | ||
225 | assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2)) | ||
226 | a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20) | ||
227 | assert(a == 20 and b == false) | ||
228 | a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20) | ||
229 | assert(a == 20 and b == false) | ||
230 | a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20) | ||
231 | assert(a == 20 and b == true) | ||
232 | |||
233 | -- testing length | ||
234 | local t = setmetatable({x = 20}, {__len = function (t) return t.x end}) | ||
235 | a,b,c = T.testC([[ | ||
236 | len 2; | ||
237 | Llen 2; | ||
238 | objsize 2; | ||
239 | return 3 | ||
240 | ]], t) | ||
241 | assert(a == 20 and b == 20 and c == 0) | ||
242 | |||
243 | t.x = "234"; t[1] = 20 | ||
244 | a,b,c = T.testC([[ | ||
245 | len 2; | ||
246 | Llen 2; | ||
247 | objsize 2; | ||
248 | return 3 | ||
249 | ]], t) | ||
250 | assert(a == "234" and b == 234 and c == 1) | ||
251 | |||
252 | t.x = print; t[1] = 20 | ||
253 | a,c = T.testC([[ | ||
254 | len 2; | ||
255 | objsize 2; | ||
256 | return 2 | ||
257 | ]], t) | ||
258 | assert(a == print and c == 1) | ||
259 | |||
260 | |||
261 | -- testing __concat | ||
262 | |||
263 | a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end}) | ||
264 | x,y = T.testC([[ | ||
265 | pushnum 5 | ||
266 | pushvalue 2; | ||
267 | pushvalue 2; | ||
268 | concat 2; | ||
269 | pushvalue -2; | ||
270 | return 2; | ||
271 | ]], a, a) | ||
272 | assert(x == a..a and y == 5) | ||
273 | |||
274 | -- concat with 0 elements | ||
275 | assert(T.testC("concat 0; return 1") == "") | ||
276 | |||
277 | -- concat with 1 element | ||
278 | assert(T.testC("concat 1; return 1", "xuxu") == "xuxu") | ||
279 | |||
280 | |||
281 | |||
282 | -- testing lua_is | ||
283 | |||
284 | function B(x) return x and 1 or 0 end | ||
285 | |||
286 | function count (x, n) | ||
287 | n = n or 2 | ||
288 | local prog = [[ | ||
289 | isnumber %d; | ||
290 | isstring %d; | ||
291 | isfunction %d; | ||
292 | iscfunction %d; | ||
293 | istable %d; | ||
294 | isuserdata %d; | ||
295 | isnil %d; | ||
296 | isnull %d; | ||
297 | return 8 | ||
298 | ]] | ||
299 | prog = string.format(prog, n, n, n, n, n, n, n, n) | ||
300 | local a,b,c,d,e,f,g,h = T.testC(prog, x) | ||
301 | return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h)) | ||
302 | end | ||
303 | |||
304 | assert(count(3) == 2) | ||
305 | assert(count('alo') == 1) | ||
306 | assert(count('32') == 2) | ||
307 | assert(count({}) == 1) | ||
308 | assert(count(print) == 2) | ||
309 | assert(count(function () end) == 1) | ||
310 | assert(count(nil) == 1) | ||
311 | assert(count(io.stdin) == 1) | ||
312 | assert(count(nil, 15) == 100) | ||
313 | |||
314 | |||
315 | -- testing lua_to... | ||
316 | |||
317 | function to (s, x, n) | ||
318 | n = n or 2 | ||
319 | return T.testC(string.format("%s %d; return 1", s, n), x) | ||
320 | end | ||
321 | |||
322 | local hfunc = string.gmatch("", "") -- a "heavy C function" (with upvalues) | ||
323 | assert(debug.getupvalue(hfunc, 1)) | ||
324 | assert(to("tostring", {}) == nil) | ||
325 | assert(to("tostring", "alo") == "alo") | ||
326 | assert(to("tostring", 12) == "12") | ||
327 | assert(to("tostring", 12, 3) == nil) | ||
328 | assert(to("objsize", {}) == 0) | ||
329 | assert(to("objsize", {1,2,3}) == 3) | ||
330 | assert(to("objsize", "alo\0\0a") == 6) | ||
331 | assert(to("objsize", T.newuserdata(0)) == 0) | ||
332 | assert(to("objsize", T.newuserdata(101)) == 101) | ||
333 | assert(to("objsize", 124) == 0) | ||
334 | assert(to("objsize", true) == 0) | ||
335 | assert(to("tonumber", {}) == 0) | ||
336 | assert(to("tonumber", "12") == 12) | ||
337 | assert(to("tonumber", "s2") == 0) | ||
338 | assert(to("tonumber", 1, 20) == 0) | ||
339 | assert(to("topointer", 10) == 0) | ||
340 | assert(to("topointer", true) == 0) | ||
341 | assert(to("topointer", T.pushuserdata(20)) == 20) | ||
342 | assert(to("topointer", io.read) ~= 0) -- light C function | ||
343 | assert(to("topointer", hfunc) ~= 0) -- "heavy" C function | ||
344 | assert(to("topointer", function () end) ~= 0) -- Lua function | ||
345 | assert(to("topointer", io.stdin) ~= 0) -- full userdata | ||
346 | assert(to("func2num", 20) == 0) | ||
347 | assert(to("func2num", T.pushuserdata(10)) == 0) | ||
348 | assert(to("func2num", io.read) ~= 0) -- light C function | ||
349 | assert(to("func2num", hfunc) ~= 0) -- "heavy" C function (with upvalue) | ||
350 | a = to("tocfunction", math.deg) | ||
351 | assert(a(3) == math.deg(3) and a == math.deg) | ||
352 | |||
353 | |||
354 | print("testing panic function") | ||
355 | do | ||
356 | -- trivial error | ||
357 | assert(T.checkpanic("pushstring hi; error") == "hi") | ||
358 | |||
359 | -- using the stack inside panic | ||
360 | assert(T.checkpanic("pushstring hi; error;", | ||
361 | [[checkstack 5 XX | ||
362 | pushstring ' alo' | ||
363 | pushstring ' mundo' | ||
364 | concat 3]]) == "hi alo mundo") | ||
365 | |||
366 | -- "argerror" without frames | ||
367 | assert(T.checkpanic("loadstring 4") == | ||
368 | "bad argument #4 (string expected, got no value)") | ||
369 | |||
370 | |||
371 | -- memory error | ||
372 | T.totalmem(T.totalmem()+10000) -- set low memory limit (+10k) | ||
373 | assert(T.checkpanic("newuserdata 20000") == "not enough memory") | ||
374 | T.totalmem(0) -- restore high limit | ||
375 | |||
376 | -- stack error | ||
377 | if not _soft then | ||
378 | local msg = T.checkpanic[[ | ||
379 | pushstring "function f() f() end" | ||
380 | loadstring -1; call 0 0 | ||
381 | getglobal f; call 0 0 | ||
382 | ]] | ||
383 | assert(string.find(msg, "stack overflow")) | ||
384 | end | ||
385 | |||
386 | end | ||
387 | |||
388 | -- testing deep C stack | ||
389 | if not _soft then | ||
390 | print("testing stack overflow") | ||
391 | collectgarbage("stop") | ||
392 | checkerr("XXXX", T.testC, "checkstack 1000023 XXXX") -- too deep | ||
393 | -- too deep (with no message) | ||
394 | checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''") | ||
395 | local s = string.rep("pushnil;checkstack 1 XX;", 1000000) | ||
396 | checkerr("overflow", T.testC, s) | ||
397 | collectgarbage("restart") | ||
398 | print'+' | ||
399 | end | ||
400 | |||
401 | local lim = _soft and 500 or 12000 | ||
402 | local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"} | ||
403 | for i = 1,lim do | ||
404 | prog[#prog + 1] = "pushnum " .. i | ||
405 | prog[#prog + 1] = "pushnum " .. i * 10 | ||
406 | end | ||
407 | |||
408 | prog[#prog + 1] = "rawgeti R 2" -- get global table in registry | ||
409 | prog[#prog + 1] = "insert " .. -(2*lim + 2) | ||
410 | |||
411 | for i = 1,lim do | ||
412 | prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1) | ||
413 | end | ||
414 | |||
415 | prog[#prog + 1] = "return 2" | ||
416 | |||
417 | prog = table.concat(prog, ";") | ||
418 | local g, t = T.testC(prog) | ||
419 | assert(g == _G) | ||
420 | for i = 1,lim do assert(t[i] == i*10); t[i] = undef end | ||
421 | assert(next(t) == nil) | ||
422 | prog, g, t = nil | ||
423 | |||
424 | -- testing errors | ||
425 | |||
426 | a = T.testC([[ | ||
427 | loadstring 2; pcall 0 1 0; | ||
428 | pushvalue 3; insert -2; pcall 1 1 0; | ||
429 | pcall 0 0 0; | ||
430 | return 1 | ||
431 | ]], "x=150", function (a) assert(a==nil); return 3 end) | ||
432 | |||
433 | assert(type(a) == 'string' and x == 150) | ||
434 | |||
435 | function check3(p, ...) | ||
436 | local arg = {...} | ||
437 | assert(#arg == 3) | ||
438 | assert(string.find(arg[3], p)) | ||
439 | end | ||
440 | check3(":1:", T.testC("loadstring 2; return *", "x=")) | ||
441 | check3("%.", T.testC("loadfile 2; return *", ".")) | ||
442 | check3("xxxx", T.testC("loadfile 2; return *", "xxxx")) | ||
443 | |||
444 | -- test errors in non protected threads | ||
445 | function checkerrnopro (code, msg) | ||
446 | local th = coroutine.create(function () end) -- create new thread | ||
447 | local stt, err = pcall(T.testC, th, code) -- run code there | ||
448 | assert(not stt and string.find(err, msg)) | ||
449 | end | ||
450 | |||
451 | if not _soft then | ||
452 | checkerrnopro("pushnum 3; call 0 0", "attempt to call") | ||
453 | print"testing stack overflow in unprotected thread" | ||
454 | function f () f() end | ||
455 | checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow") | ||
456 | end | ||
457 | print"+" | ||
458 | |||
459 | |||
460 | -- testing table access | ||
461 | |||
462 | do -- getp/setp | ||
463 | local a = {} | ||
464 | T.testC("rawsetp 2 1", a, 20) | ||
465 | assert(a[T.pushuserdata(1)] == 20) | ||
466 | assert(T.testC("rawgetp 2 1; return 1", a) == 20) | ||
467 | end | ||
468 | |||
469 | a = {x=0, y=12} | ||
470 | x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2", | ||
471 | a, 3, "y", 4, "x") | ||
472 | assert(x == 0 and y == 12) | ||
473 | T.testC("settable -5", a, 3, 4, "x", 15) | ||
474 | assert(a.x == 15) | ||
475 | a[a] = print | ||
476 | x = T.testC("gettable 2; return 1", a) -- table and key are the same object! | ||
477 | assert(x == print) | ||
478 | T.testC("settable 2", a, "x") -- table and key are the same object! | ||
479 | assert(a[a] == "x") | ||
480 | |||
481 | b = setmetatable({p = a}, {}) | ||
482 | getmetatable(b).__index = function (t, i) return t.p[i] end | ||
483 | k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x") | ||
484 | assert(x == 15 and k == 35) | ||
485 | k = T.testC("getfield 2 y, return 1", b) | ||
486 | assert(k == 12) | ||
487 | getmetatable(b).__index = function (t, i) return a[i] end | ||
488 | getmetatable(b).__newindex = function (t, i,v ) a[i] = v end | ||
489 | y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b) | ||
490 | assert(y == 12) | ||
491 | k = T.testC("settable -5, return 1", b, 3, 4, "x", 16) | ||
492 | assert(a.x == 16 and k == 4) | ||
493 | a[b] = 'xuxu' | ||
494 | y = T.testC("gettable 2, return 1", b) | ||
495 | assert(y == 'xuxu') | ||
496 | T.testC("settable 2", b, 19) | ||
497 | assert(a[b] == 19) | ||
498 | |||
499 | -- | ||
500 | do -- testing getfield/setfield with long keys | ||
501 | local t = {_012345678901234567890123456789012345678901234567890123456789 = 32} | ||
502 | local a = T.testC([[ | ||
503 | getfield 2 _012345678901234567890123456789012345678901234567890123456789 | ||
504 | return 1 | ||
505 | ]], t) | ||
506 | assert(a == 32) | ||
507 | local a = T.testC([[ | ||
508 | pushnum 33 | ||
509 | setglobal _012345678901234567890123456789012345678901234567890123456789 | ||
510 | ]]) | ||
511 | assert(_012345678901234567890123456789012345678901234567890123456789 == 33) | ||
512 | _012345678901234567890123456789012345678901234567890123456789 = nil | ||
513 | end | ||
514 | |||
515 | -- testing next | ||
516 | a = {} | ||
517 | t = pack(T.testC("next; return *", a, nil)) | ||
518 | tcheck(t, {n=1,a}) | ||
519 | a = {a=3} | ||
520 | t = pack(T.testC("next; return *", a, nil)) | ||
521 | tcheck(t, {n=3,a,'a',3}) | ||
522 | t = pack(T.testC("next; pop 1; next; return *", a, nil)) | ||
523 | tcheck(t, {n=1,a}) | ||
524 | |||
525 | |||
526 | |||
527 | -- testing upvalues | ||
528 | |||
529 | do | ||
530 | local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]] | ||
531 | t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]]) | ||
532 | assert(b == 10 and c == 20 and type(t) == 'table') | ||
533 | a, b = A([[tostring U3; tonumber U4; return 2]]) | ||
534 | assert(a == nil and b == 0) | ||
535 | A([[pushnum 100; pushnum 200; replace U2; replace U1]]) | ||
536 | b, c = A([[pushvalue U1; pushvalue U2; return 2]]) | ||
537 | assert(b == 100 and c == 200) | ||
538 | A([[replace U2; replace U1]], {x=1}, {x=2}) | ||
539 | b, c = A([[pushvalue U1; pushvalue U2; return 2]]) | ||
540 | assert(b.x == 1 and c.x == 2) | ||
541 | T.checkmemory() | ||
542 | end | ||
543 | |||
544 | |||
545 | -- testing absent upvalues from C-function pointers | ||
546 | assert(T.testC[[isnull U1; return 1]] == true) | ||
547 | assert(T.testC[[isnull U100; return 1]] == true) | ||
548 | assert(T.testC[[pushvalue U1; return 1]] == nil) | ||
549 | |||
550 | local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]] | ||
551 | assert(T.upvalue(f, 1) == 10 and | ||
552 | T.upvalue(f, 2) == 20 and | ||
553 | T.upvalue(f, 3) == nil) | ||
554 | T.upvalue(f, 2, "xuxu") | ||
555 | assert(T.upvalue(f, 2) == "xuxu") | ||
556 | |||
557 | |||
558 | -- large closures | ||
559 | do | ||
560 | local A = "checkstack 300 msg;" .. | ||
561 | string.rep("pushnum 10;", 255) .. | ||
562 | "pushcclosure 255; return 1" | ||
563 | A = T.testC(A) | ||
564 | for i=1,255 do | ||
565 | assert(A(("pushvalue U%d; return 1"):format(i)) == 10) | ||
566 | end | ||
567 | assert(A("isnull U256; return 1")) | ||
568 | assert(not A("isnil U256; return 1")) | ||
569 | end | ||
570 | |||
571 | |||
572 | |||
573 | -- testing get/setuservalue | ||
574 | -- bug in 5.1.2 | ||
575 | checkerr("got number", debug.setuservalue, 3, {}) | ||
576 | checkerr("got nil", debug.setuservalue, nil, {}) | ||
577 | checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {}) | ||
578 | |||
579 | -- testing multiple user values | ||
580 | local b = T.newuserdata(0, 10) | ||
581 | for i = 1, 10 do | ||
582 | local v, p = debug.getuservalue(b, i) | ||
583 | assert(v == nil and p) | ||
584 | end | ||
585 | do -- indices out of range | ||
586 | local v, p = debug.getuservalue(b, -2) | ||
587 | assert(v == nil and not p) | ||
588 | local v, p = debug.getuservalue(b, 11) | ||
589 | assert(v == nil and not p) | ||
590 | end | ||
591 | local t = {true, false, 4.56, print, {}, b, "XYZ"} | ||
592 | for k, v in ipairs(t) do | ||
593 | debug.setuservalue(b, v, k) | ||
594 | end | ||
595 | for k, v in ipairs(t) do | ||
596 | local v1, p = debug.getuservalue(b, k) | ||
597 | assert(v1 == v and p) | ||
598 | end | ||
599 | |||
600 | assert(debug.getuservalue(4) == nil) | ||
601 | |||
602 | debug.setuservalue(b, function () return 10 end, 10) | ||
603 | collectgarbage() -- function should not be collected | ||
604 | assert(debug.getuservalue(b, 10)() == 10) | ||
605 | |||
606 | debug.setuservalue(b, 134) | ||
607 | collectgarbage() -- number should not be a problem for collector | ||
608 | assert(debug.getuservalue(b) == 134) | ||
609 | |||
610 | |||
611 | -- test barrier for uservalues | ||
612 | do | ||
613 | local oldmode = collectgarbage("incremental") | ||
614 | T.gcstate("atomic") | ||
615 | assert(T.gccolor(b) == "black") | ||
616 | debug.setuservalue(b, {x = 100}) | ||
617 | T.gcstate("pause") -- complete collection | ||
618 | assert(debug.getuservalue(b).x == 100) -- uvalue should be there | ||
619 | collectgarbage(oldmode) | ||
620 | end | ||
621 | |||
622 | -- long chain of userdata | ||
623 | for i = 1, 1000 do | ||
624 | local bb = T.newuserdata(0, 1) | ||
625 | debug.setuservalue(bb, b) | ||
626 | b = bb | ||
627 | end | ||
628 | collectgarbage() -- nothing should not be collected | ||
629 | for i = 1, 1000 do | ||
630 | b = debug.getuservalue(b) | ||
631 | end | ||
632 | assert(debug.getuservalue(b).x == 100) | ||
633 | b = nil | ||
634 | |||
635 | |||
636 | -- testing locks (refs) | ||
637 | |||
638 | -- reuse of references | ||
639 | local i = T.ref{} | ||
640 | T.unref(i) | ||
641 | assert(T.ref{} == i) | ||
642 | |||
643 | Arr = {} | ||
644 | Lim = 100 | ||
645 | for i=1,Lim do -- lock many objects | ||
646 | Arr[i] = T.ref({}) | ||
647 | end | ||
648 | |||
649 | assert(T.ref(nil) == -1 and T.getref(-1) == nil) | ||
650 | T.unref(-1); T.unref(-1) | ||
651 | |||
652 | for i=1,Lim do -- unlock all them | ||
653 | T.unref(Arr[i]) | ||
654 | end | ||
655 | |||
656 | function printlocks () | ||
657 | local f = T.makeCfunc("gettable R; return 1") | ||
658 | local n = f("n") | ||
659 | print("n", n) | ||
660 | for i=0,n do | ||
661 | print(i, f(i)) | ||
662 | end | ||
663 | end | ||
664 | |||
665 | |||
666 | for i=1,Lim do -- lock many objects | ||
667 | Arr[i] = T.ref({}) | ||
668 | end | ||
669 | |||
670 | for i=1,Lim,2 do -- unlock half of them | ||
671 | T.unref(Arr[i]) | ||
672 | end | ||
673 | |||
674 | assert(type(T.getref(Arr[2])) == 'table') | ||
675 | |||
676 | |||
677 | assert(T.getref(-1) == nil) | ||
678 | |||
679 | |||
680 | a = T.ref({}) | ||
681 | |||
682 | collectgarbage() | ||
683 | |||
684 | assert(type(T.getref(a)) == 'table') | ||
685 | |||
686 | |||
687 | -- colect in cl the `val' of all collected userdata | ||
688 | tt = {} | ||
689 | cl = {n=0} | ||
690 | A = nil; B = nil | ||
691 | local F | ||
692 | F = function (x) | ||
693 | local udval = T.udataval(x) | ||
694 | table.insert(cl, udval) | ||
695 | local d = T.newuserdata(100) -- create garbage | ||
696 | d = nil | ||
697 | assert(debug.getmetatable(x).__gc == F) | ||
698 | assert(load("table.insert({}, {})"))() -- create more garbage | ||
699 | collectgarbage() -- force a GC during GC | ||
700 | assert(debug.getmetatable(x).__gc == F) -- previous GC did not mess this? | ||
701 | local dummy = {} -- create more garbage during GC | ||
702 | if A ~= nil then | ||
703 | assert(type(A) == "userdata") | ||
704 | assert(T.udataval(A) == B) | ||
705 | debug.getmetatable(A) -- just acess it | ||
706 | end | ||
707 | A = x -- ressucita userdata | ||
708 | B = udval | ||
709 | return 1,2,3 | ||
710 | end | ||
711 | tt.__gc = F | ||
712 | |||
713 | -- test whether udate collection frees memory in the right time | ||
714 | do | ||
715 | collectgarbage(); | ||
716 | collectgarbage(); | ||
717 | local x = collectgarbage("count"); | ||
718 | local a = T.newuserdata(5001) | ||
719 | assert(T.testC("objsize 2; return 1", a) == 5001) | ||
720 | assert(collectgarbage("count") >= x+4) | ||
721 | a = nil | ||
722 | collectgarbage(); | ||
723 | assert(collectgarbage("count") <= x+1) | ||
724 | -- udata without finalizer | ||
725 | x = collectgarbage("count") | ||
726 | collectgarbage("stop") | ||
727 | for i=1,1000 do T.newuserdata(0) end | ||
728 | assert(collectgarbage("count") > x+10) | ||
729 | collectgarbage() | ||
730 | assert(collectgarbage("count") <= x+1) | ||
731 | -- udata with finalizer | ||
732 | collectgarbage() | ||
733 | x = collectgarbage("count") | ||
734 | collectgarbage("stop") | ||
735 | a = {__gc = function () end} | ||
736 | for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end | ||
737 | assert(collectgarbage("count") >= x+10) | ||
738 | collectgarbage() -- this collection only calls TM, without freeing memory | ||
739 | assert(collectgarbage("count") >= x+10) | ||
740 | collectgarbage() -- now frees memory | ||
741 | assert(collectgarbage("count") <= x+1) | ||
742 | collectgarbage("restart") | ||
743 | end | ||
744 | |||
745 | |||
746 | collectgarbage("stop") | ||
747 | |||
748 | -- create 3 userdatas with tag `tt' | ||
749 | a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a) | ||
750 | b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b) | ||
751 | c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c) | ||
752 | |||
753 | -- create userdata without meta table | ||
754 | x = T.newuserdata(4) | ||
755 | y = T.newuserdata(0) | ||
756 | |||
757 | checkerr("FILE%* expected, got userdata", io.input, a) | ||
758 | checkerr("FILE%* expected, got userdata", io.input, x) | ||
759 | |||
760 | assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil) | ||
761 | |||
762 | d=T.ref(a); | ||
763 | e=T.ref(b); | ||
764 | f=T.ref(c); | ||
765 | t = {T.getref(d), T.getref(e), T.getref(f)} | ||
766 | assert(t[1] == a and t[2] == b and t[3] == c) | ||
767 | |||
768 | t=nil; a=nil; c=nil; | ||
769 | T.unref(e); T.unref(f) | ||
770 | |||
771 | collectgarbage() | ||
772 | |||
773 | -- check that unref objects have been collected | ||
774 | assert(#cl == 1 and cl[1] == nc) | ||
775 | |||
776 | x = T.getref(d) | ||
777 | assert(type(x) == 'userdata' and debug.getmetatable(x) == tt) | ||
778 | x =nil | ||
779 | tt.b = b -- create cycle | ||
780 | tt=nil -- frees tt for GC | ||
781 | A = nil | ||
782 | b = nil | ||
783 | T.unref(d); | ||
784 | n5 = T.newuserdata(0) | ||
785 | debug.setmetatable(n5, {__gc=F}) | ||
786 | n5 = T.udataval(n5) | ||
787 | collectgarbage() | ||
788 | assert(#cl == 4) | ||
789 | -- check order of collection | ||
790 | assert(cl[2] == n5 and cl[3] == nb and cl[4] == na) | ||
791 | |||
792 | collectgarbage"restart" | ||
793 | |||
794 | |||
795 | a, na = {}, {} | ||
796 | for i=30,1,-1 do | ||
797 | a[i] = T.newuserdata(0) | ||
798 | debug.setmetatable(a[i], {__gc=F}) | ||
799 | na[i] = T.udataval(a[i]) | ||
800 | end | ||
801 | cl = {} | ||
802 | a = nil; collectgarbage() | ||
803 | assert(#cl == 30) | ||
804 | for i=1,30 do assert(cl[i] == na[i]) end | ||
805 | na = nil | ||
806 | |||
807 | |||
808 | for i=2,Lim,2 do -- unlock the other half | ||
809 | T.unref(Arr[i]) | ||
810 | end | ||
811 | |||
812 | x = T.newuserdata(41); debug.setmetatable(x, {__gc=F}) | ||
813 | assert(T.testC("objsize 2; return 1", x) == 41) | ||
814 | cl = {} | ||
815 | a = {[x] = 1} | ||
816 | x = T.udataval(x) | ||
817 | collectgarbage() | ||
818 | -- old `x' cannot be collected (`a' still uses it) | ||
819 | assert(#cl == 0) | ||
820 | for n in pairs(a) do a[n] = undef end | ||
821 | collectgarbage() | ||
822 | assert(#cl == 1 and cl[1] == x) -- old `x' must be collected | ||
823 | |||
824 | -- testing lua_equal | ||
825 | assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20)) | ||
826 | assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo")) | ||
827 | assert(T.testC("compare EQ 2 3; return 1", nil, nil)) | ||
828 | assert(not T.testC("compare EQ 2 3; return 1", {}, {})) | ||
829 | assert(not T.testC("compare EQ 2 3; return 1")) | ||
830 | assert(not T.testC("compare EQ 2 3; return 1", 3)) | ||
831 | |||
832 | -- testing lua_equal with fallbacks | ||
833 | do | ||
834 | local map = {} | ||
835 | local t = {__eq = function (a,b) return map[a] == map[b] end} | ||
836 | local function f(x) | ||
837 | local u = T.newuserdata(0) | ||
838 | debug.setmetatable(u, t) | ||
839 | map[u] = x | ||
840 | return u | ||
841 | end | ||
842 | assert(f(10) == f(10)) | ||
843 | assert(f(10) ~= f(11)) | ||
844 | assert(T.testC("compare EQ 2 3; return 1", f(10), f(10))) | ||
845 | assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20))) | ||
846 | t.__eq = nil | ||
847 | assert(f(10) ~= f(10)) | ||
848 | end | ||
849 | |||
850 | print'+' | ||
851 | |||
852 | |||
853 | |||
854 | -- testing changing hooks during hooks | ||
855 | _G.t = {} | ||
856 | T.sethook([[ | ||
857 | # set a line hook after 3 count hooks | ||
858 | sethook 4 0 ' | ||
859 | getglobal t; | ||
860 | pushvalue -3; append -2 | ||
861 | pushvalue -2; append -2 | ||
862 | ']], "c", 3) | ||
863 | local a = 1 -- counting | ||
864 | a = 1 -- counting | ||
865 | a = 1 -- count hook (set line hook) | ||
866 | a = 1 -- line hook | ||
867 | a = 1 -- line hook | ||
868 | debug.sethook() | ||
869 | t = _G.t | ||
870 | assert(t[1] == "line") | ||
871 | line = t[2] | ||
872 | assert(t[3] == "line" and t[4] == line + 1) | ||
873 | assert(t[5] == "line" and t[6] == line + 2) | ||
874 | assert(t[7] == nil) | ||
875 | |||
876 | |||
877 | ------------------------------------------------------------------------- | ||
878 | do -- testing errors during GC | ||
879 | collectgarbage("stop") | ||
880 | local a = {} | ||
881 | for i=1,20 do | ||
882 | a[i] = T.newuserdata(i) -- creates several udata | ||
883 | end | ||
884 | for i=1,20,2 do -- mark half of them to raise errors during GC | ||
885 | debug.setmetatable(a[i], {__gc = function (x) error("error inside gc") end}) | ||
886 | end | ||
887 | for i=2,20,2 do -- mark the other half to count and to create more garbage | ||
888 | debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end}) | ||
889 | end | ||
890 | _G.A = 0 | ||
891 | a = 0 | ||
892 | while 1 do | ||
893 | local stat, msg = pcall(collectgarbage) | ||
894 | if stat then | ||
895 | break -- stop when no more errors | ||
896 | else | ||
897 | a = a + 1 | ||
898 | assert(string.find(msg, "__gc")) | ||
899 | end | ||
900 | end | ||
901 | assert(a == 10) -- number of errors | ||
902 | |||
903 | assert(A == 10) -- number of normal collections | ||
904 | collectgarbage("restart") | ||
905 | end | ||
906 | ------------------------------------------------------------------------- | ||
907 | -- test for userdata vals | ||
908 | do | ||
909 | local a = {}; local lim = 30 | ||
910 | for i=0,lim do a[i] = T.pushuserdata(i) end | ||
911 | for i=0,lim do assert(T.udataval(a[i]) == i) end | ||
912 | for i=0,lim do assert(T.pushuserdata(i) == a[i]) end | ||
913 | for i=0,lim do a[a[i]] = i end | ||
914 | for i=0,lim do a[T.pushuserdata(i)] = i end | ||
915 | assert(type(tostring(a[1])) == "string") | ||
916 | end | ||
917 | |||
918 | |||
919 | ------------------------------------------------------------------------- | ||
920 | -- testing multiple states | ||
921 | T.closestate(T.newstate()); | ||
922 | L1 = T.newstate() | ||
923 | assert(L1) | ||
924 | |||
925 | assert(T.doremote(L1, "X='a'; return 'a'") == 'a') | ||
926 | |||
927 | |||
928 | assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0) | ||
929 | |||
930 | a, b = T.doremote(L1, "return f()") | ||
931 | assert(a == 'alo' and b == '3') | ||
932 | |||
933 | T.doremote(L1, "_ERRORMESSAGE = nil") | ||
934 | -- error: `sin' is not defined | ||
935 | a, _, b = T.doremote(L1, "return sin(1)") | ||
936 | assert(a == nil and b == 2) -- 2 == run-time error | ||
937 | |||
938 | -- error: syntax error | ||
939 | a, b, c = T.doremote(L1, "return a+") | ||
940 | assert(a == nil and c == 3 and type(b) == "string") -- 3 == syntax error | ||
941 | |||
942 | T.loadlib(L1) | ||
943 | a, b, c = T.doremote(L1, [[ | ||
944 | string = require'string' | ||
945 | a = require'_G'; assert(a == _G and require("_G") == a) | ||
946 | io = require'io'; assert(type(io.read) == "function") | ||
947 | assert(require("io") == io) | ||
948 | a = require'table'; assert(type(a.insert) == "function") | ||
949 | a = require'debug'; assert(type(a.getlocal) == "function") | ||
950 | a = require'math'; assert(type(a.sin) == "function") | ||
951 | return string.sub('okinama', 1, 2) | ||
952 | ]]) | ||
953 | assert(a == "ok") | ||
954 | |||
955 | T.closestate(L1); | ||
956 | |||
957 | |||
958 | L1 = T.newstate() | ||
959 | T.loadlib(L1) | ||
960 | T.doremote(L1, "a = {}") | ||
961 | T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1; | ||
962 | settable -3]]) | ||
963 | assert(T.doremote(L1, "return a.x") == "1") | ||
964 | |||
965 | T.closestate(L1) | ||
966 | |||
967 | L1 = nil | ||
968 | |||
969 | print('+') | ||
970 | |||
971 | ------------------------------------------------------------------------- | ||
972 | -- testing memory limits | ||
973 | ------------------------------------------------------------------------- | ||
974 | print("memory-allocation errors") | ||
975 | |||
976 | checkerr("block too big", T.newuserdata, math.maxinteger) | ||
977 | collectgarbage() | ||
978 | local f = load"local a={}; for i=1,100000 do a[i]=i end" | ||
979 | T.alloccount(10) | ||
980 | checkerr("not enough memory", f) | ||
981 | T.alloccount() -- remove limit | ||
982 | |||
983 | -- test memory errors; increase limit for number of allocations one | ||
984 | -- by one, so that we get memory errors in all allocations of a given | ||
985 | -- task, until there is enough allocations to complete the task without | ||
986 | -- errors. | ||
987 | |||
988 | function testamem (s, f) | ||
989 | collectgarbage(); collectgarbage() | ||
990 | local M = 0 | ||
991 | local a,b = nil | ||
992 | while true do | ||
993 | T.alloccount(M) | ||
994 | a, b = pcall(f) | ||
995 | T.alloccount() -- remove limit | ||
996 | if a and b then break end -- stop when no more errors | ||
997 | if not a and not -- `real' error? | ||
998 | (string.find(b, "memory") or string.find(b, "overflow")) then | ||
999 | error(b, 0) -- propagate it | ||
1000 | end | ||
1001 | M = M + 1 -- increase allocation limit | ||
1002 | end | ||
1003 | print(string.format("limit for %s: %d allocations", s, M)) | ||
1004 | return b | ||
1005 | end | ||
1006 | |||
1007 | |||
1008 | -- doing nothing | ||
1009 | b = testamem("doing nothing", function () return 10 end) | ||
1010 | assert(b == 10) | ||
1011 | |||
1012 | -- testing memory errors when creating a new state | ||
1013 | |||
1014 | b = testamem("state creation", T.newstate) | ||
1015 | T.closestate(b); -- close new state | ||
1016 | |||
1017 | testamem("empty-table creation", function () | ||
1018 | return {} | ||
1019 | end) | ||
1020 | |||
1021 | testamem("string creation", function () | ||
1022 | return "XXX" .. "YYY" | ||
1023 | end) | ||
1024 | |||
1025 | testamem("coroutine creation", function() | ||
1026 | return coroutine.create(print) | ||
1027 | end) | ||
1028 | |||
1029 | |||
1030 | -- testing threads | ||
1031 | |||
1032 | -- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1) | ||
1033 | mt = T.testC("rawgeti R 1; return 1") | ||
1034 | assert(type(mt) == "thread" and coroutine.running() == mt) | ||
1035 | |||
1036 | |||
1037 | |||
1038 | function expand (n,s) | ||
1039 | if n==0 then return "" end | ||
1040 | local e = string.rep("=", n) | ||
1041 | return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n", | ||
1042 | e, s, expand(n-1,s), e) | ||
1043 | end | ||
1044 | |||
1045 | G=0; collectgarbage(); a =collectgarbage("count") | ||
1046 | load(expand(20,"G=G+1"))() | ||
1047 | assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1) | ||
1048 | |||
1049 | testamem("running code on new thread", function () | ||
1050 | return T.doonnewstack("x=1") == 0 -- try to create thread | ||
1051 | end) | ||
1052 | |||
1053 | |||
1054 | -- testing memory x compiler | ||
1055 | |||
1056 | testamem("loadstring", function () | ||
1057 | return load("x=1") -- try to do load a string | ||
1058 | end) | ||
1059 | |||
1060 | |||
1061 | local testprog = [[ | ||
1062 | local function foo () return end | ||
1063 | local t = {"x"} | ||
1064 | a = "aaa" | ||
1065 | for i = 1, #t do a=a..t[i] end | ||
1066 | return true | ||
1067 | ]] | ||
1068 | |||
1069 | -- testing memory x dofile | ||
1070 | _G.a = nil | ||
1071 | local t =os.tmpname() | ||
1072 | local f = assert(io.open(t, "w")) | ||
1073 | f:write(testprog) | ||
1074 | f:close() | ||
1075 | testamem("dofile", function () | ||
1076 | local a = loadfile(t) | ||
1077 | return a and a() | ||
1078 | end) | ||
1079 | assert(os.remove(t)) | ||
1080 | assert(_G.a == "aaax") | ||
1081 | |||
1082 | |||
1083 | -- other generic tests | ||
1084 | |||
1085 | testamem("gsub", function () | ||
1086 | local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end) | ||
1087 | return (a == 'ablo ablo') | ||
1088 | end) | ||
1089 | |||
1090 | testamem("dump/undump", function () | ||
1091 | local a = load(testprog) | ||
1092 | local b = a and string.dump(a) | ||
1093 | a = b and load(b) | ||
1094 | return a and a() | ||
1095 | end) | ||
1096 | |||
1097 | local t = os.tmpname() | ||
1098 | testamem("file creation", function () | ||
1099 | local f = assert(io.open(t, 'w')) | ||
1100 | assert (not io.open"nomenaoexistente") | ||
1101 | io.close(f); | ||
1102 | return not loadfile'nomenaoexistente' | ||
1103 | end) | ||
1104 | assert(os.remove(t)) | ||
1105 | |||
1106 | testamem("table creation", function () | ||
1107 | local a, lim = {}, 10 | ||
1108 | for i=1,lim do a[i] = i; a[i..'a'] = {} end | ||
1109 | return (type(a[lim..'a']) == 'table' and a[lim] == lim) | ||
1110 | end) | ||
1111 | |||
1112 | testamem("constructors", function () | ||
1113 | local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5} | ||
1114 | return (type(a) == 'table' and a.e == 5) | ||
1115 | end) | ||
1116 | |||
1117 | local a = 1 | ||
1118 | close = nil | ||
1119 | testamem("closure creation", function () | ||
1120 | function close (b) | ||
1121 | return function (x) return b + x end | ||
1122 | end | ||
1123 | return (close(2)(4) == 6) | ||
1124 | end) | ||
1125 | |||
1126 | testamem("using coroutines", function () | ||
1127 | local a = coroutine.wrap(function () | ||
1128 | coroutine.yield(string.rep("a", 10)) | ||
1129 | return {} | ||
1130 | end) | ||
1131 | assert(string.len(a()) == 10) | ||
1132 | return a() | ||
1133 | end) | ||
1134 | |||
1135 | do -- auxiliary buffer | ||
1136 | local lim = 100 | ||
1137 | local a = {}; for i = 1, lim do a[i] = "01234567890123456789" end | ||
1138 | testamem("auxiliary buffer", function () | ||
1139 | return (#table.concat(a, ",") == 20*lim + lim - 1) | ||
1140 | end) | ||
1141 | end | ||
1142 | |||
1143 | testamem("growing stack", function () | ||
1144 | local function foo (n) | ||
1145 | if n == 0 then return 1 else return 1 + foo(n - 1) end | ||
1146 | end | ||
1147 | return foo(100) | ||
1148 | end) | ||
1149 | |||
1150 | do -- testing failing in 'lua_checkstack' | ||
1151 | local res = T.testC([[rawcheckstack 500000; return 1]]) | ||
1152 | assert(res == false) | ||
1153 | local L = T.newstate() | ||
1154 | T.alloccount(0) -- will be unable to reallocate the stack | ||
1155 | res = T.testC(L, [[rawcheckstack 5000; return 1]]) | ||
1156 | T.alloccount() | ||
1157 | T.closestate(L) | ||
1158 | assert(res == false) | ||
1159 | end | ||
1160 | |||
1161 | do -- closing state with no extra memory | ||
1162 | local L = T.newstate() | ||
1163 | T.alloccount(0) | ||
1164 | T.closestate(L) | ||
1165 | T.alloccount() | ||
1166 | end | ||
1167 | |||
1168 | do -- garbage collection with no extra memory | ||
1169 | local L = T.newstate() | ||
1170 | T.loadlib(L) | ||
1171 | local res = (T.doremote(L, [[ | ||
1172 | _ENV = require"_G" | ||
1173 | local T = require"T" | ||
1174 | local a = {} | ||
1175 | for i = 1, 1000 do a[i] = 'i' .. i end -- grow string table | ||
1176 | local stsize, stuse = T.querystr() | ||
1177 | assert(stuse > 1000) | ||
1178 | local function foo (n) | ||
1179 | if n > 0 then foo(n - 1) end | ||
1180 | end | ||
1181 | foo(180) -- grow stack | ||
1182 | local _, stksize = T.stacklevel() | ||
1183 | assert(stksize > 180) | ||
1184 | a = nil | ||
1185 | T.alloccount(0) | ||
1186 | collectgarbage() | ||
1187 | T.alloccount() | ||
1188 | -- stack and string table could not be reallocated, | ||
1189 | -- so they kept their sizes (without errors) | ||
1190 | assert(select(2, T.stacklevel()) == stksize) | ||
1191 | assert(T.querystr() == stsize) | ||
1192 | return 'ok' | ||
1193 | ]])) | ||
1194 | assert(res == 'ok') | ||
1195 | T.closestate(L) | ||
1196 | end | ||
1197 | |||
1198 | print'+' | ||
1199 | |||
1200 | -- testing some auxlib functions | ||
1201 | local function gsub (a, b, c) | ||
1202 | a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c) | ||
1203 | assert(b == 5) | ||
1204 | return a | ||
1205 | end | ||
1206 | |||
1207 | assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//") | ||
1208 | assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.") | ||
1209 | assert(gsub("", "alo", "//") == "") | ||
1210 | assert(gsub("...", ".", "/.") == "/././.") | ||
1211 | assert(gsub("...", "...", "") == "") | ||
1212 | |||
1213 | |||
1214 | -- testing luaL_newmetatable | ||
1215 | local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3") | ||
1216 | assert(type(mt_xuxu) == "table" and res and top == 3) | ||
1217 | local d, res, top = T.testC("newmetatable xuxu; gettop; return 3") | ||
1218 | assert(mt_xuxu == d and not res and top == 3) | ||
1219 | d, res, top = T.testC("newmetatable xuxu1; gettop; return 3") | ||
1220 | assert(mt_xuxu ~= d and res and top == 3) | ||
1221 | |||
1222 | x = T.newuserdata(0); | ||
1223 | y = T.newuserdata(0); | ||
1224 | T.testC("pushstring xuxu; gettable R; setmetatable 2", x) | ||
1225 | assert(getmetatable(x) == mt_xuxu) | ||
1226 | |||
1227 | -- testing luaL_testudata | ||
1228 | -- correct metatable | ||
1229 | local res1, res2, top = T.testC([[testudata -1 xuxu | ||
1230 | testudata 2 xuxu | ||
1231 | gettop | ||
1232 | return 3]], x) | ||
1233 | assert(res1 and res2 and top == 4) | ||
1234 | |||
1235 | -- wrong metatable | ||
1236 | res1, res2, top = T.testC([[testudata -1 xuxu1 | ||
1237 | testudata 2 xuxu1 | ||
1238 | gettop | ||
1239 | return 3]], x) | ||
1240 | assert(not res1 and not res2 and top == 4) | ||
1241 | |||
1242 | -- non-existent type | ||
1243 | res1, res2, top = T.testC([[testudata -1 xuxu2 | ||
1244 | testudata 2 xuxu2 | ||
1245 | gettop | ||
1246 | return 3]], x) | ||
1247 | assert(not res1 and not res2 and top == 4) | ||
1248 | |||
1249 | -- userdata has no metatable | ||
1250 | res1, res2, top = T.testC([[testudata -1 xuxu | ||
1251 | testudata 2 xuxu | ||
1252 | gettop | ||
1253 | return 3]], y) | ||
1254 | assert(not res1 and not res2 and top == 4) | ||
1255 | |||
1256 | -- erase metatables | ||
1257 | do | ||
1258 | local r = debug.getregistry() | ||
1259 | assert(r.xuxu == mt_xuxu and r.xuxu1 == d) | ||
1260 | r.xuxu = nil; r.xuxu1 = nil | ||
1261 | end | ||
1262 | |||
1263 | print'OK' | ||
1264 | |||
diff --git a/testes/attrib.lua b/testes/attrib.lua new file mode 100644 index 00000000..79a08a4f --- /dev/null +++ b/testes/attrib.lua | |||
@@ -0,0 +1,487 @@ | |||
1 | -- $Id: attrib.lua,v 1.69 2018/03/12 13:51:02 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print "testing require" | ||
5 | |||
6 | assert(require"string" == string) | ||
7 | assert(require"math" == math) | ||
8 | assert(require"table" == table) | ||
9 | assert(require"io" == io) | ||
10 | assert(require"os" == os) | ||
11 | assert(require"coroutine" == coroutine) | ||
12 | |||
13 | assert(type(package.path) == "string") | ||
14 | assert(type(package.cpath) == "string") | ||
15 | assert(type(package.loaded) == "table") | ||
16 | assert(type(package.preload) == "table") | ||
17 | |||
18 | assert(type(package.config) == "string") | ||
19 | print("package config: "..string.gsub(package.config, "\n", "|")) | ||
20 | |||
21 | do | ||
22 | -- create a path with 'max' templates, | ||
23 | -- each with 1-10 repetitions of '?' | ||
24 | local max = _soft and 100 or 2000 | ||
25 | local t = {} | ||
26 | for i = 1,max do t[i] = string.rep("?", i%10 + 1) end | ||
27 | t[#t + 1] = ";" -- empty template | ||
28 | local path = table.concat(t, ";") | ||
29 | -- use that path in a search | ||
30 | local s, err = package.searchpath("xuxu", path) | ||
31 | -- search fails; check that message has an occurence of | ||
32 | -- '??????????' with ? replaced by xuxu and at least 'max' lines | ||
33 | assert(not s and | ||
34 | string.find(err, string.rep("xuxu", 10)) and | ||
35 | #string.gsub(err, "[^\n]", "") >= max) | ||
36 | -- path with one very long template | ||
37 | local path = string.rep("?", max) | ||
38 | local s, err = package.searchpath("xuxu", path) | ||
39 | assert(not s and string.find(err, string.rep('xuxu', max))) | ||
40 | end | ||
41 | |||
42 | do | ||
43 | local oldpath = package.path | ||
44 | package.path = {} | ||
45 | local s, err = pcall(require, "no-such-file") | ||
46 | assert(not s and string.find(err, "package.path")) | ||
47 | package.path = oldpath | ||
48 | end | ||
49 | |||
50 | print('+') | ||
51 | |||
52 | |||
53 | -- The next tests for 'require' assume some specific directories and | ||
54 | -- libraries. | ||
55 | |||
56 | if not _port then --[ | ||
57 | |||
58 | local dirsep = string.match(package.config, "^([^\n]+)\n") | ||
59 | |||
60 | -- auxiliary directory with C modules and temporary files | ||
61 | local DIR = "libs" .. dirsep | ||
62 | |||
63 | -- prepend DIR to a name and correct directory separators | ||
64 | local function D (x) | ||
65 | x = string.gsub(x, "/", dirsep) | ||
66 | return DIR .. x | ||
67 | end | ||
68 | |||
69 | -- prepend DIR and pospend proper C lib. extension to a name | ||
70 | local function DC (x) | ||
71 | local ext = (dirsep == '\\') and ".dll" or ".so" | ||
72 | return D(x .. ext) | ||
73 | end | ||
74 | |||
75 | |||
76 | local function createfiles (files, preextras, posextras) | ||
77 | for n,c in pairs(files) do | ||
78 | io.output(D(n)) | ||
79 | io.write(string.format(preextras, n)) | ||
80 | io.write(c) | ||
81 | io.write(string.format(posextras, n)) | ||
82 | io.close(io.output()) | ||
83 | end | ||
84 | end | ||
85 | |||
86 | function removefiles (files) | ||
87 | for n in pairs(files) do | ||
88 | os.remove(D(n)) | ||
89 | end | ||
90 | end | ||
91 | |||
92 | local files = { | ||
93 | ["names.lua"] = "do return {...} end\n", | ||
94 | ["err.lua"] = "B = 15; a = a + 1;", | ||
95 | ["synerr.lua"] = "B =", | ||
96 | ["A.lua"] = "", | ||
97 | ["B.lua"] = "assert(...=='B');require 'A'", | ||
98 | ["A.lc"] = "", | ||
99 | ["A"] = "", | ||
100 | ["L"] = "", | ||
101 | ["XXxX"] = "", | ||
102 | ["C.lua"] = "package.loaded[...] = 25; require'C'", | ||
103 | } | ||
104 | |||
105 | AA = nil | ||
106 | local extras = [[ | ||
107 | NAME = '%s' | ||
108 | REQUIRED = ... | ||
109 | return AA]] | ||
110 | |||
111 | createfiles(files, "", extras) | ||
112 | |||
113 | -- testing explicit "dir" separator in 'searchpath' | ||
114 | assert(package.searchpath("C.lua", D"?", "", "") == D"C.lua") | ||
115 | assert(package.searchpath("C.lua", D"?", ".", ".") == D"C.lua") | ||
116 | assert(package.searchpath("--x-", D"?", "-", "X") == D"XXxX") | ||
117 | assert(package.searchpath("---xX", D"?", "---", "XX") == D"XXxX") | ||
118 | assert(package.searchpath(D"C.lua", "?", dirsep) == D"C.lua") | ||
119 | assert(package.searchpath(".\\C.lua", D"?", "\\") == D"./C.lua") | ||
120 | |||
121 | local oldpath = package.path | ||
122 | |||
123 | package.path = string.gsub("D/?.lua;D/?.lc;D/?;D/??x?;D/L", "D/", DIR) | ||
124 | |||
125 | local try = function (p, n, r) | ||
126 | NAME = nil | ||
127 | local rr = require(p) | ||
128 | assert(NAME == n) | ||
129 | assert(REQUIRED == p) | ||
130 | assert(rr == r) | ||
131 | end | ||
132 | |||
133 | a = require"names" | ||
134 | assert(a[1] == "names" and a[2] == D"names.lua") | ||
135 | |||
136 | _G.a = nil | ||
137 | local st, msg = pcall(require, "err") | ||
138 | assert(not st and string.find(msg, "arithmetic") and B == 15) | ||
139 | st, msg = pcall(require, "synerr") | ||
140 | assert(not st and string.find(msg, "error loading module")) | ||
141 | |||
142 | assert(package.searchpath("C", package.path) == D"C.lua") | ||
143 | assert(require"C" == 25) | ||
144 | assert(require"C" == 25) | ||
145 | AA = nil | ||
146 | try('B', 'B.lua', true) | ||
147 | assert(package.loaded.B) | ||
148 | assert(require"B" == true) | ||
149 | assert(package.loaded.A) | ||
150 | assert(require"C" == 25) | ||
151 | package.loaded.A = nil | ||
152 | try('B', nil, true) -- should not reload package | ||
153 | try('A', 'A.lua', true) | ||
154 | package.loaded.A = nil | ||
155 | os.remove(D'A.lua') | ||
156 | AA = {} | ||
157 | try('A', 'A.lc', AA) -- now must find second option | ||
158 | assert(package.searchpath("A", package.path) == D"A.lc") | ||
159 | assert(require("A") == AA) | ||
160 | AA = false | ||
161 | try('K', 'L', false) -- default option | ||
162 | try('K', 'L', false) -- default option (should reload it) | ||
163 | assert(rawget(_G, "_REQUIREDNAME") == nil) | ||
164 | |||
165 | AA = "x" | ||
166 | try("X", "XXxX", AA) | ||
167 | |||
168 | |||
169 | removefiles(files) | ||
170 | |||
171 | |||
172 | -- testing require of sub-packages | ||
173 | |||
174 | local _G = _G | ||
175 | |||
176 | package.path = string.gsub("D/?.lua;D/?/init.lua", "D/", DIR) | ||
177 | |||
178 | files = { | ||
179 | ["P1/init.lua"] = "AA = 10", | ||
180 | ["P1/xuxu.lua"] = "AA = 20", | ||
181 | } | ||
182 | |||
183 | createfiles(files, "_ENV = {}\n", "\nreturn _ENV\n") | ||
184 | AA = 0 | ||
185 | |||
186 | local m = assert(require"P1") | ||
187 | assert(AA == 0 and m.AA == 10) | ||
188 | assert(require"P1" == m) | ||
189 | assert(require"P1" == m) | ||
190 | |||
191 | assert(package.searchpath("P1.xuxu", package.path) == D"P1/xuxu.lua") | ||
192 | m.xuxu = assert(require"P1.xuxu") | ||
193 | assert(AA == 0 and m.xuxu.AA == 20) | ||
194 | assert(require"P1.xuxu" == m.xuxu) | ||
195 | assert(require"P1.xuxu" == m.xuxu) | ||
196 | assert(require"P1" == m and m.AA == 10) | ||
197 | |||
198 | |||
199 | removefiles(files) | ||
200 | |||
201 | |||
202 | package.path = "" | ||
203 | assert(not pcall(require, "file_does_not_exist")) | ||
204 | package.path = "??\0?" | ||
205 | assert(not pcall(require, "file_does_not_exist1")) | ||
206 | |||
207 | package.path = oldpath | ||
208 | |||
209 | -- check 'require' error message | ||
210 | local fname = "file_does_not_exist2" | ||
211 | local m, err = pcall(require, fname) | ||
212 | for t in string.gmatch(package.path..";"..package.cpath, "[^;]+") do | ||
213 | t = string.gsub(t, "?", fname) | ||
214 | assert(string.find(err, t, 1, true)) | ||
215 | end | ||
216 | |||
217 | do -- testing 'package.searchers' not being a table | ||
218 | local searchers = package.searchers | ||
219 | package.searchers = 3 | ||
220 | local st, msg = pcall(require, 'a') | ||
221 | assert(not st and string.find(msg, "must be a table")) | ||
222 | package.searchers = searchers | ||
223 | end | ||
224 | |||
225 | local function import(...) | ||
226 | local f = {...} | ||
227 | return function (m) | ||
228 | for i=1, #f do m[f[i]] = _G[f[i]] end | ||
229 | end | ||
230 | end | ||
231 | |||
232 | -- cannot change environment of a C function | ||
233 | assert(not pcall(module, 'XUXU')) | ||
234 | |||
235 | |||
236 | |||
237 | -- testing require of C libraries | ||
238 | |||
239 | |||
240 | local p = "" -- On Mac OS X, redefine this to "_" | ||
241 | |||
242 | -- check whether loadlib works in this system | ||
243 | local st, err, when = package.loadlib(DC"lib1", "*") | ||
244 | if not st then | ||
245 | local f, err, when = package.loadlib("donotexist", p.."xuxu") | ||
246 | assert(not f and type(err) == "string" and when == "absent") | ||
247 | ;(Message or print)('\n >>> cannot load dynamic library <<<\n') | ||
248 | print(err, when) | ||
249 | else | ||
250 | -- tests for loadlib | ||
251 | local f = assert(package.loadlib(DC"lib1", p.."onefunction")) | ||
252 | local a, b = f(15, 25) | ||
253 | assert(a == 25 and b == 15) | ||
254 | |||
255 | f = assert(package.loadlib(DC"lib1", p.."anotherfunc")) | ||
256 | assert(f(10, 20) == "10%20\n") | ||
257 | |||
258 | -- check error messages | ||
259 | local f, err, when = package.loadlib(DC"lib1", p.."xuxu") | ||
260 | assert(not f and type(err) == "string" and when == "init") | ||
261 | f, err, when = package.loadlib("donotexist", p.."xuxu") | ||
262 | assert(not f and type(err) == "string" and when == "open") | ||
263 | |||
264 | -- symbols from 'lib1' must be visible to other libraries | ||
265 | f = assert(package.loadlib(DC"lib11", p.."luaopen_lib11")) | ||
266 | assert(f() == "exported") | ||
267 | |||
268 | -- test C modules with prefixes in names | ||
269 | package.cpath = DC"?" | ||
270 | local lib2 = require"lib2-v2" | ||
271 | -- check correct access to global environment and correct | ||
272 | -- parameters | ||
273 | assert(_ENV.x == "lib2-v2" and _ENV.y == DC"lib2-v2") | ||
274 | assert(lib2.id("x") == "x") | ||
275 | |||
276 | -- test C submodules | ||
277 | local fs = require"lib1.sub" | ||
278 | assert(_ENV.x == "lib1.sub" and _ENV.y == DC"lib1") | ||
279 | assert(fs.id(45) == 45) | ||
280 | end | ||
281 | |||
282 | _ENV = _G | ||
283 | |||
284 | |||
285 | -- testing preload | ||
286 | |||
287 | do | ||
288 | local p = package | ||
289 | package = {} | ||
290 | p.preload.pl = function (...) | ||
291 | local _ENV = {...} | ||
292 | function xuxu (x) return x+20 end | ||
293 | return _ENV | ||
294 | end | ||
295 | |||
296 | local pl = require"pl" | ||
297 | assert(require"pl" == pl) | ||
298 | assert(pl.xuxu(10) == 30) | ||
299 | assert(pl[1] == "pl" and pl[2] == nil) | ||
300 | |||
301 | package = p | ||
302 | assert(type(package.path) == "string") | ||
303 | end | ||
304 | |||
305 | print('+') | ||
306 | |||
307 | end --] | ||
308 | |||
309 | print("testing assignments, logical operators, and constructors") | ||
310 | |||
311 | local res, res2 = 27 | ||
312 | |||
313 | a, b = 1, 2+3 | ||
314 | assert(a==1 and b==5) | ||
315 | a={} | ||
316 | function f() return 10, 11, 12 end | ||
317 | a.x, b, a[1] = 1, 2, f() | ||
318 | assert(a.x==1 and b==2 and a[1]==10) | ||
319 | a[f()], b, a[f()+3] = f(), a, 'x' | ||
320 | assert(a[10] == 10 and b == a and a[13] == 'x') | ||
321 | |||
322 | do | ||
323 | local f = function (n) local x = {}; for i=1,n do x[i]=i end; | ||
324 | return table.unpack(x) end; | ||
325 | local a,b,c | ||
326 | a,b = 0, f(1) | ||
327 | assert(a == 0 and b == 1) | ||
328 | A,b = 0, f(1) | ||
329 | assert(A == 0 and b == 1) | ||
330 | a,b,c = 0,5,f(4) | ||
331 | assert(a==0 and b==5 and c==1) | ||
332 | a,b,c = 0,5,f(0) | ||
333 | assert(a==0 and b==5 and c==nil) | ||
334 | end | ||
335 | |||
336 | a, b, c, d = 1 and nil, 1 or nil, (1 and (nil or 1)), 6 | ||
337 | assert(not a and b and c and d==6) | ||
338 | |||
339 | d = 20 | ||
340 | a, b, c, d = f() | ||
341 | assert(a==10 and b==11 and c==12 and d==nil) | ||
342 | a,b = f(), 1, 2, 3, f() | ||
343 | assert(a==10 and b==1) | ||
344 | |||
345 | assert(a<b == false and a>b == true) | ||
346 | assert((10 and 2) == 2) | ||
347 | assert((10 or 2) == 10) | ||
348 | assert((10 or assert(nil)) == 10) | ||
349 | assert(not (nil and assert(nil))) | ||
350 | assert((nil or "alo") == "alo") | ||
351 | assert((nil and 10) == nil) | ||
352 | assert((false and 10) == false) | ||
353 | assert((true or 10) == true) | ||
354 | assert((false or 10) == 10) | ||
355 | assert(false ~= nil) | ||
356 | assert(nil ~= false) | ||
357 | assert(not nil == true) | ||
358 | assert(not not nil == false) | ||
359 | assert(not not 1 == true) | ||
360 | assert(not not a == true) | ||
361 | assert(not not (6 or nil) == true) | ||
362 | assert(not not (nil and 56) == false) | ||
363 | assert(not not (nil and true) == false) | ||
364 | assert(not 10 == false) | ||
365 | assert(not {} == false) | ||
366 | assert(not 0.5 == false) | ||
367 | assert(not "x" == false) | ||
368 | |||
369 | assert({} ~= {}) | ||
370 | print('+') | ||
371 | |||
372 | a = {} | ||
373 | a[true] = 20 | ||
374 | a[false] = 10 | ||
375 | assert(a[1<2] == 20 and a[1>2] == 10) | ||
376 | |||
377 | function f(a) return a end | ||
378 | |||
379 | local a = {} | ||
380 | for i=3000,-3000,-1 do a[i + 0.0] = i; end | ||
381 | a[10e30] = "alo"; a[true] = 10; a[false] = 20 | ||
382 | assert(a[10e30] == 'alo' and a[not 1] == 20 and a[10<20] == 10) | ||
383 | for i=3000,-3000,-1 do assert(a[i] == i); end | ||
384 | a[print] = assert | ||
385 | a[f] = print | ||
386 | a[a] = a | ||
387 | assert(a[a][a][a][a][print] == assert) | ||
388 | a[print](a[a[f]] == a[print]) | ||
389 | assert(not pcall(function () local a = {}; a[nil] = 10 end)) | ||
390 | assert(not pcall(function () local a = {[nil] = 10} end)) | ||
391 | assert(a[nil] == undef) | ||
392 | a = nil | ||
393 | |||
394 | a = {10,9,8,7,6,5,4,3,2; [-3]='a', [f]=print, a='a', b='ab'} | ||
395 | a, a.x, a.y = a, a[-3] | ||
396 | assert(a[1]==10 and a[-3]==a.a and a[f]==print and a.x=='a' and not a.y) | ||
397 | a[1], f(a)[2], b, c = {['alo']=assert}, 10, a[1], a[f], 6, 10, 23, f(a), 2 | ||
398 | a[1].alo(a[2]==10 and b==10 and c==print) | ||
399 | |||
400 | a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 = 10 | ||
401 | local function foo () | ||
402 | return a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 | ||
403 | end | ||
404 | assert(foo() == 10 and | ||
405 | a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 == | ||
406 | 10) | ||
407 | |||
408 | |||
409 | |||
410 | -- test of large float/integer indices | ||
411 | |||
412 | -- compute maximum integer where all bits fit in a float | ||
413 | local maxint = math.maxinteger | ||
414 | |||
415 | -- trim (if needed) to fit in a float | ||
416 | while maxint ~= (maxint + 0.0) or (maxint - 1) ~= (maxint - 1.0) do | ||
417 | maxint = maxint // 2 | ||
418 | end | ||
419 | |||
420 | maxintF = maxint + 0.0 -- float version | ||
421 | |||
422 | assert(maxintF == maxint and math.type(maxintF) == "float" and | ||
423 | maxintF >= 2.0^14) | ||
424 | |||
425 | -- floats and integers must index the same places | ||
426 | a[maxintF] = 10; a[maxintF - 1.0] = 11; | ||
427 | a[-maxintF] = 12; a[-maxintF + 1.0] = 13; | ||
428 | |||
429 | assert(a[maxint] == 10 and a[maxint - 1] == 11 and | ||
430 | a[-maxint] == 12 and a[-maxint + 1] == 13) | ||
431 | |||
432 | a[maxint] = 20 | ||
433 | a[-maxint] = 22 | ||
434 | |||
435 | assert(a[maxintF] == 20 and a[maxintF - 1.0] == 11 and | ||
436 | a[-maxintF] == 22 and a[-maxintF + 1.0] == 13) | ||
437 | |||
438 | a = nil | ||
439 | |||
440 | |||
441 | -- test conflicts in multiple assignment | ||
442 | do | ||
443 | local a,i,j,b | ||
444 | a = {'a', 'b'}; i=1; j=2; b=a | ||
445 | i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i | ||
446 | assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and | ||
447 | b[3] == 1) | ||
448 | a = {} | ||
449 | local function foo () -- assigining to upvalues | ||
450 | b, a.x, a = a, 10, 20 | ||
451 | end | ||
452 | foo() | ||
453 | assert(a == 20 and b.x == 10) | ||
454 | end | ||
455 | |||
456 | -- repeat test with upvalues | ||
457 | do | ||
458 | local a,i,j,b | ||
459 | a = {'a', 'b'}; i=1; j=2; b=a | ||
460 | local function foo () | ||
461 | i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i | ||
462 | end | ||
463 | foo() | ||
464 | assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and | ||
465 | b[3] == 1) | ||
466 | local t = {} | ||
467 | (function (a) t[a], a = 10, 20 end)(1); | ||
468 | assert(t[1] == 10) | ||
469 | end | ||
470 | |||
471 | -- bug in 5.2 beta | ||
472 | local function foo () | ||
473 | local a | ||
474 | return function () | ||
475 | local b | ||
476 | a, b = 3, 14 -- local and upvalue have same index | ||
477 | return a, b | ||
478 | end | ||
479 | end | ||
480 | |||
481 | local a, b = foo()() | ||
482 | assert(a == 3 and b == 14) | ||
483 | |||
484 | print('OK') | ||
485 | |||
486 | return res | ||
487 | |||
diff --git a/testes/big.lua b/testes/big.lua new file mode 100644 index 00000000..ebee1ec0 --- /dev/null +++ b/testes/big.lua | |||
@@ -0,0 +1,82 @@ | |||
1 | -- $Id: big.lua,v 1.35 2018/03/09 14:23:48 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | if _soft then | ||
5 | return 'a' | ||
6 | end | ||
7 | |||
8 | print "testing large tables" | ||
9 | |||
10 | local debug = require"debug" | ||
11 | |||
12 | local lim = 2^18 + 1000 | ||
13 | local prog = { "local y = {0" } | ||
14 | for i = 1, lim do prog[#prog + 1] = i end | ||
15 | prog[#prog + 1] = "}\n" | ||
16 | prog[#prog + 1] = "X = y\n" | ||
17 | prog[#prog + 1] = ("assert(X[%d] == %d)"):format(lim - 1, lim - 2) | ||
18 | prog[#prog + 1] = "return 0" | ||
19 | prog = table.concat(prog, ";") | ||
20 | |||
21 | local env = {string = string, assert = assert} | ||
22 | local f = assert(load(prog, nil, nil, env)) | ||
23 | |||
24 | f() | ||
25 | assert(env.X[lim] == lim - 1 and env.X[lim + 1] == lim) | ||
26 | for k in pairs(env) do env[k] = undef end | ||
27 | |||
28 | -- yields during accesses larger than K (in RK) | ||
29 | setmetatable(env, { | ||
30 | __index = function (t, n) coroutine.yield('g'); return _G[n] end, | ||
31 | __newindex = function (t, n, v) coroutine.yield('s'); _G[n] = v end, | ||
32 | }) | ||
33 | |||
34 | X = nil | ||
35 | co = coroutine.wrap(f) | ||
36 | assert(co() == 's') | ||
37 | assert(co() == 'g') | ||
38 | assert(co() == 'g') | ||
39 | assert(co() == 0) | ||
40 | |||
41 | assert(X[lim] == lim - 1 and X[lim + 1] == lim) | ||
42 | |||
43 | -- errors in accesses larger than K (in RK) | ||
44 | getmetatable(env).__index = function () end | ||
45 | getmetatable(env).__newindex = function () end | ||
46 | local e, m = pcall(f) | ||
47 | assert(not e and m:find("global 'X'")) | ||
48 | |||
49 | -- errors in metamethods | ||
50 | getmetatable(env).__newindex = function () error("hi") end | ||
51 | local e, m = xpcall(f, debug.traceback) | ||
52 | assert(not e and m:find("'newindex'")) | ||
53 | |||
54 | f, X = nil | ||
55 | |||
56 | coroutine.yield'b' | ||
57 | |||
58 | if 2^32 == 0 then -- (small integers) { | ||
59 | |||
60 | print "testing string length overflow" | ||
61 | |||
62 | local repstrings = 192 -- number of strings to be concatenated | ||
63 | local ssize = math.ceil(2.0^32 / repstrings) + 1 -- size of each string | ||
64 | |||
65 | assert(repstrings * ssize > 2.0^32) -- it should be larger than maximum size | ||
66 | |||
67 | local longs = string.rep("\0", ssize) -- create one long string | ||
68 | |||
69 | -- create function to concatentate 'repstrings' copies of its argument | ||
70 | local rep = assert(load( | ||
71 | "local a = ...; return " .. string.rep("a", repstrings, ".."))) | ||
72 | |||
73 | local a, b = pcall(rep, longs) -- call that function | ||
74 | |||
75 | -- it should fail without creating string (result would be too large) | ||
76 | assert(not a and string.find(b, "overflow")) | ||
77 | |||
78 | end -- } | ||
79 | |||
80 | print'OK' | ||
81 | |||
82 | return 'a' | ||
diff --git a/testes/bitwise.lua b/testes/bitwise.lua new file mode 100755 index 00000000..3e7079d3 --- /dev/null +++ b/testes/bitwise.lua | |||
@@ -0,0 +1,346 @@ | |||
1 | -- $Id: bitwise.lua,v 1.27 2018/02/21 17:49:39 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print("testing bitwise operations") | ||
5 | |||
6 | require "bwcoercion" | ||
7 | |||
8 | local numbits = string.packsize('j') * 8 | ||
9 | |||
10 | assert(~0 == -1) | ||
11 | |||
12 | assert((1 << (numbits - 1)) == math.mininteger) | ||
13 | |||
14 | -- basic tests for bitwise operators; | ||
15 | -- use variables to avoid constant folding | ||
16 | local a, b, c, d | ||
17 | a = 0xFFFFFFFFFFFFFFFF | ||
18 | assert(a == -1 and a & -1 == a and a & 35 == 35) | ||
19 | a = 0xF0F0F0F0F0F0F0F0 | ||
20 | assert(a | -1 == -1) | ||
21 | assert(a ~ a == 0 and a ~ 0 == a and a ~ ~a == -1) | ||
22 | assert(a >> 4 == ~a) | ||
23 | a = 0xF0; b = 0xCC; c = 0xAA; d = 0xFD | ||
24 | assert(a | b ~ c & d == 0xF4) | ||
25 | |||
26 | a = 0xF0.0; b = 0xCC.0; c = "0xAA.0"; d = "0xFD.0" | ||
27 | assert(a | b ~ c & d == 0xF4) | ||
28 | |||
29 | a = 0xF0000000; b = 0xCC000000; | ||
30 | c = 0xAA000000; d = 0xFD000000 | ||
31 | assert(a | b ~ c & d == 0xF4000000) | ||
32 | assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1) | ||
33 | |||
34 | a = a << 32 | ||
35 | b = b << 32 | ||
36 | c = c << 32 | ||
37 | d = d << 32 | ||
38 | assert(a | b ~ c & d == 0xF4000000 << 32) | ||
39 | assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1) | ||
40 | |||
41 | assert(-1 >> 1 == (1 << (numbits - 1)) - 1 and 1 << 31 == 0x80000000) | ||
42 | assert(-1 >> (numbits - 1) == 1) | ||
43 | assert(-1 >> numbits == 0 and | ||
44 | -1 >> -numbits == 0 and | ||
45 | -1 << numbits == 0 and | ||
46 | -1 << -numbits == 0) | ||
47 | |||
48 | assert((2^30 - 1) << 2^30 == 0) | ||
49 | assert((2^30 - 1) >> 2^30 == 0) | ||
50 | |||
51 | assert(1 >> -3 == 1 << 3 and 1000 >> 5 == 1000 << -5) | ||
52 | |||
53 | |||
54 | -- coercion from strings to integers | ||
55 | assert("0xffffffffffffffff" | 0 == -1) | ||
56 | assert("0xfffffffffffffffe" & "-1" == -2) | ||
57 | assert(" \t-0xfffffffffffffffe\n\t" & "-1" == 2) | ||
58 | assert(" \n -45 \t " >> " -2 " == -45 * 4) | ||
59 | assert("1234.0" << "5.0" == 1234 * 32) | ||
60 | assert("0xffff.0" ~ "0xAAAA" == 0x5555) | ||
61 | assert(~"0x0.000p4" == -1) | ||
62 | |||
63 | assert("7" .. 3 << 1 == 146) | ||
64 | assert(10 >> 1 .. "9" == 0) | ||
65 | assert(10 | 1 .. "9" == 27) | ||
66 | |||
67 | do | ||
68 | local st, msg = pcall(function () return 4 & "a" end) | ||
69 | assert(string.find(msg, "'band'")) | ||
70 | |||
71 | local st, msg = pcall(function () return ~"a" end) | ||
72 | assert(string.find(msg, "'bnot'")) | ||
73 | end | ||
74 | |||
75 | |||
76 | -- out of range number | ||
77 | assert(not pcall(function () return "0xffffffffffffffff.0" | 0 end)) | ||
78 | |||
79 | -- embedded zeros | ||
80 | assert(not pcall(function () return "0xffffffffffffffff\0" | 0 end)) | ||
81 | |||
82 | print'+' | ||
83 | |||
84 | |||
85 | package.preload.bit32 = function () --{ | ||
86 | |||
87 | -- no built-in 'bit32' library: implement it using bitwise operators | ||
88 | |||
89 | local bit = {} | ||
90 | |||
91 | function bit.bnot (a) | ||
92 | return ~a & 0xFFFFFFFF | ||
93 | end | ||
94 | |||
95 | |||
96 | -- | ||
97 | -- in all vararg functions, avoid creating 'arg' table when there are | ||
98 | -- only 2 (or less) parameters, as 2 parameters is the common case | ||
99 | -- | ||
100 | |||
101 | function bit.band (x, y, z, ...) | ||
102 | if not z then | ||
103 | return ((x or -1) & (y or -1)) & 0xFFFFFFFF | ||
104 | else | ||
105 | local arg = {...} | ||
106 | local res = x & y & z | ||
107 | for i = 1, #arg do res = res & arg[i] end | ||
108 | return res & 0xFFFFFFFF | ||
109 | end | ||
110 | end | ||
111 | |||
112 | function bit.bor (x, y, z, ...) | ||
113 | if not z then | ||
114 | return ((x or 0) | (y or 0)) & 0xFFFFFFFF | ||
115 | else | ||
116 | local arg = {...} | ||
117 | local res = x | y | z | ||
118 | for i = 1, #arg do res = res | arg[i] end | ||
119 | return res & 0xFFFFFFFF | ||
120 | end | ||
121 | end | ||
122 | |||
123 | function bit.bxor (x, y, z, ...) | ||
124 | if not z then | ||
125 | return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF | ||
126 | else | ||
127 | local arg = {...} | ||
128 | local res = x ~ y ~ z | ||
129 | for i = 1, #arg do res = res ~ arg[i] end | ||
130 | return res & 0xFFFFFFFF | ||
131 | end | ||
132 | end | ||
133 | |||
134 | function bit.btest (...) | ||
135 | return bit.band(...) ~= 0 | ||
136 | end | ||
137 | |||
138 | function bit.lshift (a, b) | ||
139 | return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF | ||
140 | end | ||
141 | |||
142 | function bit.rshift (a, b) | ||
143 | return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF | ||
144 | end | ||
145 | |||
146 | function bit.arshift (a, b) | ||
147 | a = a & 0xFFFFFFFF | ||
148 | if b <= 0 or (a & 0x80000000) == 0 then | ||
149 | return (a >> b) & 0xFFFFFFFF | ||
150 | else | ||
151 | return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF | ||
152 | end | ||
153 | end | ||
154 | |||
155 | function bit.lrotate (a ,b) | ||
156 | b = b & 31 | ||
157 | a = a & 0xFFFFFFFF | ||
158 | a = (a << b) | (a >> (32 - b)) | ||
159 | return a & 0xFFFFFFFF | ||
160 | end | ||
161 | |||
162 | function bit.rrotate (a, b) | ||
163 | return bit.lrotate(a, -b) | ||
164 | end | ||
165 | |||
166 | local function checkfield (f, w) | ||
167 | w = w or 1 | ||
168 | assert(f >= 0, "field cannot be negative") | ||
169 | assert(w > 0, "width must be positive") | ||
170 | assert(f + w <= 32, "trying to access non-existent bits") | ||
171 | return f, ~(-1 << w) | ||
172 | end | ||
173 | |||
174 | function bit.extract (a, f, w) | ||
175 | local f, mask = checkfield(f, w) | ||
176 | return (a >> f) & mask | ||
177 | end | ||
178 | |||
179 | function bit.replace (a, v, f, w) | ||
180 | local f, mask = checkfield(f, w) | ||
181 | v = v & mask | ||
182 | a = (a & ~(mask << f)) | (v << f) | ||
183 | return a & 0xFFFFFFFF | ||
184 | end | ||
185 | |||
186 | return bit | ||
187 | |||
188 | end --} | ||
189 | |||
190 | |||
191 | print("testing bitwise library") | ||
192 | |||
193 | local bit32 = require'bit32' | ||
194 | |||
195 | assert(bit32.band() == bit32.bnot(0)) | ||
196 | assert(bit32.btest() == true) | ||
197 | assert(bit32.bor() == 0) | ||
198 | assert(bit32.bxor() == 0) | ||
199 | |||
200 | assert(bit32.band() == bit32.band(0xffffffff)) | ||
201 | assert(bit32.band(1,2) == 0) | ||
202 | |||
203 | |||
204 | -- out-of-range numbers | ||
205 | assert(bit32.band(-1) == 0xffffffff) | ||
206 | assert(bit32.band((1 << 33) - 1) == 0xffffffff) | ||
207 | assert(bit32.band(-(1 << 33) - 1) == 0xffffffff) | ||
208 | assert(bit32.band((1 << 33) + 1) == 1) | ||
209 | assert(bit32.band(-(1 << 33) + 1) == 1) | ||
210 | assert(bit32.band(-(1 << 40)) == 0) | ||
211 | assert(bit32.band(1 << 40) == 0) | ||
212 | assert(bit32.band(-(1 << 40) - 2) == 0xfffffffe) | ||
213 | assert(bit32.band((1 << 40) - 4) == 0xfffffffc) | ||
214 | |||
215 | assert(bit32.lrotate(0, -1) == 0) | ||
216 | assert(bit32.lrotate(0, 7) == 0) | ||
217 | assert(bit32.lrotate(0x12345678, 0) == 0x12345678) | ||
218 | assert(bit32.lrotate(0x12345678, 32) == 0x12345678) | ||
219 | assert(bit32.lrotate(0x12345678, 4) == 0x23456781) | ||
220 | assert(bit32.rrotate(0x12345678, -4) == 0x23456781) | ||
221 | assert(bit32.lrotate(0x12345678, -8) == 0x78123456) | ||
222 | assert(bit32.rrotate(0x12345678, 8) == 0x78123456) | ||
223 | assert(bit32.lrotate(0xaaaaaaaa, 2) == 0xaaaaaaaa) | ||
224 | assert(bit32.lrotate(0xaaaaaaaa, -2) == 0xaaaaaaaa) | ||
225 | for i = -50, 50 do | ||
226 | assert(bit32.lrotate(0x89abcdef, i) == bit32.lrotate(0x89abcdef, i%32)) | ||
227 | end | ||
228 | |||
229 | assert(bit32.lshift(0x12345678, 4) == 0x23456780) | ||
230 | assert(bit32.lshift(0x12345678, 8) == 0x34567800) | ||
231 | assert(bit32.lshift(0x12345678, -4) == 0x01234567) | ||
232 | assert(bit32.lshift(0x12345678, -8) == 0x00123456) | ||
233 | assert(bit32.lshift(0x12345678, 32) == 0) | ||
234 | assert(bit32.lshift(0x12345678, -32) == 0) | ||
235 | assert(bit32.rshift(0x12345678, 4) == 0x01234567) | ||
236 | assert(bit32.rshift(0x12345678, 8) == 0x00123456) | ||
237 | assert(bit32.rshift(0x12345678, 32) == 0) | ||
238 | assert(bit32.rshift(0x12345678, -32) == 0) | ||
239 | assert(bit32.arshift(0x12345678, 0) == 0x12345678) | ||
240 | assert(bit32.arshift(0x12345678, 1) == 0x12345678 // 2) | ||
241 | assert(bit32.arshift(0x12345678, -1) == 0x12345678 * 2) | ||
242 | assert(bit32.arshift(-1, 1) == 0xffffffff) | ||
243 | assert(bit32.arshift(-1, 24) == 0xffffffff) | ||
244 | assert(bit32.arshift(-1, 32) == 0xffffffff) | ||
245 | assert(bit32.arshift(-1, -1) == bit32.band(-1 * 2, 0xffffffff)) | ||
246 | |||
247 | assert(0x12345678 << 4 == 0x123456780) | ||
248 | assert(0x12345678 << 8 == 0x1234567800) | ||
249 | assert(0x12345678 << -4 == 0x01234567) | ||
250 | assert(0x12345678 << -8 == 0x00123456) | ||
251 | assert(0x12345678 << 32 == 0x1234567800000000) | ||
252 | assert(0x12345678 << -32 == 0) | ||
253 | assert(0x12345678 >> 4 == 0x01234567) | ||
254 | assert(0x12345678 >> 8 == 0x00123456) | ||
255 | assert(0x12345678 >> 32 == 0) | ||
256 | assert(0x12345678 >> -32 == 0x1234567800000000) | ||
257 | |||
258 | print("+") | ||
259 | -- some special cases | ||
260 | local c = {0, 1, 2, 3, 10, 0x80000000, 0xaaaaaaaa, 0x55555555, | ||
261 | 0xffffffff, 0x7fffffff} | ||
262 | |||
263 | for _, b in pairs(c) do | ||
264 | assert(bit32.band(b) == b) | ||
265 | assert(bit32.band(b, b) == b) | ||
266 | assert(bit32.band(b, b, b, b) == b) | ||
267 | assert(bit32.btest(b, b) == (b ~= 0)) | ||
268 | assert(bit32.band(b, b, b) == b) | ||
269 | assert(bit32.band(b, b, b, ~b) == 0) | ||
270 | assert(bit32.btest(b, b, b) == (b ~= 0)) | ||
271 | assert(bit32.band(b, bit32.bnot(b)) == 0) | ||
272 | assert(bit32.bor(b, bit32.bnot(b)) == bit32.bnot(0)) | ||
273 | assert(bit32.bor(b) == b) | ||
274 | assert(bit32.bor(b, b) == b) | ||
275 | assert(bit32.bor(b, b, b) == b) | ||
276 | assert(bit32.bor(b, b, 0, ~b) == 0xffffffff) | ||
277 | assert(bit32.bxor(b) == b) | ||
278 | assert(bit32.bxor(b, b) == 0) | ||
279 | assert(bit32.bxor(b, b, b) == b) | ||
280 | assert(bit32.bxor(b, b, b, b) == 0) | ||
281 | assert(bit32.bxor(b, 0) == b) | ||
282 | assert(bit32.bnot(b) ~= b) | ||
283 | assert(bit32.bnot(bit32.bnot(b)) == b) | ||
284 | assert(bit32.bnot(b) == (1 << 32) - 1 - b) | ||
285 | assert(bit32.lrotate(b, 32) == b) | ||
286 | assert(bit32.rrotate(b, 32) == b) | ||
287 | assert(bit32.lshift(bit32.lshift(b, -4), 4) == bit32.band(b, bit32.bnot(0xf))) | ||
288 | assert(bit32.rshift(bit32.rshift(b, 4), -4) == bit32.band(b, bit32.bnot(0xf))) | ||
289 | end | ||
290 | |||
291 | -- for this test, use at most 24 bits (mantissa of a single float) | ||
292 | c = {0, 1, 2, 3, 10, 0x800000, 0xaaaaaa, 0x555555, 0xffffff, 0x7fffff} | ||
293 | for _, b in pairs(c) do | ||
294 | for i = -40, 40 do | ||
295 | local x = bit32.lshift(b, i) | ||
296 | local y = math.floor(math.fmod(b * 2.0^i, 2.0^32)) | ||
297 | assert(math.fmod(x - y, 2.0^32) == 0) | ||
298 | end | ||
299 | end | ||
300 | |||
301 | assert(not pcall(bit32.band, {})) | ||
302 | assert(not pcall(bit32.bnot, "a")) | ||
303 | assert(not pcall(bit32.lshift, 45)) | ||
304 | assert(not pcall(bit32.lshift, 45, print)) | ||
305 | assert(not pcall(bit32.rshift, 45, print)) | ||
306 | |||
307 | print("+") | ||
308 | |||
309 | |||
310 | -- testing extract/replace | ||
311 | |||
312 | assert(bit32.extract(0x12345678, 0, 4) == 8) | ||
313 | assert(bit32.extract(0x12345678, 4, 4) == 7) | ||
314 | assert(bit32.extract(0xa0001111, 28, 4) == 0xa) | ||
315 | assert(bit32.extract(0xa0001111, 31, 1) == 1) | ||
316 | assert(bit32.extract(0x50000111, 31, 1) == 0) | ||
317 | assert(bit32.extract(0xf2345679, 0, 32) == 0xf2345679) | ||
318 | |||
319 | assert(not pcall(bit32.extract, 0, -1)) | ||
320 | assert(not pcall(bit32.extract, 0, 32)) | ||
321 | assert(not pcall(bit32.extract, 0, 0, 33)) | ||
322 | assert(not pcall(bit32.extract, 0, 31, 2)) | ||
323 | |||
324 | assert(bit32.replace(0x12345678, 5, 28, 4) == 0x52345678) | ||
325 | assert(bit32.replace(0x12345678, 0x87654321, 0, 32) == 0x87654321) | ||
326 | assert(bit32.replace(0, 1, 2) == 2^2) | ||
327 | assert(bit32.replace(0, -1, 4) == 2^4) | ||
328 | assert(bit32.replace(-1, 0, 31) == (1 << 31) - 1) | ||
329 | assert(bit32.replace(-1, 0, 1, 2) == (1 << 32) - 7) | ||
330 | |||
331 | |||
332 | -- testing conversion of floats | ||
333 | |||
334 | assert(bit32.bor(3.0) == 3) | ||
335 | assert(bit32.bor(-4.0) == 0xfffffffc) | ||
336 | |||
337 | -- large floats and large-enough integers? | ||
338 | if 2.0^50 < 2.0^50 + 1.0 and 2.0^50 < (-1 >> 1) then | ||
339 | assert(bit32.bor(2.0^32 - 5.0) == 0xfffffffb) | ||
340 | assert(bit32.bor(-2.0^32 - 6.0) == 0xfffffffa) | ||
341 | assert(bit32.bor(2.0^48 - 5.0) == 0xfffffffb) | ||
342 | assert(bit32.bor(-2.0^48 - 6.0) == 0xfffffffa) | ||
343 | end | ||
344 | |||
345 | print'OK' | ||
346 | |||
diff --git a/testes/bwcoercion.lua b/testes/bwcoercion.lua new file mode 100644 index 00000000..cd735ab0 --- /dev/null +++ b/testes/bwcoercion.lua | |||
@@ -0,0 +1,78 @@ | |||
1 | local tonumber, tointeger = tonumber, math.tointeger | ||
2 | local type, getmetatable, rawget, error = type, getmetatable, rawget, error | ||
3 | local strsub = string.sub | ||
4 | |||
5 | local print = print | ||
6 | |||
7 | _ENV = nil | ||
8 | |||
9 | -- Try to convert a value to an integer, without assuming any coercion. | ||
10 | local function toint (x) | ||
11 | x = tonumber(x) -- handle numerical strings | ||
12 | if not x then | ||
13 | return false -- not coercible to a number | ||
14 | end | ||
15 | return tointeger(x) | ||
16 | end | ||
17 | |||
18 | |||
19 | -- If operation fails, maybe second operand has a metamethod that should | ||
20 | -- have been called if not for this string metamethod, so try to | ||
21 | -- call it. | ||
22 | local function trymt (x, y, mtname) | ||
23 | if type(y) ~= "string" then -- avoid recalling original metamethod | ||
24 | local mt = getmetatable(y) | ||
25 | local mm = mt and rawget(mt, mtname) | ||
26 | if mm then | ||
27 | return mm(x, y) | ||
28 | end | ||
29 | end | ||
30 | -- if any test fails, there is no other metamethod to be called | ||
31 | error("attempt to '" .. strsub(mtname, 3) .. | ||
32 | "' a " .. type(x) .. " with a " .. type(y), 4) | ||
33 | end | ||
34 | |||
35 | |||
36 | local function checkargs (x, y, mtname) | ||
37 | local xi = toint(x) | ||
38 | local yi = toint(y) | ||
39 | if xi and yi then | ||
40 | return xi, yi | ||
41 | else | ||
42 | return trymt(x, y, mtname), nil | ||
43 | end | ||
44 | end | ||
45 | |||
46 | |||
47 | local smt = getmetatable("") | ||
48 | |||
49 | smt.__band = function (x, y) | ||
50 | local x, y = checkargs(x, y, "__band") | ||
51 | return y and x & y or x | ||
52 | end | ||
53 | |||
54 | smt.__bor = function (x, y) | ||
55 | local x, y = checkargs(x, y, "__bor") | ||
56 | return y and x | y or x | ||
57 | end | ||
58 | |||
59 | smt.__bxor = function (x, y) | ||
60 | local x, y = checkargs(x, y, "__bxor") | ||
61 | return y and x ~ y or x | ||
62 | end | ||
63 | |||
64 | smt.__shl = function (x, y) | ||
65 | local x, y = checkargs(x, y, "__shl") | ||
66 | return y and x << y or x | ||
67 | end | ||
68 | |||
69 | smt.__shr = function (x, y) | ||
70 | local x, y = checkargs(x, y, "__shr") | ||
71 | return y and x >> y or x | ||
72 | end | ||
73 | |||
74 | smt.__bnot = function (x) | ||
75 | local x, y = checkargs(x, x, "__bnot") | ||
76 | return y and ~x or x | ||
77 | end | ||
78 | |||
diff --git a/testes/calls.lua b/testes/calls.lua new file mode 100644 index 00000000..95d9d6d6 --- /dev/null +++ b/testes/calls.lua | |||
@@ -0,0 +1,435 @@ | |||
1 | -- $Id: calls.lua,v 1.66 2018/02/09 16:35:21 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print("testing functions and calls") | ||
5 | |||
6 | local debug = require "debug" | ||
7 | |||
8 | -- get the opportunity to test 'type' too ;) | ||
9 | |||
10 | assert(type(1<2) == 'boolean') | ||
11 | assert(type(true) == 'boolean' and type(false) == 'boolean') | ||
12 | assert(type(nil) == 'nil' | ||
13 | and type(-3) == 'number' | ||
14 | and type'x' == 'string' | ||
15 | and type{} == 'table' | ||
16 | and type(type) == 'function') | ||
17 | |||
18 | assert(type(assert) == type(print)) | ||
19 | function f (x) return a:x (x) end | ||
20 | assert(type(f) == 'function') | ||
21 | assert(not pcall(type)) | ||
22 | |||
23 | |||
24 | do -- test error in 'print' too... | ||
25 | local tostring = _ENV.tostring | ||
26 | |||
27 | _ENV.tostring = nil | ||
28 | local st, msg = pcall(print, 1) | ||
29 | assert(st == false and string.find(msg, "attempt to call a nil value")) | ||
30 | |||
31 | _ENV.tostring = function () return {} end | ||
32 | local st, msg = pcall(print, 1) | ||
33 | assert(st == false and string.find(msg, "must return a string")) | ||
34 | |||
35 | _ENV.tostring = tostring | ||
36 | end | ||
37 | |||
38 | |||
39 | -- testing local-function recursion | ||
40 | fact = false | ||
41 | do | ||
42 | local res = 1 | ||
43 | local function fact (n) | ||
44 | if n==0 then return res | ||
45 | else return n*fact(n-1) | ||
46 | end | ||
47 | end | ||
48 | assert(fact(5) == 120) | ||
49 | end | ||
50 | assert(fact == false) | ||
51 | |||
52 | -- testing declarations | ||
53 | a = {i = 10} | ||
54 | self = 20 | ||
55 | function a:x (x) return x+self.i end | ||
56 | function a.y (x) return x+self end | ||
57 | |||
58 | assert(a:x(1)+10 == a.y(1)) | ||
59 | |||
60 | a.t = {i=-100} | ||
61 | a["t"].x = function (self, a,b) return self.i+a+b end | ||
62 | |||
63 | assert(a.t:x(2,3) == -95) | ||
64 | |||
65 | do | ||
66 | local a = {x=0} | ||
67 | function a:add (x) self.x, a.y = self.x+x, 20; return self end | ||
68 | assert(a:add(10):add(20):add(30).x == 60 and a.y == 20) | ||
69 | end | ||
70 | |||
71 | local a = {b={c={}}} | ||
72 | |||
73 | function a.b.c.f1 (x) return x+1 end | ||
74 | function a.b.c:f2 (x,y) self[x] = y end | ||
75 | assert(a.b.c.f1(4) == 5) | ||
76 | a.b.c:f2('k', 12); assert(a.b.c.k == 12) | ||
77 | |||
78 | print('+') | ||
79 | |||
80 | t = nil -- 'declare' t | ||
81 | function f(a,b,c) local d = 'a'; t={a,b,c,d} end | ||
82 | |||
83 | f( -- this line change must be valid | ||
84 | 1,2) | ||
85 | assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a') | ||
86 | f(1,2, -- this one too | ||
87 | 3,4) | ||
88 | assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a') | ||
89 | |||
90 | function fat(x) | ||
91 | if x <= 1 then return 1 | ||
92 | else return x*load("return fat(" .. x-1 .. ")", "")() | ||
93 | end | ||
94 | end | ||
95 | |||
96 | assert(load "load 'assert(fat(6)==720)' () ")() | ||
97 | a = load('return fat(5), 3') | ||
98 | a,b = a() | ||
99 | assert(a == 120 and b == 3) | ||
100 | print('+') | ||
101 | |||
102 | function err_on_n (n) | ||
103 | if n==0 then error(); exit(1); | ||
104 | else err_on_n (n-1); exit(1); | ||
105 | end | ||
106 | end | ||
107 | |||
108 | do | ||
109 | function dummy (n) | ||
110 | if n > 0 then | ||
111 | assert(not pcall(err_on_n, n)) | ||
112 | dummy(n-1) | ||
113 | end | ||
114 | end | ||
115 | end | ||
116 | |||
117 | dummy(10) | ||
118 | |||
119 | function deep (n) | ||
120 | if n>0 then deep(n-1) end | ||
121 | end | ||
122 | deep(10) | ||
123 | deep(180) | ||
124 | |||
125 | -- testing tail calls | ||
126 | function deep (n) if n>0 then return deep(n-1) else return 101 end end | ||
127 | assert(deep(30000) == 101) | ||
128 | a = {} | ||
129 | function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end | ||
130 | assert(a:deep(30000) == 101) | ||
131 | |||
132 | do -- tail calls x varargs | ||
133 | local function foo (x, ...) local a = {...}; return x, a[1], a[2] end | ||
134 | |||
135 | local function foo1 (x) return foo(10, x, x + 1) end | ||
136 | |||
137 | local a, b, c = foo1(-2) | ||
138 | assert(a == 10 and b == -2 and c == -1) | ||
139 | |||
140 | -- tail calls x metamethods | ||
141 | local t = setmetatable({}, {__call = foo}) | ||
142 | local function foo2 (x) return t(10, x) end | ||
143 | a, b, c = foo2(100) | ||
144 | assert(a == t and b == 10 and c == 100) | ||
145 | |||
146 | a, b = (function () return foo() end)() | ||
147 | assert(a == nil and b == nil) | ||
148 | |||
149 | local X, Y, A | ||
150 | local function foo (x, y, ...) X = x; Y = y; A = {...} end | ||
151 | local function foo1 (...) return foo(...) end | ||
152 | |||
153 | local a, b, c = foo1() | ||
154 | assert(X == nil and Y == nil and #A == 0) | ||
155 | |||
156 | a, b, c = foo1(10) | ||
157 | assert(X == 10 and Y == nil and #A == 0) | ||
158 | |||
159 | a, b, c = foo1(10, 20) | ||
160 | assert(X == 10 and Y == 20 and #A == 0) | ||
161 | |||
162 | a, b, c = foo1(10, 20, 30) | ||
163 | assert(X == 10 and Y == 20 and #A == 1 and A[1] == 30) | ||
164 | end | ||
165 | |||
166 | print('+') | ||
167 | |||
168 | |||
169 | a = nil | ||
170 | (function (x) a=x end)(23) | ||
171 | assert(a == 23 and (function (x) return x*2 end)(20) == 40) | ||
172 | |||
173 | |||
174 | -- testing closures | ||
175 | |||
176 | -- fixed-point operator | ||
177 | Z = function (le) | ||
178 | local function a (f) | ||
179 | return le(function (x) return f(f)(x) end) | ||
180 | end | ||
181 | return a(a) | ||
182 | end | ||
183 | |||
184 | |||
185 | -- non-recursive factorial | ||
186 | |||
187 | F = function (f) | ||
188 | return function (n) | ||
189 | if n == 0 then return 1 | ||
190 | else return n*f(n-1) end | ||
191 | end | ||
192 | end | ||
193 | |||
194 | fat = Z(F) | ||
195 | |||
196 | assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4)) | ||
197 | |||
198 | local function g (z) | ||
199 | local function f (a,b,c,d) | ||
200 | return function (x,y) return a+b+c+d+a+x+y+z end | ||
201 | end | ||
202 | return f(z,z+1,z+2,z+3) | ||
203 | end | ||
204 | |||
205 | f = g(10) | ||
206 | assert(f(9, 16) == 10+11+12+13+10+9+16+10) | ||
207 | |||
208 | Z, F, f = nil | ||
209 | print('+') | ||
210 | |||
211 | -- testing multiple returns | ||
212 | |||
213 | function unlpack (t, i) | ||
214 | i = i or 1 | ||
215 | if (i <= #t) then | ||
216 | return t[i], unlpack(t, i+1) | ||
217 | end | ||
218 | end | ||
219 | |||
220 | function equaltab (t1, t2) | ||
221 | assert(#t1 == #t2) | ||
222 | for i = 1, #t1 do | ||
223 | assert(t1[i] == t2[i]) | ||
224 | end | ||
225 | end | ||
226 | |||
227 | local pack = function (...) return (table.pack(...)) end | ||
228 | |||
229 | function f() return 1,2,30,4 end | ||
230 | function ret2 (a,b) return a,b end | ||
231 | |||
232 | local a,b,c,d = unlpack{1,2,3} | ||
233 | assert(a==1 and b==2 and c==3 and d==nil) | ||
234 | a = {1,2,3,4,false,10,'alo',false,assert} | ||
235 | equaltab(pack(unlpack(a)), a) | ||
236 | equaltab(pack(unlpack(a), -1), {1,-1}) | ||
237 | a,b,c,d = ret2(f()), ret2(f()) | ||
238 | assert(a==1 and b==1 and c==2 and d==nil) | ||
239 | a,b,c,d = unlpack(pack(ret2(f()), ret2(f()))) | ||
240 | assert(a==1 and b==1 and c==2 and d==nil) | ||
241 | a,b,c,d = unlpack(pack(ret2(f()), (ret2(f())))) | ||
242 | assert(a==1 and b==1 and c==nil and d==nil) | ||
243 | |||
244 | a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}} | ||
245 | assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b") | ||
246 | |||
247 | |||
248 | -- testing calls with 'incorrect' arguments | ||
249 | rawget({}, "x", 1) | ||
250 | rawset({}, "x", 1, 2) | ||
251 | assert(math.sin(1,2) == math.sin(1)) | ||
252 | table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg") | ||
253 | |||
254 | |||
255 | -- test for generic load | ||
256 | local x = "-- a comment\0\0\0\n x = 10 + \n23; \ | ||
257 | local a = function () x = 'hi' end; \ | ||
258 | return '\0'" | ||
259 | function read1 (x) | ||
260 | local i = 0 | ||
261 | return function () | ||
262 | collectgarbage() | ||
263 | i=i+1 | ||
264 | return string.sub(x, i, i) | ||
265 | end | ||
266 | end | ||
267 | |||
268 | function cannotload (msg, a,b) | ||
269 | assert(not a and string.find(b, msg)) | ||
270 | end | ||
271 | |||
272 | a = assert(load(read1(x), "modname", "t", _G)) | ||
273 | assert(a() == "\0" and _G.x == 33) | ||
274 | assert(debug.getinfo(a).source == "modname") | ||
275 | -- cannot read text in binary mode | ||
276 | cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {})) | ||
277 | cannotload("attempt to load a text chunk", load(x, "modname", "b")) | ||
278 | |||
279 | a = assert(load(function () return nil end)) | ||
280 | a() -- empty chunk | ||
281 | |||
282 | assert(not load(function () return true end)) | ||
283 | |||
284 | |||
285 | -- small bug | ||
286 | local t = {nil, "return ", "3"} | ||
287 | f, msg = load(function () return table.remove(t, 1) end) | ||
288 | assert(f() == nil) -- should read the empty chunk | ||
289 | |||
290 | -- another small bug (in 5.2.1) | ||
291 | f = load(string.dump(function () return 1 end), nil, "b", {}) | ||
292 | assert(type(f) == "function" and f() == 1) | ||
293 | |||
294 | |||
295 | x = string.dump(load("x = 1; return x")) | ||
296 | a = assert(load(read1(x), nil, "b")) | ||
297 | assert(a() == 1 and _G.x == 1) | ||
298 | cannotload("attempt to load a binary chunk", load(read1(x), nil, "t")) | ||
299 | cannotload("attempt to load a binary chunk", load(x, nil, "t")) | ||
300 | |||
301 | assert(not pcall(string.dump, print)) -- no dump of C functions | ||
302 | |||
303 | cannotload("unexpected symbol", load(read1("*a = 123"))) | ||
304 | cannotload("unexpected symbol", load("*a = 123")) | ||
305 | cannotload("hhi", load(function () error("hhi") end)) | ||
306 | |||
307 | -- any value is valid for _ENV | ||
308 | assert(load("return _ENV", nil, nil, 123)() == 123) | ||
309 | |||
310 | |||
311 | -- load when _ENV is not first upvalue | ||
312 | local x; XX = 123 | ||
313 | local function h () | ||
314 | local y=x -- use 'x', so that it becomes 1st upvalue | ||
315 | return XX -- global name | ||
316 | end | ||
317 | local d = string.dump(h) | ||
318 | x = load(d, "", "b") | ||
319 | assert(debug.getupvalue(x, 2) == '_ENV') | ||
320 | debug.setupvalue(x, 2, _G) | ||
321 | assert(x() == 123) | ||
322 | |||
323 | assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17) | ||
324 | |||
325 | |||
326 | -- test generic load with nested functions | ||
327 | x = [[ | ||
328 | return function (x) | ||
329 | return function (y) | ||
330 | return function (z) | ||
331 | return x+y+z | ||
332 | end | ||
333 | end | ||
334 | end | ||
335 | ]] | ||
336 | |||
337 | a = assert(load(read1(x))) | ||
338 | assert(a()(2)(3)(10) == 15) | ||
339 | |||
340 | |||
341 | -- test for dump/undump with upvalues | ||
342 | local a, b = 20, 30 | ||
343 | x = load(string.dump(function (x) | ||
344 | if x == "set" then a = 10+b; b = b+1 else | ||
345 | return a | ||
346 | end | ||
347 | end), "", "b", nil) | ||
348 | assert(x() == nil) | ||
349 | assert(debug.setupvalue(x, 1, "hi") == "a") | ||
350 | assert(x() == "hi") | ||
351 | assert(debug.setupvalue(x, 2, 13) == "b") | ||
352 | assert(not debug.setupvalue(x, 3, 10)) -- only 2 upvalues | ||
353 | x("set") | ||
354 | assert(x() == 23) | ||
355 | x("set") | ||
356 | assert(x() == 24) | ||
357 | |||
358 | -- test for dump/undump with many upvalues | ||
359 | do | ||
360 | local nup = 200 -- maximum number of local variables | ||
361 | local prog = {"local a1"} | ||
362 | for i = 2, nup do prog[#prog + 1] = ", a" .. i end | ||
363 | prog[#prog + 1] = " = 1" | ||
364 | for i = 2, nup do prog[#prog + 1] = ", " .. i end | ||
365 | local sum = 1 | ||
366 | prog[#prog + 1] = "; return function () return a1" | ||
367 | for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end | ||
368 | prog[#prog + 1] = " end" | ||
369 | prog = table.concat(prog) | ||
370 | local f = assert(load(prog))() | ||
371 | assert(f() == sum) | ||
372 | |||
373 | f = load(string.dump(f)) -- main chunk now has many upvalues | ||
374 | local a = 10 | ||
375 | local h = function () return a end | ||
376 | for i = 1, nup do | ||
377 | debug.upvaluejoin(f, i, h, 1) | ||
378 | end | ||
379 | assert(f() == 10 * nup) | ||
380 | end | ||
381 | |||
382 | -- test for long method names | ||
383 | do | ||
384 | local t = {x = 1} | ||
385 | function t:_012345678901234567890123456789012345678901234567890123456789 () | ||
386 | return self.x | ||
387 | end | ||
388 | assert(t:_012345678901234567890123456789012345678901234567890123456789() == 1) | ||
389 | end | ||
390 | |||
391 | |||
392 | -- test for bug in parameter adjustment | ||
393 | assert((function () return nil end)(4) == nil) | ||
394 | assert((function () local a; return a end)(4) == nil) | ||
395 | assert((function (a) return a end)() == nil) | ||
396 | |||
397 | |||
398 | print("testing binary chunks") | ||
399 | do | ||
400 | local header = string.pack("c4BBc6BBBBBj", | ||
401 | "\27Lua", -- signature | ||
402 | 5*16 + 4, -- version 5.4 | ||
403 | 0, -- format | ||
404 | "\x19\x93\r\n\x1a\n", -- data | ||
405 | string.packsize("i"), -- sizeof(int) | ||
406 | string.packsize("T"), -- sizeof(size_t) | ||
407 | 4, -- size of instruction | ||
408 | string.packsize("j"), -- sizeof(lua integer) | ||
409 | string.packsize("n"), -- sizeof(lua number) | ||
410 | 0x5678 -- LUAC_INT | ||
411 | -- LUAC_NUM may not have a unique binary representation (padding...) | ||
412 | ) | ||
413 | local c = string.dump(function () local a = 1; local b = 3; return a+b*3 end) | ||
414 | |||
415 | assert(string.sub(c, 1, #header) == header) | ||
416 | |||
417 | -- corrupted header | ||
418 | for i = 1, #header do | ||
419 | local s = string.sub(c, 1, i - 1) .. | ||
420 | string.char(string.byte(string.sub(c, i, i)) + 1) .. | ||
421 | string.sub(c, i + 1, -1) | ||
422 | assert(#s == #c) | ||
423 | assert(not load(s)) | ||
424 | end | ||
425 | |||
426 | -- loading truncated binary chunks | ||
427 | for i = 1, #c - 1 do | ||
428 | local st, msg = load(string.sub(c, 1, i)) | ||
429 | assert(not st and string.find(msg, "truncated")) | ||
430 | end | ||
431 | assert(assert(load(c))() == 10) | ||
432 | end | ||
433 | |||
434 | print('OK') | ||
435 | return deep | ||
diff --git a/testes/closure.lua b/testes/closure.lua new file mode 100644 index 00000000..79da3cc0 --- /dev/null +++ b/testes/closure.lua | |||
@@ -0,0 +1,271 @@ | |||
1 | -- $Id: closure.lua,v 1.62 2018/03/12 14:19:36 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print "testing closures" | ||
5 | |||
6 | local A,B = 0,{g=10} | ||
7 | function f(x) | ||
8 | local a = {} | ||
9 | for i=1,1000 do | ||
10 | local y = 0 | ||
11 | do | ||
12 | a[i] = function () B.g = B.g+1; y = y+x; return y+A end | ||
13 | end | ||
14 | end | ||
15 | local dummy = function () return a[A] end | ||
16 | collectgarbage() | ||
17 | A = 1; assert(dummy() == a[1]); A = 0; | ||
18 | assert(a[1]() == x) | ||
19 | assert(a[3]() == x) | ||
20 | collectgarbage() | ||
21 | assert(B.g == 12) | ||
22 | return a | ||
23 | end | ||
24 | |||
25 | local a = f(10) | ||
26 | -- force a GC in this level | ||
27 | local x = {[1] = {}} -- to detect a GC | ||
28 | setmetatable(x, {__mode = 'kv'}) | ||
29 | while x[1] do -- repeat until GC | ||
30 | local a = A..A..A..A -- create garbage | ||
31 | A = A+1 | ||
32 | end | ||
33 | assert(a[1]() == 20+A) | ||
34 | assert(a[1]() == 30+A) | ||
35 | assert(a[2]() == 10+A) | ||
36 | collectgarbage() | ||
37 | assert(a[2]() == 20+A) | ||
38 | assert(a[2]() == 30+A) | ||
39 | assert(a[3]() == 20+A) | ||
40 | assert(a[8]() == 10+A) | ||
41 | assert(getmetatable(x).__mode == 'kv') | ||
42 | assert(B.g == 19) | ||
43 | |||
44 | |||
45 | -- testing equality | ||
46 | a = {} | ||
47 | collectgarbage"stop" | ||
48 | for i = 1, 5 do a[i] = function (x) return x + a + _ENV end end | ||
49 | collectgarbage"restart" | ||
50 | assert(a[3] == a[4] and a[4] == a[5]) | ||
51 | |||
52 | for i = 1, 5 do a[i] = function (x) return i + a + _ENV end end | ||
53 | assert(a[3] ~= a[4] and a[4] ~= a[5]) | ||
54 | |||
55 | local function f() | ||
56 | return function (x) return math.sin(_ENV[x]) end | ||
57 | end | ||
58 | assert(f() == f()) | ||
59 | |||
60 | |||
61 | -- testing closures with 'for' control variable | ||
62 | a = {} | ||
63 | for i=1,10 do | ||
64 | a[i] = {set = function(x) i=x end, get = function () return i end} | ||
65 | if i == 3 then break end | ||
66 | end | ||
67 | assert(a[4] == undef) | ||
68 | a[1].set(10) | ||
69 | assert(a[2].get() == 2) | ||
70 | a[2].set('a') | ||
71 | assert(a[3].get() == 3) | ||
72 | assert(a[2].get() == 'a') | ||
73 | |||
74 | a = {} | ||
75 | local t = {"a", "b"} | ||
76 | for i = 1, #t do | ||
77 | local k = t[i] | ||
78 | a[i] = {set = function(x, y) i=x; k=y end, | ||
79 | get = function () return i, k end} | ||
80 | if i == 2 then break end | ||
81 | end | ||
82 | a[1].set(10, 20) | ||
83 | local r,s = a[2].get() | ||
84 | assert(r == 2 and s == 'b') | ||
85 | r,s = a[1].get() | ||
86 | assert(r == 10 and s == 20) | ||
87 | a[2].set('a', 'b') | ||
88 | r,s = a[2].get() | ||
89 | assert(r == "a" and s == "b") | ||
90 | |||
91 | |||
92 | -- testing closures with 'for' control variable x break | ||
93 | for i=1,3 do | ||
94 | f = function () return i end | ||
95 | break | ||
96 | end | ||
97 | assert(f() == 1) | ||
98 | |||
99 | for k = 1, #t do | ||
100 | local v = t[k] | ||
101 | f = function () return k, v end | ||
102 | break | ||
103 | end | ||
104 | assert(({f()})[1] == 1) | ||
105 | assert(({f()})[2] == "a") | ||
106 | |||
107 | |||
108 | -- testing closure x break x return x errors | ||
109 | |||
110 | local b | ||
111 | function f(x) | ||
112 | local first = 1 | ||
113 | while 1 do | ||
114 | if x == 3 and not first then return end | ||
115 | local a = 'xuxu' | ||
116 | b = function (op, y) | ||
117 | if op == 'set' then | ||
118 | a = x+y | ||
119 | else | ||
120 | return a | ||
121 | end | ||
122 | end | ||
123 | if x == 1 then do break end | ||
124 | elseif x == 2 then return | ||
125 | else if x ~= 3 then error() end | ||
126 | end | ||
127 | first = nil | ||
128 | end | ||
129 | end | ||
130 | |||
131 | for i=1,3 do | ||
132 | f(i) | ||
133 | assert(b('get') == 'xuxu') | ||
134 | b('set', 10); assert(b('get') == 10+i) | ||
135 | b = nil | ||
136 | end | ||
137 | |||
138 | pcall(f, 4); | ||
139 | assert(b('get') == 'xuxu') | ||
140 | b('set', 10); assert(b('get') == 14) | ||
141 | |||
142 | |||
143 | local w | ||
144 | -- testing multi-level closure | ||
145 | function f(x) | ||
146 | return function (y) | ||
147 | return function (z) return w+x+y+z end | ||
148 | end | ||
149 | end | ||
150 | |||
151 | y = f(10) | ||
152 | w = 1.345 | ||
153 | assert(y(20)(30) == 60+w) | ||
154 | |||
155 | |||
156 | -- testing closures x break | ||
157 | do | ||
158 | local X, Y | ||
159 | local a = math.sin(0) | ||
160 | |||
161 | while a do | ||
162 | local b = 10 | ||
163 | X = function () return b end -- closure with upvalue | ||
164 | if a then break end | ||
165 | end | ||
166 | |||
167 | do | ||
168 | local b = 20 | ||
169 | Y = function () return b end -- closure with upvalue | ||
170 | end | ||
171 | |||
172 | -- upvalues must be different | ||
173 | assert(X() == 10 and Y() == 20) | ||
174 | end | ||
175 | |||
176 | |||
177 | -- testing closures x repeat-until | ||
178 | |||
179 | local a = {} | ||
180 | local i = 1 | ||
181 | repeat | ||
182 | local x = i | ||
183 | a[i] = function () i = x+1; return x end | ||
184 | until i > 10 or a[i]() ~= x | ||
185 | assert(i == 11 and a[1]() == 1 and a[3]() == 3 and i == 4) | ||
186 | |||
187 | |||
188 | -- testing closures created in 'then' and 'else' parts of 'if's | ||
189 | a = {} | ||
190 | for i = 1, 10 do | ||
191 | if i % 3 == 0 then | ||
192 | local y = 0 | ||
193 | a[i] = function (x) local t = y; y = x; return t end | ||
194 | elseif i % 3 == 1 then | ||
195 | goto L1 | ||
196 | error'not here' | ||
197 | ::L1:: | ||
198 | local y = 1 | ||
199 | a[i] = function (x) local t = y; y = x; return t end | ||
200 | elseif i % 3 == 2 then | ||
201 | local t | ||
202 | goto l4 | ||
203 | ::l4a:: a[i] = t; goto l4b | ||
204 | error("should never be here!") | ||
205 | ::l4:: | ||
206 | local y = 2 | ||
207 | t = function (x) local t = y; y = x; return t end | ||
208 | goto l4a | ||
209 | error("should never be here!") | ||
210 | ::l4b:: | ||
211 | end | ||
212 | end | ||
213 | |||
214 | for i = 1, 10 do | ||
215 | assert(a[i](i * 10) == i % 3 and a[i]() == i * 10) | ||
216 | end | ||
217 | |||
218 | print'+' | ||
219 | |||
220 | |||
221 | -- test for correctly closing upvalues in tail calls of vararg functions | ||
222 | local function t () | ||
223 | local function c(a,b) assert(a=="test" and b=="OK") end | ||
224 | local function v(f, ...) c("test", f() ~= 1 and "FAILED" or "OK") end | ||
225 | local x = 1 | ||
226 | return v(function() return x end) | ||
227 | end | ||
228 | t() | ||
229 | |||
230 | |||
231 | -- test for debug manipulation of upvalues | ||
232 | local debug = require'debug' | ||
233 | |||
234 | do | ||
235 | local a , b, c = 3, 5, 7 | ||
236 | foo1 = function () return a+b end; | ||
237 | foo2 = function () return b+a end; | ||
238 | do | ||
239 | local a = 10 | ||
240 | foo3 = function () return a+b end; | ||
241 | end | ||
242 | end | ||
243 | |||
244 | assert(debug.upvalueid(foo1, 1)) | ||
245 | assert(debug.upvalueid(foo1, 2)) | ||
246 | assert(not pcall(debug.upvalueid, foo1, 3)) | ||
247 | assert(debug.upvalueid(foo1, 1) == debug.upvalueid(foo2, 2)) | ||
248 | assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo2, 1)) | ||
249 | assert(debug.upvalueid(foo3, 1)) | ||
250 | assert(debug.upvalueid(foo1, 1) ~= debug.upvalueid(foo3, 1)) | ||
251 | assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo3, 2)) | ||
252 | |||
253 | assert(debug.upvalueid(string.gmatch("x", "x"), 1) ~= nil) | ||
254 | |||
255 | assert(foo1() == 3 + 5 and foo2() == 5 + 3) | ||
256 | debug.upvaluejoin(foo1, 2, foo2, 2) | ||
257 | assert(foo1() == 3 + 3 and foo2() == 5 + 3) | ||
258 | assert(foo3() == 10 + 5) | ||
259 | debug.upvaluejoin(foo3, 2, foo2, 1) | ||
260 | assert(foo3() == 10 + 5) | ||
261 | debug.upvaluejoin(foo3, 2, foo2, 2) | ||
262 | assert(foo3() == 10 + 3) | ||
263 | |||
264 | assert(not pcall(debug.upvaluejoin, foo1, 3, foo2, 1)) | ||
265 | assert(not pcall(debug.upvaluejoin, foo1, 1, foo2, 3)) | ||
266 | assert(not pcall(debug.upvaluejoin, foo1, 0, foo2, 1)) | ||
267 | assert(not pcall(debug.upvaluejoin, print, 1, foo2, 1)) | ||
268 | assert(not pcall(debug.upvaluejoin, {}, 1, foo2, 1)) | ||
269 | assert(not pcall(debug.upvaluejoin, foo1, 1, print, 1)) | ||
270 | |||
271 | print'OK' | ||
diff --git a/testes/code.lua b/testes/code.lua new file mode 100644 index 00000000..e39c62ad --- /dev/null +++ b/testes/code.lua | |||
@@ -0,0 +1,347 @@ | |||
1 | -- $Id: code.lua,v 1.55 2018/03/12 14:19:36 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | if T==nil then | ||
5 | (Message or print)('\n >>> testC not active: skipping opcode tests <<<\n') | ||
6 | return | ||
7 | end | ||
8 | print "testing code generation and optimizations" | ||
9 | |||
10 | |||
11 | -- this code gave an error for the code checker | ||
12 | do | ||
13 | local function f (a) | ||
14 | for k,v,w in a do end | ||
15 | end | ||
16 | end | ||
17 | |||
18 | |||
19 | -- testing reuse in constant table | ||
20 | local function checkKlist (func, list) | ||
21 | local k = T.listk(func) | ||
22 | assert(#k == #list) | ||
23 | for i = 1, #k do | ||
24 | assert(k[i] == list[i] and math.type(k[i]) == math.type(list[i])) | ||
25 | end | ||
26 | end | ||
27 | |||
28 | local function foo () | ||
29 | local a | ||
30 | a = 3; | ||
31 | a = 0; a = 0.0; a = -7 + 7 | ||
32 | a = 3.78/4; a = 3.78/4 | ||
33 | a = -3.78/4; a = 3.78/4; a = -3.78/4 | ||
34 | a = -3.79/4; a = 0.0; a = -0; | ||
35 | a = 3; a = 3.0; a = 3; a = 3.0 | ||
36 | end | ||
37 | |||
38 | checkKlist(foo, {3.78/4, -3.78/4, -3.79/4}) | ||
39 | |||
40 | |||
41 | -- testing opcodes | ||
42 | |||
43 | function check (f, ...) | ||
44 | local arg = {...} | ||
45 | local c = T.listcode(f) | ||
46 | for i=1, #arg do | ||
47 | local opcode = string.match(c[i], "%u%w+") | ||
48 | -- print(arg[i], opcode) | ||
49 | assert(arg[i] == opcode) | ||
50 | end | ||
51 | assert(c[#arg+2] == undef) | ||
52 | end | ||
53 | |||
54 | |||
55 | function checkequal (a, b) | ||
56 | a = T.listcode(a) | ||
57 | b = T.listcode(b) | ||
58 | for i = 1, #a do | ||
59 | a[i] = string.gsub(a[i], '%b()', '') -- remove line number | ||
60 | b[i] = string.gsub(b[i], '%b()', '') -- remove line number | ||
61 | assert(a[i] == b[i]) | ||
62 | end | ||
63 | end | ||
64 | |||
65 | |||
66 | -- some basic instructions | ||
67 | check(function () | ||
68 | (function () end){f()} | ||
69 | end, 'CLOSURE', 'NEWTABLE', 'GETTABUP', 'CALL', 'SETLIST', 'CALL', 'RETURN') | ||
70 | |||
71 | |||
72 | -- sequence of LOADNILs | ||
73 | check(function () | ||
74 | local a,b,c | ||
75 | local d; local e; | ||
76 | local f,g,h; | ||
77 | d = nil; d=nil; b=nil; a=nil; c=nil; | ||
78 | end, 'LOADNIL', 'RETURN0') | ||
79 | |||
80 | check(function () | ||
81 | local a,b,c,d = 1,1,1,1 | ||
82 | d=nil;c=nil;b=nil;a=nil | ||
83 | end, 'LOADI', 'LOADI', 'LOADI', 'LOADI', 'LOADNIL', 'RETURN0') | ||
84 | |||
85 | do | ||
86 | local a,b,c,d = 1,1,1,1 | ||
87 | d=nil;c=nil;b=nil;a=nil | ||
88 | assert(a == nil and b == nil and c == nil and d == nil) | ||
89 | end | ||
90 | |||
91 | |||
92 | -- single return | ||
93 | check (function (a,b,c) return a end, 'RETURN1') | ||
94 | |||
95 | |||
96 | -- infinite loops | ||
97 | check(function () while true do local a = -1 end end, | ||
98 | 'LOADI', 'JMP', 'RETURN0') | ||
99 | |||
100 | check(function () while 1 do local a = -1 end end, | ||
101 | 'LOADI', 'JMP', 'RETURN0') | ||
102 | |||
103 | check(function () repeat local x = 1 until true end, | ||
104 | 'LOADI', 'RETURN0') | ||
105 | |||
106 | |||
107 | -- concat optimization | ||
108 | check(function (a,b,c,d) return a..b..c..d end, | ||
109 | 'MOVE', 'MOVE', 'MOVE', 'MOVE', 'CONCAT', 'RETURN1') | ||
110 | |||
111 | -- not | ||
112 | check(function () return not not nil end, 'LOADBOOL', 'RETURN1') | ||
113 | check(function () return not not false end, 'LOADBOOL', 'RETURN1') | ||
114 | check(function () return not not true end, 'LOADBOOL', 'RETURN1') | ||
115 | check(function () return not not 1 end, 'LOADBOOL', 'RETURN1') | ||
116 | |||
117 | -- direct access to locals | ||
118 | check(function () | ||
119 | local a,b,c,d | ||
120 | a = b*a | ||
121 | c.x, a[b] = -((a + d/b - a[b]) ^ a.x), b | ||
122 | end, | ||
123 | 'LOADNIL', | ||
124 | 'MUL', | ||
125 | 'DIV', 'ADD', 'GETTABLE', 'SUB', 'GETFIELD', 'POW', | ||
126 | 'UNM', 'SETTABLE', 'SETFIELD', 'RETURN0') | ||
127 | |||
128 | |||
129 | -- direct access to constants | ||
130 | check(function () | ||
131 | local a,b | ||
132 | a.x = 3.2 | ||
133 | a.x = b | ||
134 | a[b] = 'x' | ||
135 | end, | ||
136 | 'LOADNIL', 'SETFIELD', 'SETFIELD', 'SETTABLE', 'RETURN0') | ||
137 | |||
138 | -- "get/set table" with numeric indices | ||
139 | check(function (a) | ||
140 | a[1] = a[100] | ||
141 | a[255] = a[256] | ||
142 | a[256] = 5 | ||
143 | end, | ||
144 | 'GETI', 'SETI', | ||
145 | 'LOADI', 'GETTABLE', 'SETI', | ||
146 | 'LOADI', 'SETTABLE', 'RETURN0') | ||
147 | |||
148 | check(function () | ||
149 | local a,b | ||
150 | a = a - a | ||
151 | b = a/a | ||
152 | b = 5-4 | ||
153 | end, | ||
154 | 'LOADNIL', 'SUB', 'DIV', 'LOADI', 'RETURN0') | ||
155 | |||
156 | check(function () | ||
157 | local a,b | ||
158 | a[true] = false | ||
159 | end, | ||
160 | 'LOADNIL', 'LOADBOOL', 'SETTABLE', 'RETURN0') | ||
161 | |||
162 | |||
163 | -- equalities | ||
164 | check(function (a) if a == 1 then return 2 end end, | ||
165 | 'EQI', 'JMP', 'LOADI', 'RETURN1') | ||
166 | |||
167 | check(function (a) if -4.0 == a then return 2 end end, | ||
168 | 'EQI', 'JMP', 'LOADI', 'RETURN1') | ||
169 | |||
170 | check(function (a) if a == "hi" then return 2 end end, | ||
171 | 'EQK', 'JMP', 'LOADI', 'RETURN1') | ||
172 | |||
173 | check(function (a) if a == 10000 then return 2 end end, | ||
174 | 'EQK', 'JMP', 'LOADI', 'RETURN1') -- number too large | ||
175 | |||
176 | check(function (a) if -10000 == a then return 2 end end, | ||
177 | 'EQK', 'JMP', 'LOADI', 'RETURN1') -- number too large | ||
178 | |||
179 | -- comparisons | ||
180 | |||
181 | check(function (a) if -10 <= a then return 2 end end, | ||
182 | 'GEI', 'JMP', 'LOADI', 'RETURN1') | ||
183 | |||
184 | check(function (a) if 128.0 > a then return 2 end end, | ||
185 | 'LTI', 'JMP', 'LOADI', 'RETURN1') | ||
186 | |||
187 | check(function (a) if -127.0 < a then return 2 end end, | ||
188 | 'GTI', 'JMP', 'LOADI', 'RETURN1') | ||
189 | |||
190 | check(function (a) if 10 < a then return 2 end end, | ||
191 | 'GTI', 'JMP', 'LOADI', 'RETURN1') | ||
192 | |||
193 | check(function (a) if 129 < a then return 2 end end, | ||
194 | 'LOADI', 'LT', 'JMP', 'LOADI', 'RETURN1') | ||
195 | |||
196 | check(function (a) if a >= 23.0 then return 2 end end, | ||
197 | 'GEI', 'JMP', 'LOADI', 'RETURN1') | ||
198 | |||
199 | check(function (a) if a >= 23.1 then return 2 end end, | ||
200 | 'LOADK', 'LE', 'JMP', 'LOADI', 'RETURN1') | ||
201 | |||
202 | check(function (a) if a > 2300.0 then return 2 end end, | ||
203 | 'LOADF', 'LT', 'JMP', 'LOADI', 'RETURN1') | ||
204 | |||
205 | |||
206 | -- constant folding | ||
207 | local function checkK (func, val) | ||
208 | check(func, 'LOADK', 'RETURN1') | ||
209 | local k = T.listk(func) | ||
210 | assert(#k == 1 and k[1] == val and math.type(k[1]) == math.type(val)) | ||
211 | assert(func() == val) | ||
212 | end | ||
213 | |||
214 | local function checkI (func, val) | ||
215 | check(func, 'LOADI', 'RETURN1') | ||
216 | assert(#T.listk(func) == 0) | ||
217 | assert(func() == val) | ||
218 | end | ||
219 | |||
220 | local function checkF (func, val) | ||
221 | check(func, 'LOADF', 'RETURN1') | ||
222 | assert(#T.listk(func) == 0) | ||
223 | assert(func() == val) | ||
224 | end | ||
225 | |||
226 | checkF(function () return 0.0 end, 0.0) | ||
227 | checkI(function () return 0 end, 0) | ||
228 | checkI(function () return -0//1 end, 0) | ||
229 | checkK(function () return 3^-1 end, 1/3) | ||
230 | checkK(function () return (1 + 1)^(50 + 50) end, 2^100) | ||
231 | checkK(function () return (-2)^(31 - 2) end, -0x20000000 + 0.0) | ||
232 | checkF(function () return (-3^0 + 5) // 3.0 end, 1.0) | ||
233 | checkI(function () return -3 % 5 end, 2) | ||
234 | checkF(function () return -((2.0^8 + -(-1)) % 8)/2 * 4 - 3 end, -5.0) | ||
235 | checkF(function () return -((2^8 + -(-1)) % 8)//2 * 4 - 3 end, -7.0) | ||
236 | checkI(function () return 0xF0.0 | 0xCC.0 ~ 0xAA & 0xFD end, 0xF4) | ||
237 | checkI(function () return ~(~0xFF0 | 0xFF0) end, 0) | ||
238 | checkI(function () return ~~-1024.0 end, -1024) | ||
239 | checkI(function () return ((100 << 6) << -4) >> 2 end, 100) | ||
240 | |||
241 | -- borders around MAXARG_sBx ((((1 << 17) - 1) >> 1) == 65535) | ||
242 | local sbx = ((1 << "17") - 1) >> 1 -- avoid folding | ||
243 | checkI(function () return 65535 end, sbx) | ||
244 | checkI(function () return -65535 end, -sbx) | ||
245 | checkI(function () return 65536 end, sbx + 1) | ||
246 | checkK(function () return 65537 end, sbx + 2) | ||
247 | checkK(function () return -65536 end, -(sbx + 1)) | ||
248 | |||
249 | checkF(function () return 65535.0 end, sbx + 0.0) | ||
250 | checkF(function () return -65535.0 end, -sbx + 0.0) | ||
251 | checkF(function () return 65536.0 end, (sbx + 1.0)) | ||
252 | checkK(function () return 65537.0 end, (sbx + 2.0)) | ||
253 | checkK(function () return -65536.0 end, -(sbx + 1.0)) | ||
254 | |||
255 | |||
256 | -- immediate operands | ||
257 | check(function (x) return x + 1 end, 'ADDI', 'RETURN1') | ||
258 | check(function (x) return 128 + x end, 'ADDI', 'RETURN1') | ||
259 | check(function (x) return x * -127 end, 'MULI', 'RETURN1') | ||
260 | check(function (x) return 20 * x end, 'MULI', 'RETURN1') | ||
261 | check(function (x) return x ^ -2 end, 'POWI', 'RETURN1') | ||
262 | check(function (x) return x / 40 end, 'DIVI', 'RETURN1') | ||
263 | check(function (x) return x // 1 end, 'IDIVI', 'RETURN1') | ||
264 | check(function (x) return x % (100 - 10) end, 'MODI', 'RETURN1') | ||
265 | check(function (x) return 1 << x end, 'SHLI', 'RETURN1') | ||
266 | check(function (x) return x << 2 end, 'SHRI', 'RETURN1') | ||
267 | check(function (x) return x >> 2 end, 'SHRI', 'RETURN1') | ||
268 | check(function (x) return x & 1 end, 'BANDK', 'RETURN1') | ||
269 | check(function (x) return 10 | x end, 'BORK', 'RETURN1') | ||
270 | check(function (x) return -10 ~ x end, 'BXORK', 'RETURN1') | ||
271 | |||
272 | -- no foldings (and immediate operands) | ||
273 | check(function () return -0.0 end, 'LOADF', 'UNM', 'RETURN1') | ||
274 | check(function () return 3/0 end, 'LOADI', 'DIVI', 'RETURN1') | ||
275 | check(function () return 0%0 end, 'LOADI', 'MODI', 'RETURN1') | ||
276 | check(function () return -4//0 end, 'LOADI', 'IDIVI', 'RETURN1') | ||
277 | check(function (x) return x >> 2.0 end, 'LOADF', 'SHR', 'RETURN1') | ||
278 | check(function (x) return x & 2.0 end, 'LOADF', 'BAND', 'RETURN1') | ||
279 | |||
280 | -- basic 'for' loops | ||
281 | check(function () for i = -10, 10.5 do end end, | ||
282 | 'LOADI', 'LOADK', 'LOADI', 'FORPREP1', 'FORLOOP1', 'RETURN0') | ||
283 | check(function () for i = 0xfffffff, 10.0, 1 do end end, | ||
284 | 'LOADK', 'LOADF', 'LOADI', 'FORPREP1', 'FORLOOP1', 'RETURN0') | ||
285 | |||
286 | -- bug in constant folding for 5.1 | ||
287 | check(function () return -nil end, 'LOADNIL', 'UNM', 'RETURN1') | ||
288 | |||
289 | |||
290 | check(function () | ||
291 | local a,b,c | ||
292 | b[c], a = c, b | ||
293 | b[a], a = c, b | ||
294 | a, b = c, a | ||
295 | a = a | ||
296 | end, | ||
297 | 'LOADNIL', | ||
298 | 'MOVE', 'MOVE', 'SETTABLE', | ||
299 | 'MOVE', 'MOVE', 'MOVE', 'SETTABLE', | ||
300 | 'MOVE', 'MOVE', 'MOVE', | ||
301 | -- no code for a = a | ||
302 | 'RETURN0') | ||
303 | |||
304 | |||
305 | -- x == nil , x ~= nil | ||
306 | -- checkequal(function (b) if (a==nil) then a=1 end; if a~=nil then a=1 end end, | ||
307 | -- function () if (a==9) then a=1 end; if a~=9 then a=1 end end) | ||
308 | |||
309 | -- check(function () if a==nil then a='a' end end, | ||
310 | -- 'GETTABUP', 'EQ', 'JMP', 'SETTABUP', 'RETURN') | ||
311 | |||
312 | do -- tests for table access in upvalues | ||
313 | local t | ||
314 | check(function () t.x = t.y end, 'GETTABUP', 'SETTABUP') | ||
315 | check(function (a) t[a()] = t[a()] end, | ||
316 | 'MOVE', 'CALL', 'GETUPVAL', 'MOVE', 'CALL', | ||
317 | 'GETUPVAL', 'GETTABLE', 'SETTABLE') | ||
318 | end | ||
319 | |||
320 | -- de morgan | ||
321 | checkequal(function () local a; if not (a or b) then b=a end end, | ||
322 | function () local a; if (not a and not b) then b=a end end) | ||
323 | |||
324 | checkequal(function (l) local a; return 0 <= a and a <= l end, | ||
325 | function (l) local a; return not (not(a >= 0) or not(a <= l)) end) | ||
326 | |||
327 | |||
328 | -- if-goto optimizations | ||
329 | check(function (a, b, c, d, e) | ||
330 | if a == b then goto l1; | ||
331 | elseif a == c then goto l2; | ||
332 | elseif a == d then goto l2; | ||
333 | else if a == e then goto l3; | ||
334 | else goto l3 | ||
335 | end | ||
336 | end | ||
337 | ::l1:: ::l2:: ::l3:: ::l4:: | ||
338 | end, 'EQ', 'JMP', 'EQ', 'JMP', 'EQ', 'JMP', 'EQ', 'JMP', 'JMP', | ||
339 | 'CLOSE', 'CLOSE', 'CLOSE', 'CLOSE', 'RETURN0') | ||
340 | |||
341 | checkequal( | ||
342 | function (a) while a < 10 do a = a + 1 end end, | ||
343 | function (a) while true do if not(a < 10) then break end; a = a + 1; end end | ||
344 | ) | ||
345 | |||
346 | print 'OK' | ||
347 | |||
diff --git a/testes/constructs.lua b/testes/constructs.lua new file mode 100644 index 00000000..7796c46f --- /dev/null +++ b/testes/constructs.lua | |||
@@ -0,0 +1,302 @@ | |||
1 | -- $Id: constructs.lua,v 1.43 2018/02/21 17:41:07 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | ;;print "testing syntax";; | ||
5 | |||
6 | local debug = require "debug" | ||
7 | |||
8 | |||
9 | local function checkload (s, msg) | ||
10 | assert(string.find(select(2, load(s)), msg)) | ||
11 | end | ||
12 | |||
13 | -- testing semicollons | ||
14 | do ;;; end | ||
15 | ; do ; a = 3; assert(a == 3) end; | ||
16 | ; | ||
17 | |||
18 | |||
19 | -- invalid operations should not raise errors when not executed | ||
20 | if false then a = 3 // 0; a = 0 % 0 end | ||
21 | |||
22 | |||
23 | -- testing priorities | ||
24 | |||
25 | assert(2^3^2 == 2^(3^2)); | ||
26 | assert(2^3*4 == (2^3)*4); | ||
27 | assert(2.0^-2 == 1/4 and -2^- -2 == - - -4); | ||
28 | assert(not nil and 2 and not(2>3 or 3<2)); | ||
29 | assert(-3-1-5 == 0+0-9); | ||
30 | assert(-2^2 == -4 and (-2)^2 == 4 and 2*2-3-1 == 0); | ||
31 | assert(-3%5 == 2 and -3+5 == 2) | ||
32 | assert(2*1+3/3 == 3 and 1+2 .. 3*1 == "33"); | ||
33 | assert(not(2+1 > 3*1) and "a".."b" > "a"); | ||
34 | |||
35 | assert(0xF0 | 0xCC ~ 0xAA & 0xFD == 0xF4) | ||
36 | assert(0xFD & 0xAA ~ 0xCC | 0xF0 == 0xF4) | ||
37 | assert(0xF0 & 0x0F + 1 == 0x10) | ||
38 | |||
39 | assert(3^4//2^3//5 == 2) | ||
40 | |||
41 | assert(-3+4*5//2^3^2//9+4%10/3 == (-3)+(((4*5)//(2^(3^2)))//9)+((4%10)/3)) | ||
42 | |||
43 | assert(not ((true or false) and nil)) | ||
44 | assert( true or false and nil) | ||
45 | |||
46 | -- old bug | ||
47 | assert((((1 or false) and true) or false) == true) | ||
48 | assert((((nil and true) or false) and true) == false) | ||
49 | |||
50 | local a,b = 1,nil; | ||
51 | assert(-(1 or 2) == -1 and (1 and 2)+(-1.25 or -4) == 0.75); | ||
52 | x = ((b or a)+1 == 2 and (10 or a)+1 == 11); assert(x); | ||
53 | x = (((2<3) or 1) == true and (2<3 and 4) == 4); assert(x); | ||
54 | |||
55 | x,y=1,2; | ||
56 | assert((x>y) and x or y == 2); | ||
57 | x,y=2,1; | ||
58 | assert((x>y) and x or y == 2); | ||
59 | |||
60 | assert(1234567890 == tonumber('1234567890') and 1234567890+1 == 1234567891) | ||
61 | |||
62 | |||
63 | -- silly loops | ||
64 | repeat until 1; repeat until true; | ||
65 | while false do end; while nil do end; | ||
66 | |||
67 | do -- test old bug (first name could not be an `upvalue') | ||
68 | local a; function f(x) x={a=1}; x={x=1}; x={G=1} end | ||
69 | end | ||
70 | |||
71 | function f (i) | ||
72 | if type(i) ~= 'number' then return i,'jojo'; end; | ||
73 | if i > 0 then return i, f(i-1); end; | ||
74 | end | ||
75 | |||
76 | x = {f(3), f(5), f(10);}; | ||
77 | assert(x[1] == 3 and x[2] == 5 and x[3] == 10 and x[4] == 9 and x[12] == 1); | ||
78 | assert(x[nil] == nil) | ||
79 | x = {f'alo', f'xixi', nil}; | ||
80 | assert(x[1] == 'alo' and x[2] == 'xixi' and x[3] == nil); | ||
81 | x = {f'alo'..'xixi'}; | ||
82 | assert(x[1] == 'aloxixi') | ||
83 | x = {f{}} | ||
84 | assert(x[2] == 'jojo' and type(x[1]) == 'table') | ||
85 | |||
86 | |||
87 | local f = function (i) | ||
88 | if i < 10 then return 'a'; | ||
89 | elseif i < 20 then return 'b'; | ||
90 | elseif i < 30 then return 'c'; | ||
91 | end; | ||
92 | end | ||
93 | |||
94 | assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == nil) | ||
95 | |||
96 | for i=1,1000 do break; end; | ||
97 | n=100; | ||
98 | i=3; | ||
99 | t = {}; | ||
100 | a=nil | ||
101 | while not a do | ||
102 | a=0; for i=1,n do for i=i,1,-1 do a=a+1; t[i]=1; end; end; | ||
103 | end | ||
104 | assert(a == n*(n+1)/2 and i==3); | ||
105 | assert(t[1] and t[n] and not t[0] and not t[n+1]) | ||
106 | |||
107 | function f(b) | ||
108 | local x = 1; | ||
109 | repeat | ||
110 | local a; | ||
111 | if b==1 then local b=1; x=10; break | ||
112 | elseif b==2 then x=20; break; | ||
113 | elseif b==3 then x=30; | ||
114 | else local a,b,c,d=math.sin(1); x=x+1; | ||
115 | end | ||
116 | until x>=12; | ||
117 | return x; | ||
118 | end; | ||
119 | |||
120 | assert(f(1) == 10 and f(2) == 20 and f(3) == 30 and f(4)==12) | ||
121 | |||
122 | |||
123 | local f = function (i) | ||
124 | if i < 10 then return 'a' | ||
125 | elseif i < 20 then return 'b' | ||
126 | elseif i < 30 then return 'c' | ||
127 | else return 8 | ||
128 | end | ||
129 | end | ||
130 | |||
131 | assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == 8) | ||
132 | |||
133 | local a, b = nil, 23 | ||
134 | x = {f(100)*2+3 or a, a or b+2} | ||
135 | assert(x[1] == 19 and x[2] == 25) | ||
136 | x = {f=2+3 or a, a = b+2} | ||
137 | assert(x.f == 5 and x.a == 25) | ||
138 | |||
139 | a={y=1} | ||
140 | x = {a.y} | ||
141 | assert(x[1] == 1) | ||
142 | |||
143 | function f(i) | ||
144 | while 1 do | ||
145 | if i>0 then i=i-1; | ||
146 | else return; end; | ||
147 | end; | ||
148 | end; | ||
149 | |||
150 | function g(i) | ||
151 | while 1 do | ||
152 | if i>0 then i=i-1 | ||
153 | else return end | ||
154 | end | ||
155 | end | ||
156 | |||
157 | f(10); g(10); | ||
158 | |||
159 | do | ||
160 | function f () return 1,2,3; end | ||
161 | local a, b, c = f(); | ||
162 | assert(a==1 and b==2 and c==3) | ||
163 | a, b, c = (f()); | ||
164 | assert(a==1 and b==nil and c==nil) | ||
165 | end | ||
166 | |||
167 | local a,b = 3 and f(); | ||
168 | assert(a==1 and b==nil) | ||
169 | |||
170 | function g() f(); return; end; | ||
171 | assert(g() == nil) | ||
172 | function g() return nil or f() end | ||
173 | a,b = g() | ||
174 | assert(a==1 and b==nil) | ||
175 | |||
176 | print'+'; | ||
177 | |||
178 | |||
179 | f = [[ | ||
180 | return function ( a , b , c , d , e ) | ||
181 | local x = a >= b or c or ( d and e ) or nil | ||
182 | return x | ||
183 | end , { a = 1 , b = 2 >= 1 , } or { 1 }; | ||
184 | ]] | ||
185 | f = string.gsub(f, "%s+", "\n"); -- force a SETLINE between opcodes | ||
186 | f,a = load(f)(); | ||
187 | assert(a.a == 1 and a.b) | ||
188 | |||
189 | function g (a,b,c,d,e) | ||
190 | if not (a>=b or c or d and e or nil) then return 0; else return 1; end; | ||
191 | end | ||
192 | |||
193 | function h (a,b,c,d,e) | ||
194 | while (a>=b or c or (d and e) or nil) do return 1; end; | ||
195 | return 0; | ||
196 | end; | ||
197 | |||
198 | assert(f(2,1) == true and g(2,1) == 1 and h(2,1) == 1) | ||
199 | assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1) | ||
200 | assert(f(1,2,'a') | ||
201 | ~= -- force SETLINE before nil | ||
202 | nil, "") | ||
203 | assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1) | ||
204 | assert(f(1,2,nil,1,'x') == 'x' and g(1,2,nil,1,'x') == 1 and | ||
205 | h(1,2,nil,1,'x') == 1) | ||
206 | assert(f(1,2,nil,nil,'x') == nil and g(1,2,nil,nil,'x') == 0 and | ||
207 | h(1,2,nil,nil,'x') == 0) | ||
208 | assert(f(1,2,nil,1,nil) == nil and g(1,2,nil,1,nil) == 0 and | ||
209 | h(1,2,nil,1,nil) == 0) | ||
210 | |||
211 | assert(1 and 2<3 == true and 2<3 and 'a'<'b' == true) | ||
212 | x = 2<3 and not 3; assert(x==false) | ||
213 | x = 2<1 or (2>1 and 'a'); assert(x=='a') | ||
214 | |||
215 | |||
216 | do | ||
217 | local a; if nil then a=1; else a=2; end; -- this nil comes as PUSHNIL 2 | ||
218 | assert(a==2) | ||
219 | end | ||
220 | |||
221 | function F(a) | ||
222 | assert(debug.getinfo(1, "n").name == 'F') | ||
223 | return a,2,3 | ||
224 | end | ||
225 | |||
226 | a,b = F(1)~=nil; assert(a == true and b == nil); | ||
227 | a,b = F(nil)==nil; assert(a == true and b == nil) | ||
228 | |||
229 | ---------------------------------------------------------------- | ||
230 | ------------------------------------------------------------------ | ||
231 | |||
232 | -- sometimes will be 0, sometimes will not... | ||
233 | _ENV.GLOB1 = math.floor(os.time()) % 2 | ||
234 | |||
235 | -- basic expressions with their respective values | ||
236 | local basiccases = { | ||
237 | {"nil", nil}, | ||
238 | {"false", false}, | ||
239 | {"true", true}, | ||
240 | {"10", 10}, | ||
241 | {"(0==_ENV.GLOB1)", 0 == _ENV.GLOB1}, | ||
242 | } | ||
243 | |||
244 | print('testing short-circuit optimizations (' .. _ENV.GLOB1 .. ')') | ||
245 | |||
246 | |||
247 | -- operators with their respective values | ||
248 | local binops = { | ||
249 | {" and ", function (a,b) if not a then return a else return b end end}, | ||
250 | {" or ", function (a,b) if a then return a else return b end end}, | ||
251 | } | ||
252 | |||
253 | local cases = {} | ||
254 | |||
255 | -- creates all combinations of '(cases[i] op cases[n-i])' plus | ||
256 | -- 'not(cases[i] op cases[n-i])' (syntax + value) | ||
257 | local function createcases (n) | ||
258 | local res = {} | ||
259 | for i = 1, n - 1 do | ||
260 | for _, v1 in ipairs(cases[i]) do | ||
261 | for _, v2 in ipairs(cases[n - i]) do | ||
262 | for _, op in ipairs(binops) do | ||
263 | local t = { | ||
264 | "(" .. v1[1] .. op[1] .. v2[1] .. ")", | ||
265 | op[2](v1[2], v2[2]) | ||
266 | } | ||
267 | res[#res + 1] = t | ||
268 | res[#res + 1] = {"not" .. t[1], not t[2]} | ||
269 | end | ||
270 | end | ||
271 | end | ||
272 | end | ||
273 | return res | ||
274 | end | ||
275 | |||
276 | -- do not do too many combinations for soft tests | ||
277 | local level = _soft and 3 or 4 | ||
278 | |||
279 | cases[1] = basiccases | ||
280 | for i = 2, level do cases[i] = createcases(i) end | ||
281 | print("+") | ||
282 | |||
283 | local prog = [[if %s then IX = true end; return %s]] | ||
284 | |||
285 | local i = 0 | ||
286 | for n = 1, level do | ||
287 | for _, v in pairs(cases[n]) do | ||
288 | local s = v[1] | ||
289 | local p = load(string.format(prog, s, s), "") | ||
290 | IX = false | ||
291 | assert(p() == v[2] and IX == not not v[2]) | ||
292 | i = i + 1 | ||
293 | if i % 60000 == 0 then print('+') end | ||
294 | end | ||
295 | end | ||
296 | ------------------------------------------------------------------ | ||
297 | |||
298 | -- testing some syntax errors (chosen through 'gcov') | ||
299 | checkload("for x do", "expected") | ||
300 | checkload("x:call", "expected") | ||
301 | |||
302 | print'OK' | ||
diff --git a/testes/coroutine.lua b/testes/coroutine.lua new file mode 100644 index 00000000..22087320 --- /dev/null +++ b/testes/coroutine.lua | |||
@@ -0,0 +1,918 @@ | |||
1 | -- $Id: coroutine.lua,v 1.48 2018/03/12 14:19:36 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print "testing coroutines" | ||
5 | |||
6 | local debug = require'debug' | ||
7 | |||
8 | local f | ||
9 | |||
10 | local main, ismain = coroutine.running() | ||
11 | assert(type(main) == "thread" and ismain) | ||
12 | assert(not coroutine.resume(main)) | ||
13 | assert(not coroutine.isyieldable()) | ||
14 | assert(not pcall(coroutine.yield)) | ||
15 | |||
16 | |||
17 | -- trivial errors | ||
18 | assert(not pcall(coroutine.resume, 0)) | ||
19 | assert(not pcall(coroutine.status, 0)) | ||
20 | |||
21 | |||
22 | -- tests for multiple yield/resume arguments | ||
23 | |||
24 | local function eqtab (t1, t2) | ||
25 | assert(#t1 == #t2) | ||
26 | for i = 1, #t1 do | ||
27 | local v = t1[i] | ||
28 | assert(t2[i] == v) | ||
29 | end | ||
30 | end | ||
31 | |||
32 | _G.x = nil -- declare x | ||
33 | function foo (a, ...) | ||
34 | local x, y = coroutine.running() | ||
35 | assert(x == f and y == false) | ||
36 | -- next call should not corrupt coroutine (but must fail, | ||
37 | -- as it attempts to resume the running coroutine) | ||
38 | assert(coroutine.resume(f) == false) | ||
39 | assert(coroutine.status(f) == "running") | ||
40 | local arg = {...} | ||
41 | assert(coroutine.isyieldable()) | ||
42 | for i=1,#arg do | ||
43 | _G.x = {coroutine.yield(table.unpack(arg[i]))} | ||
44 | end | ||
45 | return table.unpack(a) | ||
46 | end | ||
47 | |||
48 | f = coroutine.create(foo) | ||
49 | assert(type(f) == "thread" and coroutine.status(f) == "suspended") | ||
50 | assert(string.find(tostring(f), "thread")) | ||
51 | local s,a,b,c,d | ||
52 | s,a,b,c,d = coroutine.resume(f, {1,2,3}, {}, {1}, {'a', 'b', 'c'}) | ||
53 | assert(s and a == nil and coroutine.status(f) == "suspended") | ||
54 | s,a,b,c,d = coroutine.resume(f) | ||
55 | eqtab(_G.x, {}) | ||
56 | assert(s and a == 1 and b == nil) | ||
57 | s,a,b,c,d = coroutine.resume(f, 1, 2, 3) | ||
58 | eqtab(_G.x, {1, 2, 3}) | ||
59 | assert(s and a == 'a' and b == 'b' and c == 'c' and d == nil) | ||
60 | s,a,b,c,d = coroutine.resume(f, "xuxu") | ||
61 | eqtab(_G.x, {"xuxu"}) | ||
62 | assert(s and a == 1 and b == 2 and c == 3 and d == nil) | ||
63 | assert(coroutine.status(f) == "dead") | ||
64 | s, a = coroutine.resume(f, "xuxu") | ||
65 | assert(not s and string.find(a, "dead") and coroutine.status(f) == "dead") | ||
66 | |||
67 | |||
68 | -- yields in tail calls | ||
69 | local function foo (i) return coroutine.yield(i) end | ||
70 | f = coroutine.wrap(function () | ||
71 | for i=1,10 do | ||
72 | assert(foo(i) == _G.x) | ||
73 | end | ||
74 | return 'a' | ||
75 | end) | ||
76 | for i=1,10 do _G.x = i; assert(f(i) == i) end | ||
77 | _G.x = 'xuxu'; assert(f('xuxu') == 'a') | ||
78 | |||
79 | -- recursive | ||
80 | function pf (n, i) | ||
81 | coroutine.yield(n) | ||
82 | pf(n*i, i+1) | ||
83 | end | ||
84 | |||
85 | f = coroutine.wrap(pf) | ||
86 | local s=1 | ||
87 | for i=1,10 do | ||
88 | assert(f(1, 1) == s) | ||
89 | s = s*i | ||
90 | end | ||
91 | |||
92 | -- sieve | ||
93 | function gen (n) | ||
94 | return coroutine.wrap(function () | ||
95 | for i=2,n do coroutine.yield(i) end | ||
96 | end) | ||
97 | end | ||
98 | |||
99 | |||
100 | function filter (p, g) | ||
101 | return coroutine.wrap(function () | ||
102 | while 1 do | ||
103 | local n = g() | ||
104 | if n == nil then return end | ||
105 | if math.fmod(n, p) ~= 0 then coroutine.yield(n) end | ||
106 | end | ||
107 | end) | ||
108 | end | ||
109 | |||
110 | local x = gen(100) | ||
111 | local a = {} | ||
112 | while 1 do | ||
113 | local n = x() | ||
114 | if n == nil then break end | ||
115 | table.insert(a, n) | ||
116 | x = filter(n, x) | ||
117 | end | ||
118 | |||
119 | assert(#a == 25 and a[#a] == 97) | ||
120 | x, a = nil | ||
121 | |||
122 | -- yielding across C boundaries | ||
123 | |||
124 | co = coroutine.wrap(function() | ||
125 | assert(not pcall(table.sort,{1,2,3}, coroutine.yield)) | ||
126 | assert(coroutine.isyieldable()) | ||
127 | coroutine.yield(20) | ||
128 | return 30 | ||
129 | end) | ||
130 | |||
131 | assert(co() == 20) | ||
132 | assert(co() == 30) | ||
133 | |||
134 | |||
135 | local f = function (s, i) return coroutine.yield(i) end | ||
136 | |||
137 | local f1 = coroutine.wrap(function () | ||
138 | return xpcall(pcall, function (...) return ... end, | ||
139 | function () | ||
140 | local s = 0 | ||
141 | for i in f, nil, 1 do pcall(function () s = s + i end) end | ||
142 | error({s}) | ||
143 | end) | ||
144 | end) | ||
145 | |||
146 | f1() | ||
147 | for i = 1, 10 do assert(f1(i) == i) end | ||
148 | local r1, r2, v = f1(nil) | ||
149 | assert(r1 and not r2 and v[1] == (10 + 1)*10/2) | ||
150 | |||
151 | |||
152 | function f (a, b) a = coroutine.yield(a); error{a + b} end | ||
153 | function g(x) return x[1]*2 end | ||
154 | |||
155 | co = coroutine.wrap(function () | ||
156 | coroutine.yield(xpcall(f, g, 10, 20)) | ||
157 | end) | ||
158 | |||
159 | assert(co() == 10) | ||
160 | r, msg = co(100) | ||
161 | assert(not r and msg == 240) | ||
162 | |||
163 | |||
164 | -- unyieldable C call | ||
165 | do | ||
166 | local function f (c) | ||
167 | assert(not coroutine.isyieldable()) | ||
168 | return c .. c | ||
169 | end | ||
170 | |||
171 | local co = coroutine.wrap(function (c) | ||
172 | assert(coroutine.isyieldable()) | ||
173 | local s = string.gsub("a", ".", f) | ||
174 | return s | ||
175 | end) | ||
176 | assert(co() == "aa") | ||
177 | end | ||
178 | |||
179 | |||
180 | |||
181 | do -- testing single trace of coroutines | ||
182 | local X | ||
183 | local co = coroutine.create(function () | ||
184 | coroutine.yield(10) | ||
185 | return 20; | ||
186 | end) | ||
187 | local trace = {} | ||
188 | local function dotrace (event) | ||
189 | trace[#trace + 1] = event | ||
190 | end | ||
191 | debug.sethook(co, dotrace, "clr") | ||
192 | repeat until not coroutine.resume(co) | ||
193 | local correcttrace = {"call", "line", "call", "return", "line", "return"} | ||
194 | assert(#trace == #correcttrace) | ||
195 | for k, v in pairs(trace) do | ||
196 | assert(v == correcttrace[k]) | ||
197 | end | ||
198 | end | ||
199 | |||
200 | -- errors in coroutines | ||
201 | function foo () | ||
202 | assert(debug.getinfo(1).currentline == debug.getinfo(foo).linedefined + 1) | ||
203 | assert(debug.getinfo(2).currentline == debug.getinfo(goo).linedefined) | ||
204 | coroutine.yield(3) | ||
205 | error(foo) | ||
206 | end | ||
207 | |||
208 | function goo() foo() end | ||
209 | x = coroutine.wrap(goo) | ||
210 | assert(x() == 3) | ||
211 | local a,b = pcall(x) | ||
212 | assert(not a and b == foo) | ||
213 | |||
214 | x = coroutine.create(goo) | ||
215 | a,b = coroutine.resume(x) | ||
216 | assert(a and b == 3) | ||
217 | a,b = coroutine.resume(x) | ||
218 | assert(not a and b == foo and coroutine.status(x) == "dead") | ||
219 | a,b = coroutine.resume(x) | ||
220 | assert(not a and string.find(b, "dead") and coroutine.status(x) == "dead") | ||
221 | |||
222 | |||
223 | -- co-routines x for loop | ||
224 | function all (a, n, k) | ||
225 | if k == 0 then coroutine.yield(a) | ||
226 | else | ||
227 | for i=1,n do | ||
228 | a[k] = i | ||
229 | all(a, n, k-1) | ||
230 | end | ||
231 | end | ||
232 | end | ||
233 | |||
234 | local a = 0 | ||
235 | for t in coroutine.wrap(function () all({}, 5, 4) end) do | ||
236 | a = a+1 | ||
237 | end | ||
238 | assert(a == 5^4) | ||
239 | |||
240 | |||
241 | -- access to locals of collected corroutines | ||
242 | local C = {}; setmetatable(C, {__mode = "kv"}) | ||
243 | local x = coroutine.wrap (function () | ||
244 | local a = 10 | ||
245 | local function f () a = a+10; return a end | ||
246 | while true do | ||
247 | a = a+1 | ||
248 | coroutine.yield(f) | ||
249 | end | ||
250 | end) | ||
251 | |||
252 | C[1] = x; | ||
253 | |||
254 | local f = x() | ||
255 | assert(f() == 21 and x()() == 32 and x() == f) | ||
256 | x = nil | ||
257 | collectgarbage() | ||
258 | assert(C[1] == undef) | ||
259 | assert(f() == 43 and f() == 53) | ||
260 | |||
261 | |||
262 | -- old bug: attempt to resume itself | ||
263 | |||
264 | function co_func (current_co) | ||
265 | assert(coroutine.running() == current_co) | ||
266 | assert(coroutine.resume(current_co) == false) | ||
267 | coroutine.yield(10, 20) | ||
268 | assert(coroutine.resume(current_co) == false) | ||
269 | coroutine.yield(23) | ||
270 | return 10 | ||
271 | end | ||
272 | |||
273 | local co = coroutine.create(co_func) | ||
274 | local a,b,c = coroutine.resume(co, co) | ||
275 | assert(a == true and b == 10 and c == 20) | ||
276 | a,b = coroutine.resume(co, co) | ||
277 | assert(a == true and b == 23) | ||
278 | a,b = coroutine.resume(co, co) | ||
279 | assert(a == true and b == 10) | ||
280 | assert(coroutine.resume(co, co) == false) | ||
281 | assert(coroutine.resume(co, co) == false) | ||
282 | |||
283 | |||
284 | -- other old bug when attempting to resume itself | ||
285 | -- (trigger C-code assertions) | ||
286 | do | ||
287 | local A = coroutine.running() | ||
288 | local B = coroutine.create(function() return coroutine.resume(A) end) | ||
289 | local st, res = coroutine.resume(B) | ||
290 | assert(st == true and res == false) | ||
291 | |||
292 | A = coroutine.wrap(function() return pcall(A, 1) end) | ||
293 | st, res = A() | ||
294 | assert(not st and string.find(res, "non%-suspended")) | ||
295 | end | ||
296 | |||
297 | |||
298 | -- attempt to resume 'normal' coroutine | ||
299 | local co1, co2 | ||
300 | co1 = coroutine.create(function () return co2() end) | ||
301 | co2 = coroutine.wrap(function () | ||
302 | assert(coroutine.status(co1) == 'normal') | ||
303 | assert(not coroutine.resume(co1)) | ||
304 | coroutine.yield(3) | ||
305 | end) | ||
306 | |||
307 | a,b = coroutine.resume(co1) | ||
308 | assert(a and b == 3) | ||
309 | assert(coroutine.status(co1) == 'dead') | ||
310 | |||
311 | -- infinite recursion of coroutines | ||
312 | a = function(a) coroutine.wrap(a)(a) end | ||
313 | assert(not pcall(a, a)) | ||
314 | a = nil | ||
315 | |||
316 | |||
317 | -- access to locals of erroneous coroutines | ||
318 | local x = coroutine.create (function () | ||
319 | local a = 10 | ||
320 | _G.f = function () a=a+1; return a end | ||
321 | error('x') | ||
322 | end) | ||
323 | |||
324 | assert(not coroutine.resume(x)) | ||
325 | -- overwrite previous position of local `a' | ||
326 | assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1)) | ||
327 | assert(_G.f() == 11) | ||
328 | assert(_G.f() == 12) | ||
329 | |||
330 | |||
331 | if not T then | ||
332 | (Message or print)('\n >>> testC not active: skipping yield/hook tests <<<\n') | ||
333 | else | ||
334 | print "testing yields inside hooks" | ||
335 | |||
336 | local turn | ||
337 | |||
338 | function fact (t, x) | ||
339 | assert(turn == t) | ||
340 | if x == 0 then return 1 | ||
341 | else return x*fact(t, x-1) | ||
342 | end | ||
343 | end | ||
344 | |||
345 | local A, B = 0, 0 | ||
346 | |||
347 | local x = coroutine.create(function () | ||
348 | T.sethook("yield 0", "", 2) | ||
349 | A = fact("A", 6) | ||
350 | end) | ||
351 | |||
352 | local y = coroutine.create(function () | ||
353 | T.sethook("yield 0", "", 3) | ||
354 | B = fact("B", 7) | ||
355 | end) | ||
356 | |||
357 | while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y') | ||
358 | if A==0 then turn = "A"; assert(T.resume(x)) end | ||
359 | if B==0 then turn = "B"; assert(T.resume(y)) end | ||
360 | end | ||
361 | |||
362 | assert(B // A == 7) -- fact(7) // fact(6) | ||
363 | |||
364 | local line = debug.getinfo(1, "l").currentline + 2 -- get line number | ||
365 | local function foo () | ||
366 | local x = 10 --<< this line is 'line' | ||
367 | x = x + 10 | ||
368 | _G.XX = x | ||
369 | end | ||
370 | |||
371 | -- testing yields in line hook | ||
372 | local co = coroutine.wrap(function () | ||
373 | T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end) | ||
374 | |||
375 | _G.XX = nil; | ||
376 | _G.X = nil; co(); assert(_G.X == line) | ||
377 | _G.X = nil; co(); assert(_G.X == line + 1) | ||
378 | _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil) | ||
379 | _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20) | ||
380 | assert(co() == 10) | ||
381 | |||
382 | -- testing yields in count hook | ||
383 | co = coroutine.wrap(function () | ||
384 | T.sethook("yield 0", "", 1); foo(); return 10 end) | ||
385 | |||
386 | _G.XX = nil; | ||
387 | local c = 0 | ||
388 | repeat c = c + 1; local a = co() until a == 10 | ||
389 | assert(_G.XX == 20 and c >= 5) | ||
390 | |||
391 | co = coroutine.wrap(function () | ||
392 | T.sethook("yield 0", "", 2); foo(); return 10 end) | ||
393 | |||
394 | _G.XX = nil; | ||
395 | local c = 0 | ||
396 | repeat c = c + 1; local a = co() until a == 10 | ||
397 | assert(_G.XX == 20 and c >= 5) | ||
398 | _G.X = nil; _G.XX = nil | ||
399 | |||
400 | do | ||
401 | -- testing debug library on a coroutine suspended inside a hook | ||
402 | -- (bug in 5.2/5.3) | ||
403 | c = coroutine.create(function (a, ...) | ||
404 | T.sethook("yield 0", "l") -- will yield on next two lines | ||
405 | assert(a == 10) | ||
406 | return ... | ||
407 | end) | ||
408 | |||
409 | assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine | ||
410 | local n,v = debug.getlocal(c, 0, 1) -- check its local | ||
411 | assert(n == "a" and v == 1) | ||
412 | assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal' | ||
413 | local t = debug.getinfo(c, 0) -- test 'getinfo' | ||
414 | assert(t.currentline == t.linedefined + 1) | ||
415 | assert(not debug.getinfo(c, 1)) -- no other level | ||
416 | assert(coroutine.resume(c)) -- run next line | ||
417 | v = {coroutine.resume(c)} -- finish coroutine | ||
418 | assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef) | ||
419 | assert(not coroutine.resume(c)) | ||
420 | end | ||
421 | |||
422 | do | ||
423 | -- testing debug library on last function in a suspended coroutine | ||
424 | -- (bug in 5.2/5.3) | ||
425 | local c = coroutine.create(function () T.testC("yield 1", 10, 20) end) | ||
426 | local a, b = coroutine.resume(c) | ||
427 | assert(a and b == 20) | ||
428 | assert(debug.getinfo(c, 0).linedefined == -1) | ||
429 | a, b = debug.getlocal(c, 0, 2) | ||
430 | assert(b == 10) | ||
431 | end | ||
432 | |||
433 | |||
434 | print "testing coroutine API" | ||
435 | |||
436 | -- reusing a thread | ||
437 | assert(T.testC([[ | ||
438 | newthread # create thread | ||
439 | pushvalue 2 # push body | ||
440 | pushstring 'a a a' # push argument | ||
441 | xmove 0 3 2 # move values to new thread | ||
442 | resume -1, 1 # call it first time | ||
443 | pushstatus | ||
444 | xmove 3 0 0 # move results back to stack | ||
445 | setglobal X # result | ||
446 | setglobal Y # status | ||
447 | pushvalue 2 # push body (to call it again) | ||
448 | pushstring 'b b b' | ||
449 | xmove 0 3 2 | ||
450 | resume -1, 1 # call it again | ||
451 | pushstatus | ||
452 | xmove 3 0 0 | ||
453 | return 1 # return result | ||
454 | ]], function (...) return ... end) == 'b b b') | ||
455 | |||
456 | assert(X == 'a a a' and Y == 'OK') | ||
457 | |||
458 | |||
459 | -- resuming running coroutine | ||
460 | C = coroutine.create(function () | ||
461 | return T.testC([[ | ||
462 | pushnum 10; | ||
463 | pushnum 20; | ||
464 | resume -3 2; | ||
465 | pushstatus | ||
466 | gettop; | ||
467 | return 3]], C) | ||
468 | end) | ||
469 | local a, b, c, d = coroutine.resume(C) | ||
470 | assert(a == true and string.find(b, "non%-suspended") and | ||
471 | c == "ERRRUN" and d == 4) | ||
472 | |||
473 | a, b, c, d = T.testC([[ | ||
474 | rawgeti R 1 # get main thread | ||
475 | pushnum 10; | ||
476 | pushnum 20; | ||
477 | resume -3 2; | ||
478 | pushstatus | ||
479 | gettop; | ||
480 | return 4]]) | ||
481 | assert(a == coroutine.running() and string.find(b, "non%-suspended") and | ||
482 | c == "ERRRUN" and d == 4) | ||
483 | |||
484 | |||
485 | -- using a main thread as a coroutine | ||
486 | local state = T.newstate() | ||
487 | T.loadlib(state) | ||
488 | |||
489 | assert(T.doremote(state, [[ | ||
490 | coroutine = require'coroutine'; | ||
491 | X = function (x) coroutine.yield(x, 'BB'); return 'CC' end; | ||
492 | return 'ok']])) | ||
493 | |||
494 | t = table.pack(T.testC(state, [[ | ||
495 | rawgeti R 1 # get main thread | ||
496 | pushstring 'XX' | ||
497 | getglobal X # get function for body | ||
498 | pushstring AA # arg | ||
499 | resume 1 1 # 'resume' shadows previous stack! | ||
500 | gettop | ||
501 | setglobal T # top | ||
502 | setglobal B # second yielded value | ||
503 | setglobal A # fist yielded value | ||
504 | rawgeti R 1 # get main thread | ||
505 | pushnum 5 # arg (noise) | ||
506 | resume 1 1 # after coroutine ends, previous stack is back | ||
507 | pushstatus | ||
508 | return * | ||
509 | ]])) | ||
510 | assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK') | ||
511 | assert(T.doremote(state, "return T") == '2') | ||
512 | assert(T.doremote(state, "return A") == 'AA') | ||
513 | assert(T.doremote(state, "return B") == 'BB') | ||
514 | |||
515 | T.closestate(state) | ||
516 | |||
517 | print'+' | ||
518 | |||
519 | end | ||
520 | |||
521 | |||
522 | -- leaving a pending coroutine open | ||
523 | _X = coroutine.wrap(function () | ||
524 | local a = 10 | ||
525 | local x = function () a = a+1 end | ||
526 | coroutine.yield() | ||
527 | end) | ||
528 | |||
529 | _X() | ||
530 | |||
531 | |||
532 | if not _soft then | ||
533 | -- bug (stack overflow) | ||
534 | local j = 2^9 | ||
535 | local lim = 1000000 -- (C stack limit; assume 32-bit machine) | ||
536 | local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1} | ||
537 | for i = 1, #t do | ||
538 | local j = t[i] | ||
539 | co = coroutine.create(function() | ||
540 | local t = {} | ||
541 | for i = 1, j do t[i] = i end | ||
542 | return table.unpack(t) | ||
543 | end) | ||
544 | local r, msg = coroutine.resume(co) | ||
545 | assert(not r) | ||
546 | end | ||
547 | co = nil | ||
548 | end | ||
549 | |||
550 | |||
551 | assert(coroutine.running() == main) | ||
552 | |||
553 | print"+" | ||
554 | |||
555 | |||
556 | print"testing yields inside metamethods" | ||
557 | |||
558 | local function val(x) | ||
559 | if type(x) == "table" then return x.x else return x end | ||
560 | end | ||
561 | |||
562 | local mt = { | ||
563 | __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end, | ||
564 | __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end, | ||
565 | __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end, | ||
566 | __add = function(a,b) coroutine.yield(nil, "add"); | ||
567 | return val(a) + val(b) end, | ||
568 | __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end, | ||
569 | __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end, | ||
570 | __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end, | ||
571 | __idiv = function(a,b) coroutine.yield(nil, "idiv"); | ||
572 | return val(a) // val(b) end, | ||
573 | __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end, | ||
574 | __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end, | ||
575 | __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end, | ||
576 | __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end, | ||
577 | __shl = function(a,b) coroutine.yield(nil, "shl"); | ||
578 | return val(a) << val(b) end, | ||
579 | __shr = function(a,b) coroutine.yield(nil, "shr"); | ||
580 | return val(a) >> val(b) end, | ||
581 | __band = function(a,b) | ||
582 | coroutine.yield(nil, "band") | ||
583 | return val(a) & val(b) | ||
584 | end, | ||
585 | __bor = function(a,b) coroutine.yield(nil, "bor"); | ||
586 | return val(a) | val(b) end, | ||
587 | __bxor = function(a,b) coroutine.yield(nil, "bxor"); | ||
588 | return val(a) ~ val(b) end, | ||
589 | |||
590 | __concat = function(a,b) | ||
591 | coroutine.yield(nil, "concat"); | ||
592 | return val(a) .. val(b) | ||
593 | end, | ||
594 | __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end, | ||
595 | __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end, | ||
596 | } | ||
597 | |||
598 | |||
599 | local function new (x) | ||
600 | return setmetatable({x = x, k = {}}, mt) | ||
601 | end | ||
602 | |||
603 | |||
604 | local a = new(10) | ||
605 | local b = new(12) | ||
606 | local c = new"hello" | ||
607 | |||
608 | local function run (f, t) | ||
609 | local i = 1 | ||
610 | local c = coroutine.wrap(f) | ||
611 | while true do | ||
612 | local res, stat = c() | ||
613 | if res then assert(t[i] == undef); return res, t end | ||
614 | assert(stat == t[i]) | ||
615 | i = i + 1 | ||
616 | end | ||
617 | end | ||
618 | |||
619 | |||
620 | assert(run(function () if (a>=b) then return '>=' else return '<' end end, | ||
621 | {"le", "sub"}) == "<") | ||
622 | -- '<=' using '<' | ||
623 | mt.__le = nil | ||
624 | assert(run(function () if (a<=b) then return '<=' else return '>' end end, | ||
625 | {"lt"}) == "<=") | ||
626 | assert(run(function () if (a==b) then return '==' else return '~=' end end, | ||
627 | {"eq"}) == "~=") | ||
628 | |||
629 | assert(run(function () return a & b + a end, {"add", "band"}) == 2) | ||
630 | |||
631 | assert(run(function () return 1 + a end, {"add"}) == 11) | ||
632 | assert(run(function () return a - 25 end, {"sub"}) == -15) | ||
633 | assert(run(function () return 2 * a end, {"mul"}) == 20) | ||
634 | assert(run(function () return a ^ 2 end, {"pow"}) == 100) | ||
635 | assert(run(function () return a / 2 end, {"div"}) == 5) | ||
636 | assert(run(function () return a % 6 end, {"mod"}) == 4) | ||
637 | assert(run(function () return a // 3 end, {"idiv"}) == 3) | ||
638 | |||
639 | assert(run(function () return a + b end, {"add"}) == 22) | ||
640 | assert(run(function () return a - b end, {"sub"}) == -2) | ||
641 | assert(run(function () return a * b end, {"mul"}) == 120) | ||
642 | assert(run(function () return a ^ b end, {"pow"}) == 10^12) | ||
643 | assert(run(function () return a / b end, {"div"}) == 10/12) | ||
644 | assert(run(function () return a % b end, {"mod"}) == 10) | ||
645 | assert(run(function () return a // b end, {"idiv"}) == 0) | ||
646 | |||
647 | |||
648 | assert(run(function () return a % b end, {"mod"}) == 10) | ||
649 | |||
650 | assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12) | ||
651 | assert(run(function () return a | b end, {"bor"}) == 10 | 12) | ||
652 | assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12) | ||
653 | assert(run(function () return a << b end, {"shl"}) == 10 << 12) | ||
654 | assert(run(function () return a >> b end, {"shr"}) == 10 >> 12) | ||
655 | |||
656 | assert(run(function () return 10 & b end, {"band"}) == 10 & 12) | ||
657 | assert(run(function () return a | 2 end, {"bor"}) == 10 | 2) | ||
658 | assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2) | ||
659 | |||
660 | assert(run(function () return a..b end, {"concat"}) == "1012") | ||
661 | |||
662 | assert(run(function() return a .. b .. c .. a end, | ||
663 | {"concat", "concat", "concat"}) == "1012hello10") | ||
664 | |||
665 | assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end, | ||
666 | {"concat", "concat", "concat"}) == "ab10chello12x") | ||
667 | |||
668 | |||
669 | do -- a few more tests for comparsion operators | ||
670 | local mt1 = { | ||
671 | __le = function (a,b) | ||
672 | coroutine.yield(10) | ||
673 | return (val(a) <= val(b)) | ||
674 | end, | ||
675 | __lt = function (a,b) | ||
676 | coroutine.yield(10) | ||
677 | return val(a) < val(b) | ||
678 | end, | ||
679 | } | ||
680 | local mt2 = { __lt = mt1.__lt } -- no __le | ||
681 | |||
682 | local function run (f) | ||
683 | local co = coroutine.wrap(f) | ||
684 | local res | ||
685 | repeat | ||
686 | res = co() | ||
687 | until res ~= 10 | ||
688 | return res | ||
689 | end | ||
690 | |||
691 | local function test () | ||
692 | local a1 = setmetatable({x=1}, mt1) | ||
693 | local a2 = setmetatable({x=2}, mt2) | ||
694 | assert(a1 < a2) | ||
695 | assert(a1 <= a2) | ||
696 | assert(1 < a2) | ||
697 | assert(1 <= a2) | ||
698 | assert(2 > a1) | ||
699 | assert(2 >= a2) | ||
700 | return true | ||
701 | end | ||
702 | |||
703 | run(test) | ||
704 | |||
705 | end | ||
706 | |||
707 | assert(run(function () | ||
708 | a.BB = print | ||
709 | return a.BB | ||
710 | end, {"nidx", "idx"}) == print) | ||
711 | |||
712 | -- getuptable & setuptable | ||
713 | do local _ENV = _ENV | ||
714 | f = function () AAA = BBB + 1; return AAA end | ||
715 | end | ||
716 | g = new(10); g.k.BBB = 10; | ||
717 | debug.setupvalue(f, 1, g) | ||
718 | assert(run(f, {"idx", "nidx", "idx"}) == 11) | ||
719 | assert(g.k.AAA == 11) | ||
720 | |||
721 | print"+" | ||
722 | |||
723 | print"testing yields inside 'for' iterators" | ||
724 | |||
725 | local f = function (s, i) | ||
726 | if i%2 == 0 then coroutine.yield(nil, "for") end | ||
727 | if i < s then return i + 1 end | ||
728 | end | ||
729 | |||
730 | assert(run(function () | ||
731 | local s = 0 | ||
732 | for i in f, 4, 0 do s = s + i end | ||
733 | return s | ||
734 | end, {"for", "for", "for"}) == 10) | ||
735 | |||
736 | |||
737 | |||
738 | -- tests for coroutine API | ||
739 | if T==nil then | ||
740 | (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n') | ||
741 | return | ||
742 | end | ||
743 | |||
744 | print('testing coroutine API') | ||
745 | |||
746 | local function apico (...) | ||
747 | local x = {...} | ||
748 | return coroutine.wrap(function () | ||
749 | return T.testC(table.unpack(x)) | ||
750 | end) | ||
751 | end | ||
752 | |||
753 | local a = {apico( | ||
754 | [[ | ||
755 | pushstring errorcode | ||
756 | pcallk 1 0 2; | ||
757 | invalid command (should not arrive here) | ||
758 | ]], | ||
759 | [[return *]], | ||
760 | "stackmark", | ||
761 | error | ||
762 | )()} | ||
763 | assert(#a == 4 and | ||
764 | a[3] == "stackmark" and | ||
765 | a[4] == "errorcode" and | ||
766 | _G.status == "ERRRUN" and | ||
767 | _G.ctx == 2) -- 'ctx' to pcallk | ||
768 | |||
769 | local co = apico( | ||
770 | "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;", | ||
771 | coroutine.yield, | ||
772 | "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command", | ||
773 | "getglobal status; getglobal ctx; return *") | ||
774 | |||
775 | assert(co() == 10) | ||
776 | assert(co(20, 30) == 'a') | ||
777 | a = {co()} | ||
778 | assert(#a == 10 and | ||
779 | a[2] == coroutine.yield and | ||
780 | a[5] == 20 and a[6] == 30 and | ||
781 | a[7] == "YIELD" and a[8] == 3 and | ||
782 | a[9] == "YIELD" and a[10] == 4) | ||
783 | assert(not pcall(co)) -- coroutine is dead now | ||
784 | |||
785 | |||
786 | f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;") | ||
787 | co = coroutine.wrap(function () | ||
788 | assert(f() == 23); assert(f() == 23); return 10 | ||
789 | end) | ||
790 | assert(co(23,16) == 5) | ||
791 | assert(co(23,16) == 5) | ||
792 | assert(co(23,16) == 10) | ||
793 | |||
794 | |||
795 | -- testing coroutines with C bodies | ||
796 | f = T.makeCfunc([[ | ||
797 | pushnum 102 | ||
798 | yieldk 1 U2 | ||
799 | cannot be here! | ||
800 | ]], | ||
801 | [[ # continuation | ||
802 | pushvalue U3 # accessing upvalues inside a continuation | ||
803 | pushvalue U4 | ||
804 | return * | ||
805 | ]], 23, "huu") | ||
806 | |||
807 | x = coroutine.wrap(f) | ||
808 | assert(x() == 102) | ||
809 | eqtab({x()}, {23, "huu"}) | ||
810 | |||
811 | |||
812 | f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]] | ||
813 | |||
814 | a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0; | ||
815 | pushstatus; xmove 3 0 0; resume 3 0; pushstatus; | ||
816 | return 4; ]], f) | ||
817 | |||
818 | assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK') | ||
819 | |||
820 | |||
821 | -- testing chain of suspendable C calls | ||
822 | |||
823 | local count = 3 -- number of levels | ||
824 | |||
825 | f = T.makeCfunc([[ | ||
826 | remove 1; # remove argument | ||
827 | pushvalue U3; # get selection function | ||
828 | call 0 1; # call it (result is 'f' or 'yield') | ||
829 | pushstring hello # single argument for selected function | ||
830 | pushupvalueindex 2; # index of continuation program | ||
831 | callk 1 -1 .; # call selected function | ||
832 | errorerror # should never arrive here | ||
833 | ]], | ||
834 | [[ | ||
835 | # continuation program | ||
836 | pushnum 34 # return value | ||
837 | return * # return all results | ||
838 | ]], | ||
839 | function () -- selection function | ||
840 | count = count - 1 | ||
841 | if count == 0 then return coroutine.yield | ||
842 | else return f | ||
843 | end | ||
844 | end | ||
845 | ) | ||
846 | |||
847 | co = coroutine.wrap(function () return f(nil) end) | ||
848 | assert(co() == "hello") -- argument to 'yield' | ||
849 | a = {co()} | ||
850 | -- three '34's (one from each pending C call) | ||
851 | assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34) | ||
852 | |||
853 | |||
854 | -- testing yields with continuations | ||
855 | |||
856 | co = coroutine.wrap(function (...) return | ||
857 | T.testC([[ # initial function | ||
858 | yieldk 1 2 | ||
859 | cannot be here! | ||
860 | ]], | ||
861 | [[ # 1st continuation | ||
862 | yieldk 0 3 | ||
863 | cannot be here! | ||
864 | ]], | ||
865 | [[ # 2nd continuation | ||
866 | yieldk 0 4 | ||
867 | cannot be here! | ||
868 | ]], | ||
869 | [[ # 3th continuation | ||
870 | pushvalue 6 # function which is last arg. to 'testC' here | ||
871 | pushnum 10; pushnum 20; | ||
872 | pcall 2 0 0 # call should throw an error and return to next line | ||
873 | pop 1 # remove error message | ||
874 | pushvalue 6 | ||
875 | getglobal status; getglobal ctx | ||
876 | pcallk 2 2 5 # call should throw an error and jump to continuation | ||
877 | cannot be here! | ||
878 | ]], | ||
879 | [[ # 4th (and last) continuation | ||
880 | return * | ||
881 | ]], | ||
882 | -- function called by 3th continuation | ||
883 | function (a,b) x=a; y=b; error("errmsg") end, | ||
884 | ... | ||
885 | ) | ||
886 | end) | ||
887 | |||
888 | local a = {co(3,4,6)} | ||
889 | assert(a[1] == 6 and a[2] == undef) | ||
890 | a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2) | ||
891 | a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3) | ||
892 | a = {co(7,8)}; | ||
893 | -- original arguments | ||
894 | assert(type(a[1]) == 'string' and type(a[2]) == 'string' and | ||
895 | type(a[3]) == 'string' and type(a[4]) == 'string' and | ||
896 | type(a[5]) == 'string' and type(a[6]) == 'function') | ||
897 | -- arguments left from fist resume | ||
898 | assert(a[7] == 3 and a[8] == 4) | ||
899 | -- arguments to last resume | ||
900 | assert(a[9] == 7 and a[10] == 8) | ||
901 | -- error message and nothing more | ||
902 | assert(a[11]:find("errmsg") and #a == 11) | ||
903 | -- check arguments to pcallk | ||
904 | assert(x == "YIELD" and y == 4) | ||
905 | |||
906 | assert(not pcall(co)) -- coroutine should be dead | ||
907 | |||
908 | |||
909 | -- bug in nCcalls | ||
910 | local co = coroutine.wrap(function () | ||
911 | local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")} | ||
912 | return pcall(assert, table.unpack(a)) | ||
913 | end) | ||
914 | |||
915 | local a = {co()} | ||
916 | assert(a[10] == "hi") | ||
917 | |||
918 | print'OK' | ||
diff --git a/testes/db.lua b/testes/db.lua new file mode 100644 index 00000000..36d1cdaa --- /dev/null +++ b/testes/db.lua | |||
@@ -0,0 +1,948 @@ | |||
1 | -- $Id: db.lua,v 1.90 2018/04/02 17:55:58 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | -- testing debug library | ||
5 | |||
6 | local debug = require "debug" | ||
7 | |||
8 | local function dostring(s) return assert(load(s))() end | ||
9 | |||
10 | print"testing debug library and debug information" | ||
11 | |||
12 | do | ||
13 | local a=1 | ||
14 | end | ||
15 | |||
16 | assert(not debug.gethook()) | ||
17 | |||
18 | local testline = 19 -- line where 'test' is defined | ||
19 | function test (s, l, p) -- this must be line 19 | ||
20 | collectgarbage() -- avoid gc during trace | ||
21 | local function f (event, line) | ||
22 | assert(event == 'line') | ||
23 | local l = table.remove(l, 1) | ||
24 | if p then print(l, line) end | ||
25 | assert(l == line, "wrong trace!!") | ||
26 | end | ||
27 | debug.sethook(f,"l"); load(s)(); debug.sethook() | ||
28 | assert(#l == 0) | ||
29 | end | ||
30 | |||
31 | |||
32 | do | ||
33 | assert(not pcall(debug.getinfo, print, "X")) -- invalid option | ||
34 | assert(not debug.getinfo(1000)) -- out of range level | ||
35 | assert(not debug.getinfo(-1)) -- out of range level | ||
36 | local a = debug.getinfo(print) | ||
37 | assert(a.what == "C" and a.short_src == "[C]") | ||
38 | a = debug.getinfo(print, "L") | ||
39 | assert(a.activelines == nil) | ||
40 | local b = debug.getinfo(test, "SfL") | ||
41 | assert(b.name == nil and b.what == "Lua" and b.linedefined == testline and | ||
42 | b.lastlinedefined == b.linedefined + 10 and | ||
43 | b.func == test and not string.find(b.short_src, "%[")) | ||
44 | assert(b.activelines[b.linedefined + 1] and | ||
45 | b.activelines[b.lastlinedefined]) | ||
46 | assert(not b.activelines[b.linedefined] and | ||
47 | not b.activelines[b.lastlinedefined + 1]) | ||
48 | end | ||
49 | |||
50 | |||
51 | -- test file and string names truncation | ||
52 | a = "function f () end" | ||
53 | local function dostring (s, x) return load(s, x)() end | ||
54 | dostring(a) | ||
55 | assert(debug.getinfo(f).short_src == string.format('[string "%s"]', a)) | ||
56 | dostring(a..string.format("; %s\n=1", string.rep('p', 400))) | ||
57 | assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$')) | ||
58 | dostring(a..string.format("; %s=1", string.rep('p', 400))) | ||
59 | assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$')) | ||
60 | dostring("\n"..a) | ||
61 | assert(debug.getinfo(f).short_src == '[string "..."]') | ||
62 | dostring(a, "") | ||
63 | assert(debug.getinfo(f).short_src == '[string ""]') | ||
64 | dostring(a, "@xuxu") | ||
65 | assert(debug.getinfo(f).short_src == "xuxu") | ||
66 | dostring(a, "@"..string.rep('p', 1000)..'t') | ||
67 | assert(string.find(debug.getinfo(f).short_src, "^%.%.%.p*t$")) | ||
68 | dostring(a, "=xuxu") | ||
69 | assert(debug.getinfo(f).short_src == "xuxu") | ||
70 | dostring(a, string.format("=%s", string.rep('x', 500))) | ||
71 | assert(string.find(debug.getinfo(f).short_src, "^x*$")) | ||
72 | dostring(a, "=") | ||
73 | assert(debug.getinfo(f).short_src == "") | ||
74 | a = nil; f = nil; | ||
75 | |||
76 | |||
77 | repeat | ||
78 | local g = {x = function () | ||
79 | local a = debug.getinfo(2) | ||
80 | assert(a.name == 'f' and a.namewhat == 'local') | ||
81 | a = debug.getinfo(1) | ||
82 | assert(a.name == 'x' and a.namewhat == 'field') | ||
83 | return 'xixi' | ||
84 | end} | ||
85 | local f = function () return 1+1 and (not 1 or g.x()) end | ||
86 | assert(f() == 'xixi') | ||
87 | g = debug.getinfo(f) | ||
88 | assert(g.what == "Lua" and g.func == f and g.namewhat == "" and not g.name) | ||
89 | |||
90 | function f (x, name) -- local! | ||
91 | name = name or 'f' | ||
92 | local a = debug.getinfo(1) | ||
93 | assert(a.name == name and a.namewhat == 'local') | ||
94 | return x | ||
95 | end | ||
96 | |||
97 | -- breaks in different conditions | ||
98 | if 3>4 then break end; f() | ||
99 | if 3<4 then a=1 else break end; f() | ||
100 | while 1 do local x=10; break end; f() | ||
101 | local b = 1 | ||
102 | if 3>4 then return math.sin(1) end; f() | ||
103 | a = 3<4; f() | ||
104 | a = 3<4 or 1; f() | ||
105 | repeat local x=20; if 4>3 then f() else break end; f() until 1 | ||
106 | g = {} | ||
107 | f(g).x = f(2) and f(10)+f(9) | ||
108 | assert(g.x == f(19)) | ||
109 | function g(x) if not x then return 3 end return (x('a', 'x')) end | ||
110 | assert(g(f) == 'a') | ||
111 | until 1 | ||
112 | |||
113 | test([[if | ||
114 | math.sin(1) | ||
115 | then | ||
116 | a=1 | ||
117 | else | ||
118 | a=2 | ||
119 | end | ||
120 | ]], {2,3,4,7}) | ||
121 | |||
122 | test([[-- | ||
123 | if nil then | ||
124 | a=1 | ||
125 | else | ||
126 | a=2 | ||
127 | end | ||
128 | ]], {2,5,6}) | ||
129 | |||
130 | test([[a=1 | ||
131 | repeat | ||
132 | a=a+1 | ||
133 | until a==3 | ||
134 | ]], {1,3,4,3,4}) | ||
135 | |||
136 | test([[ do | ||
137 | return | ||
138 | end | ||
139 | ]], {2}) | ||
140 | |||
141 | test([[local a | ||
142 | a=1 | ||
143 | while a<=3 do | ||
144 | a=a+1 | ||
145 | end | ||
146 | ]], {1,2,3,4,3,4,3,4,3,5}) | ||
147 | |||
148 | test([[while math.sin(1) do | ||
149 | if math.sin(1) | ||
150 | then break | ||
151 | end | ||
152 | end | ||
153 | a=1]], {1,2,3,6}) | ||
154 | |||
155 | test([[for i=1,3 do | ||
156 | a=i | ||
157 | end | ||
158 | ]], {1,2,1,2,1,2,1,3}) | ||
159 | |||
160 | test([[for i,v in pairs{'a','b'} do | ||
161 | a=tostring(i) .. v | ||
162 | end | ||
163 | ]], {1,2,1,2,1,3}) | ||
164 | |||
165 | test([[for i=1,4 do a=1 end]], {1,1,1,1,1}) | ||
166 | |||
167 | |||
168 | do -- testing line info/trace with large gaps in source | ||
169 | |||
170 | local a = {1, 2, 3, 10, 124, 125, 126, 127, 128, 129, 130, | ||
171 | 255, 256, 257, 500, 1000} | ||
172 | local s = [[ | ||
173 | local b = {10} | ||
174 | a = b[1] X + Y b[1] | ||
175 | b = 4 | ||
176 | ]] | ||
177 | for _, i in ipairs(a) do | ||
178 | local subs = {X = string.rep("\n", i)} | ||
179 | for _, j in ipairs(a) do | ||
180 | subs.Y = string.rep("\n", j) | ||
181 | local s = string.gsub(s, "[XY]", subs) | ||
182 | test(s, {1, 2 + i, 2 + i + j, 2 + i, 2 + i + j, 3 + i + j}) | ||
183 | end | ||
184 | end | ||
185 | end | ||
186 | |||
187 | print'+' | ||
188 | |||
189 | -- invalid levels in [gs]etlocal | ||
190 | assert(not pcall(debug.getlocal, 20, 1)) | ||
191 | assert(not pcall(debug.setlocal, -1, 1, 10)) | ||
192 | |||
193 | |||
194 | -- parameter names | ||
195 | local function foo (a,b,...) local d, e end | ||
196 | local co = coroutine.create(foo) | ||
197 | |||
198 | assert(debug.getlocal(foo, 1) == 'a') | ||
199 | assert(debug.getlocal(foo, 2) == 'b') | ||
200 | assert(not debug.getlocal(foo, 3)) | ||
201 | assert(debug.getlocal(co, foo, 1) == 'a') | ||
202 | assert(debug.getlocal(co, foo, 2) == 'b') | ||
203 | assert(not debug.getlocal(co, foo, 3)) | ||
204 | |||
205 | assert(not debug.getlocal(print, 1)) | ||
206 | |||
207 | |||
208 | local function foo () return (debug.getlocal(1, -1)) end | ||
209 | assert(not foo(10)) | ||
210 | |||
211 | |||
212 | -- varargs | ||
213 | local function foo (a, ...) | ||
214 | local t = table.pack(...) | ||
215 | for i = 1, t.n do | ||
216 | local n, v = debug.getlocal(1, -i) | ||
217 | assert(n == "(*vararg)" and v == t[i]) | ||
218 | end | ||
219 | assert(not debug.getlocal(1, -(t.n + 1))) | ||
220 | assert(not debug.setlocal(1, -(t.n + 1), 30)) | ||
221 | if t.n > 0 then | ||
222 | (function (x) | ||
223 | assert(debug.setlocal(2, -1, x) == "(*vararg)") | ||
224 | assert(debug.setlocal(2, -t.n, x) == "(*vararg)") | ||
225 | end)(430) | ||
226 | assert(... == 430) | ||
227 | end | ||
228 | end | ||
229 | |||
230 | foo() | ||
231 | foo(print) | ||
232 | foo(200, 3, 4) | ||
233 | local a = {} | ||
234 | for i = 1, (_soft and 100 or 1000) do a[i] = i end | ||
235 | foo(table.unpack(a)) | ||
236 | a = nil | ||
237 | |||
238 | |||
239 | |||
240 | do -- test hook presence in debug info | ||
241 | assert(not debug.gethook()) | ||
242 | local count = 0 | ||
243 | local function f () | ||
244 | assert(debug.getinfo(1).namewhat == "hook") | ||
245 | local sndline = string.match(debug.traceback(), "\n(.-)\n") | ||
246 | assert(string.find(sndline, "hook")) | ||
247 | count = count + 1 | ||
248 | end | ||
249 | debug.sethook(f, "l") | ||
250 | local a = 0 | ||
251 | _ENV.a = a | ||
252 | a = 1 | ||
253 | debug.sethook() | ||
254 | assert(count == 4) | ||
255 | end | ||
256 | |||
257 | |||
258 | a = {}; L = nil | ||
259 | local glob = 1 | ||
260 | local oldglob = glob | ||
261 | debug.sethook(function (e,l) | ||
262 | collectgarbage() -- force GC during a hook | ||
263 | local f, m, c = debug.gethook() | ||
264 | assert(m == 'crl' and c == 0) | ||
265 | if e == "line" then | ||
266 | if glob ~= oldglob then | ||
267 | L = l-1 -- get the first line where "glob" has changed | ||
268 | oldglob = glob | ||
269 | end | ||
270 | elseif e == "call" then | ||
271 | local f = debug.getinfo(2, "f").func | ||
272 | a[f] = 1 | ||
273 | else assert(e == "return") | ||
274 | end | ||
275 | end, "crl") | ||
276 | |||
277 | |||
278 | function f(a,b) | ||
279 | collectgarbage() | ||
280 | local _, x = debug.getlocal(1, 1) | ||
281 | local _, y = debug.getlocal(1, 2) | ||
282 | assert(x == a and y == b) | ||
283 | assert(debug.setlocal(2, 3, "pera") == "AA".."AA") | ||
284 | assert(debug.setlocal(2, 4, "maçã") == "B") | ||
285 | x = debug.getinfo(2) | ||
286 | assert(x.func == g and x.what == "Lua" and x.name == 'g' and | ||
287 | x.nups == 2 and string.find(x.source, "^@.*db%.lua$")) | ||
288 | glob = glob+1 | ||
289 | assert(debug.getinfo(1, "l").currentline == L+1) | ||
290 | assert(debug.getinfo(1, "l").currentline == L+2) | ||
291 | end | ||
292 | |||
293 | function foo() | ||
294 | glob = glob+1 | ||
295 | assert(debug.getinfo(1, "l").currentline == L+1) | ||
296 | end; foo() -- set L | ||
297 | -- check line counting inside strings and empty lines | ||
298 | |||
299 | _ = 'alo\ | ||
300 | alo' .. [[ | ||
301 | |||
302 | ]] | ||
303 | --[[ | ||
304 | ]] | ||
305 | assert(debug.getinfo(1, "l").currentline == L+11) -- check count of lines | ||
306 | |||
307 | |||
308 | function g (...) | ||
309 | local arg = {...} | ||
310 | do local a,b,c; a=math.sin(40); end | ||
311 | local feijao | ||
312 | local AAAA,B = "xuxu", "mamão" | ||
313 | f(AAAA,B) | ||
314 | assert(AAAA == "pera" and B == "maçã") | ||
315 | do | ||
316 | local B = 13 | ||
317 | local x,y = debug.getlocal(1,5) | ||
318 | assert(x == 'B' and y == 13) | ||
319 | end | ||
320 | end | ||
321 | |||
322 | g() | ||
323 | |||
324 | |||
325 | assert(a[f] and a[g] and a[assert] and a[debug.getlocal] and not a[print]) | ||
326 | |||
327 | |||
328 | -- tests for manipulating non-registered locals (C and Lua temporaries) | ||
329 | |||
330 | local n, v = debug.getlocal(0, 1) | ||
331 | assert(v == 0 and n == "(*temporary)") | ||
332 | local n, v = debug.getlocal(0, 2) | ||
333 | assert(v == 2 and n == "(*temporary)") | ||
334 | assert(not debug.getlocal(0, 3)) | ||
335 | assert(not debug.getlocal(0, 0)) | ||
336 | |||
337 | function f() | ||
338 | assert(select(2, debug.getlocal(2,3)) == 1) | ||
339 | assert(not debug.getlocal(2,4)) | ||
340 | debug.setlocal(2, 3, 10) | ||
341 | return 20 | ||
342 | end | ||
343 | |||
344 | function g(a,b) return (a+1) + f() end | ||
345 | |||
346 | assert(g(0,0) == 30) | ||
347 | |||
348 | |||
349 | debug.sethook(nil); | ||
350 | assert(debug.gethook() == nil) | ||
351 | |||
352 | |||
353 | -- minimal tests for setuservalue/getuservalue | ||
354 | do | ||
355 | assert(debug.setuservalue(io.stdin, 10) == nil) | ||
356 | local a, b = debug.getuservalue(io.stdin, 10) | ||
357 | assert(a == nil and not b) | ||
358 | end | ||
359 | |||
360 | -- testing iteraction between multiple values x hooks | ||
361 | do | ||
362 | local function f(...) return 3, ... end | ||
363 | local count = 0 | ||
364 | local a = {} | ||
365 | for i = 1, 100 do a[i] = i end | ||
366 | debug.sethook(function () count = count + 1 end, "", 1) | ||
367 | local t = {table.unpack(a)} | ||
368 | assert(#t == 100) | ||
369 | t = {table.unpack(a, 1, 3)} | ||
370 | assert(#t == 3) | ||
371 | t = {f(table.unpack(a, 1, 30))} | ||
372 | assert(#t == 31) | ||
373 | end | ||
374 | |||
375 | |||
376 | -- testing access to function arguments | ||
377 | |||
378 | local function collectlocals (level) | ||
379 | local tab = {} | ||
380 | for i = 1, math.huge do | ||
381 | local n, v = debug.getlocal(level + 1, i) | ||
382 | if not (n and string.find(n, "^[a-zA-Z0-9_]+$")) then | ||
383 | break -- consider only real variables | ||
384 | end | ||
385 | tab[n] = v | ||
386 | end | ||
387 | return tab | ||
388 | end | ||
389 | |||
390 | |||
391 | X = nil | ||
392 | a = {} | ||
393 | function a:f (a, b, ...) local arg = {...}; local c = 13 end | ||
394 | debug.sethook(function (e) | ||
395 | assert(e == "call") | ||
396 | dostring("XX = 12") -- test dostring inside hooks | ||
397 | -- testing errors inside hooks | ||
398 | assert(not pcall(load("a='joao'+1"))) | ||
399 | debug.sethook(function (e, l) | ||
400 | assert(debug.getinfo(2, "l").currentline == l) | ||
401 | local f,m,c = debug.gethook() | ||
402 | assert(e == "line") | ||
403 | assert(m == 'l' and c == 0) | ||
404 | debug.sethook(nil) -- hook is called only once | ||
405 | assert(not X) -- check that | ||
406 | X = collectlocals(2) | ||
407 | end, "l") | ||
408 | end, "c") | ||
409 | |||
410 | a:f(1,2,3,4,5) | ||
411 | assert(X.self == a and X.a == 1 and X.b == 2 and X.c == nil) | ||
412 | assert(XX == 12) | ||
413 | assert(debug.gethook() == nil) | ||
414 | |||
415 | |||
416 | -- testing access to local variables in return hook (bug in 5.2) | ||
417 | do | ||
418 | local X = false | ||
419 | |||
420 | local function foo (a, b, ...) | ||
421 | do local x,y,z end | ||
422 | local c, d = 10, 20 | ||
423 | return | ||
424 | end | ||
425 | |||
426 | local function aux () | ||
427 | if debug.getinfo(2).name == "foo" then | ||
428 | X = true -- to signal that it found 'foo' | ||
429 | local tab = {a = 100, b = 200, c = 10, d = 20} | ||
430 | for n, v in pairs(collectlocals(2)) do | ||
431 | assert(tab[n] == v) | ||
432 | tab[n] = undef | ||
433 | end | ||
434 | assert(next(tab) == nil) -- 'tab' must be empty | ||
435 | end | ||
436 | end | ||
437 | |||
438 | debug.sethook(aux, "r"); foo(100, 200); debug.sethook() | ||
439 | assert(X) | ||
440 | |||
441 | end | ||
442 | |||
443 | |||
444 | local function eqseq (t1, t2) | ||
445 | assert(#t1 == #t2) | ||
446 | for i = 1, #t1 do | ||
447 | assert(t1[i] == t2[i]) | ||
448 | end | ||
449 | end | ||
450 | |||
451 | |||
452 | do print("testing inspection of parameters/returned values") | ||
453 | local on = false | ||
454 | local inp, out | ||
455 | |||
456 | local function hook (event) | ||
457 | if not on then return end | ||
458 | local ar = debug.getinfo(2, "ruS") | ||
459 | local t = {} | ||
460 | for i = ar.ftransfer, ar.ftransfer + ar.ntransfer - 1 do | ||
461 | local _, v = debug.getlocal(2, i) | ||
462 | t[#t + 1] = v | ||
463 | end | ||
464 | if event == "return" then | ||
465 | out = t | ||
466 | else | ||
467 | inp = t | ||
468 | end | ||
469 | end | ||
470 | |||
471 | debug.sethook(hook, "cr") | ||
472 | |||
473 | on = true; math.sin(3); on = false | ||
474 | eqseq(inp, {3}); eqseq(out, {math.sin(3)}) | ||
475 | |||
476 | on = true; select(2, 10, 20, 30, 40); on = false | ||
477 | eqseq(inp, {2, 10, 20, 30, 40}); eqseq(out, {20, 30, 40}) | ||
478 | |||
479 | local function foo (a, ...) return ... end | ||
480 | local function foo1 () on = not on; return foo(20, 10, 0) end | ||
481 | foo1(); on = false | ||
482 | eqseq(inp, {20}); eqseq(out, {10, 0}) | ||
483 | |||
484 | debug.sethook() | ||
485 | end | ||
486 | |||
487 | |||
488 | |||
489 | -- testing upvalue access | ||
490 | local function getupvalues (f) | ||
491 | local t = {} | ||
492 | local i = 1 | ||
493 | while true do | ||
494 | local name, value = debug.getupvalue(f, i) | ||
495 | if not name then break end | ||
496 | assert(not t[name]) | ||
497 | t[name] = value | ||
498 | i = i + 1 | ||
499 | end | ||
500 | return t | ||
501 | end | ||
502 | |||
503 | local a,b,c = 1,2,3 | ||
504 | local function foo1 (a) b = a; return c end | ||
505 | local function foo2 (x) a = x; return c+b end | ||
506 | assert(not debug.getupvalue(foo1, 3)) | ||
507 | assert(not debug.getupvalue(foo1, 0)) | ||
508 | assert(not debug.setupvalue(foo1, 3, "xuxu")) | ||
509 | local t = getupvalues(foo1) | ||
510 | assert(t.a == nil and t.b == 2 and t.c == 3) | ||
511 | t = getupvalues(foo2) | ||
512 | assert(t.a == 1 and t.b == 2 and t.c == 3) | ||
513 | assert(debug.setupvalue(foo1, 1, "xuxu") == "b") | ||
514 | assert(({debug.getupvalue(foo2, 3)})[2] == "xuxu") | ||
515 | -- upvalues of C functions are allways "called" "" (the empty string) | ||
516 | assert(debug.getupvalue(string.gmatch("x", "x"), 1) == "") | ||
517 | |||
518 | |||
519 | -- testing count hooks | ||
520 | local a=0 | ||
521 | debug.sethook(function (e) a=a+1 end, "", 1) | ||
522 | a=0; for i=1,1000 do end; assert(1000 < a and a < 1012) | ||
523 | debug.sethook(function (e) a=a+1 end, "", 4) | ||
524 | a=0; for i=1,1000 do end; assert(250 < a and a < 255) | ||
525 | local f,m,c = debug.gethook() | ||
526 | assert(m == "" and c == 4) | ||
527 | debug.sethook(function (e) a=a+1 end, "", 4000) | ||
528 | a=0; for i=1,1000 do end; assert(a == 0) | ||
529 | |||
530 | do | ||
531 | debug.sethook(print, "", 2^24 - 1) -- count upperbound | ||
532 | local f,m,c = debug.gethook() | ||
533 | assert(({debug.gethook()})[3] == 2^24 - 1) | ||
534 | end | ||
535 | |||
536 | debug.sethook() | ||
537 | |||
538 | |||
539 | -- tests for tail calls | ||
540 | local function f (x) | ||
541 | if x then | ||
542 | assert(debug.getinfo(1, "S").what == "Lua") | ||
543 | assert(debug.getinfo(1, "t").istailcall == true) | ||
544 | local tail = debug.getinfo(2) | ||
545 | assert(tail.func == g1 and tail.istailcall == true) | ||
546 | assert(debug.getinfo(3, "S").what == "main") | ||
547 | print"+" | ||
548 | end | ||
549 | end | ||
550 | |||
551 | function g(x) return f(x) end | ||
552 | |||
553 | function g1(x) g(x) end | ||
554 | |||
555 | local function h (x) local f=g1; return f(x) end | ||
556 | |||
557 | h(true) | ||
558 | |||
559 | local b = {} | ||
560 | debug.sethook(function (e) table.insert(b, e) end, "cr") | ||
561 | h(false) | ||
562 | debug.sethook() | ||
563 | local res = {"return", -- first return (from sethook) | ||
564 | "call", "tail call", "call", "tail call", | ||
565 | "return", "return", | ||
566 | "call", -- last call (to sethook) | ||
567 | } | ||
568 | for i = 1, #res do assert(res[i] == table.remove(b, 1)) end | ||
569 | |||
570 | b = 0 | ||
571 | debug.sethook(function (e) | ||
572 | if e == "tail call" then | ||
573 | b = b + 1 | ||
574 | assert(debug.getinfo(2, "t").istailcall == true) | ||
575 | else | ||
576 | assert(debug.getinfo(2, "t").istailcall == false) | ||
577 | end | ||
578 | end, "c") | ||
579 | h(false) | ||
580 | debug.sethook() | ||
581 | assert(b == 2) -- two tail calls | ||
582 | |||
583 | lim = _soft and 3000 or 30000 | ||
584 | local function foo (x) | ||
585 | if x==0 then | ||
586 | assert(debug.getinfo(2).what == "main") | ||
587 | local info = debug.getinfo(1) | ||
588 | assert(info.istailcall == true and info.func == foo) | ||
589 | else return foo(x-1) | ||
590 | end | ||
591 | end | ||
592 | |||
593 | foo(lim) | ||
594 | |||
595 | |||
596 | print"+" | ||
597 | |||
598 | |||
599 | -- testing local function information | ||
600 | co = load[[ | ||
601 | local A = function () | ||
602 | return x | ||
603 | end | ||
604 | return | ||
605 | ]] | ||
606 | |||
607 | local a = 0 | ||
608 | -- 'A' should be visible to debugger only after its complete definition | ||
609 | debug.sethook(function (e, l) | ||
610 | if l == 3 then a = a + 1; assert(debug.getlocal(2, 1) == "(*temporary)") | ||
611 | elseif l == 4 then a = a + 1; assert(debug.getlocal(2, 1) == "A") | ||
612 | end | ||
613 | end, "l") | ||
614 | co() -- run local function definition | ||
615 | debug.sethook() -- turn off hook | ||
616 | assert(a == 2) -- ensure all two lines where hooked | ||
617 | |||
618 | -- testing traceback | ||
619 | |||
620 | assert(debug.traceback(print) == print) | ||
621 | assert(debug.traceback(print, 4) == print) | ||
622 | assert(string.find(debug.traceback("hi", 4), "^hi\n")) | ||
623 | assert(string.find(debug.traceback("hi"), "^hi\n")) | ||
624 | assert(not string.find(debug.traceback("hi"), "'debug.traceback'")) | ||
625 | assert(string.find(debug.traceback("hi", 0), "'debug.traceback'")) | ||
626 | assert(string.find(debug.traceback(), "^stack traceback:\n")) | ||
627 | |||
628 | do -- C-function names in traceback | ||
629 | local st, msg = (function () return pcall end)()(debug.traceback) | ||
630 | assert(st == true and string.find(msg, "pcall")) | ||
631 | end | ||
632 | |||
633 | |||
634 | -- testing nparams, nups e isvararg | ||
635 | local t = debug.getinfo(print, "u") | ||
636 | assert(t.isvararg == true and t.nparams == 0 and t.nups == 0) | ||
637 | |||
638 | t = debug.getinfo(function (a,b,c) end, "u") | ||
639 | assert(t.isvararg == false and t.nparams == 3 and t.nups == 0) | ||
640 | |||
641 | t = debug.getinfo(function (a,b,...) return t[a] end, "u") | ||
642 | assert(t.isvararg == true and t.nparams == 2 and t.nups == 1) | ||
643 | |||
644 | t = debug.getinfo(1) -- main | ||
645 | assert(t.isvararg == true and t.nparams == 0 and t.nups == 1 and | ||
646 | debug.getupvalue(t.func, 1) == "_ENV") | ||
647 | |||
648 | |||
649 | |||
650 | |||
651 | -- testing debugging of coroutines | ||
652 | |||
653 | local function checktraceback (co, p, level) | ||
654 | local tb = debug.traceback(co, nil, level) | ||
655 | local i = 0 | ||
656 | for l in string.gmatch(tb, "[^\n]+\n?") do | ||
657 | assert(i == 0 or string.find(l, p[i])) | ||
658 | i = i+1 | ||
659 | end | ||
660 | assert(p[i] == undef) | ||
661 | end | ||
662 | |||
663 | |||
664 | local function f (n) | ||
665 | if n > 0 then f(n-1) | ||
666 | else coroutine.yield() end | ||
667 | end | ||
668 | |||
669 | local co = coroutine.create(f) | ||
670 | coroutine.resume(co, 3) | ||
671 | checktraceback(co, {"yield", "db.lua", "db.lua", "db.lua", "db.lua"}) | ||
672 | checktraceback(co, {"db.lua", "db.lua", "db.lua", "db.lua"}, 1) | ||
673 | checktraceback(co, {"db.lua", "db.lua", "db.lua"}, 2) | ||
674 | checktraceback(co, {"db.lua"}, 4) | ||
675 | checktraceback(co, {}, 40) | ||
676 | |||
677 | |||
678 | co = coroutine.create(function (x) | ||
679 | local a = 1 | ||
680 | coroutine.yield(debug.getinfo(1, "l")) | ||
681 | coroutine.yield(debug.getinfo(1, "l").currentline) | ||
682 | return a | ||
683 | end) | ||
684 | |||
685 | local tr = {} | ||
686 | local foo = function (e, l) if l then table.insert(tr, l) end end | ||
687 | debug.sethook(co, foo, "lcr") | ||
688 | |||
689 | local _, l = coroutine.resume(co, 10) | ||
690 | local x = debug.getinfo(co, 1, "lfLS") | ||
691 | assert(x.currentline == l.currentline and x.activelines[x.currentline]) | ||
692 | assert(type(x.func) == "function") | ||
693 | for i=x.linedefined + 1, x.lastlinedefined do | ||
694 | assert(x.activelines[i]) | ||
695 | x.activelines[i] = undef | ||
696 | end | ||
697 | assert(next(x.activelines) == nil) -- no 'extra' elements | ||
698 | assert(not debug.getinfo(co, 2)) | ||
699 | local a,b = debug.getlocal(co, 1, 1) | ||
700 | assert(a == "x" and b == 10) | ||
701 | a,b = debug.getlocal(co, 1, 2) | ||
702 | assert(a == "a" and b == 1) | ||
703 | debug.setlocal(co, 1, 2, "hi") | ||
704 | assert(debug.gethook(co) == foo) | ||
705 | assert(#tr == 2 and | ||
706 | tr[1] == l.currentline-1 and tr[2] == l.currentline) | ||
707 | |||
708 | a,b,c = pcall(coroutine.resume, co) | ||
709 | assert(a and b and c == l.currentline+1) | ||
710 | checktraceback(co, {"yield", "in function <"}) | ||
711 | |||
712 | a,b = coroutine.resume(co) | ||
713 | assert(a and b == "hi") | ||
714 | assert(#tr == 4 and tr[4] == l.currentline+2) | ||
715 | assert(debug.gethook(co) == foo) | ||
716 | assert(not debug.gethook()) | ||
717 | checktraceback(co, {}) | ||
718 | |||
719 | |||
720 | -- check get/setlocal in coroutines | ||
721 | co = coroutine.create(function (x) | ||
722 | local a, b = coroutine.yield(x) | ||
723 | assert(a == 100 and b == nil) | ||
724 | return x | ||
725 | end) | ||
726 | a, b = coroutine.resume(co, 10) | ||
727 | assert(a and b == 10) | ||
728 | a, b = debug.getlocal(co, 1, 1) | ||
729 | assert(a == "x" and b == 10) | ||
730 | assert(not debug.getlocal(co, 1, 5)) | ||
731 | assert(debug.setlocal(co, 1, 1, 30) == "x") | ||
732 | assert(not debug.setlocal(co, 1, 5, 40)) | ||
733 | a, b = coroutine.resume(co, 100) | ||
734 | assert(a and b == 30) | ||
735 | |||
736 | |||
737 | -- check traceback of suspended (or dead with error) coroutines | ||
738 | |||
739 | function f(i) if i==0 then error(i) else coroutine.yield(); f(i-1) end end | ||
740 | |||
741 | co = coroutine.create(function (x) f(x) end) | ||
742 | a, b = coroutine.resume(co, 3) | ||
743 | t = {"'coroutine.yield'", "'f'", "in function <"} | ||
744 | while coroutine.status(co) == "suspended" do | ||
745 | checktraceback(co, t) | ||
746 | a, b = coroutine.resume(co) | ||
747 | table.insert(t, 2, "'f'") -- one more recursive call to 'f' | ||
748 | end | ||
749 | t[1] = "'error'" | ||
750 | checktraceback(co, t) | ||
751 | |||
752 | |||
753 | -- test acessing line numbers of a coroutine from a resume inside | ||
754 | -- a C function (this is a known bug in Lua 5.0) | ||
755 | |||
756 | local function g(x) | ||
757 | coroutine.yield(x) | ||
758 | end | ||
759 | |||
760 | local function f (i) | ||
761 | debug.sethook(function () end, "l") | ||
762 | for j=1,1000 do | ||
763 | g(i+j) | ||
764 | end | ||
765 | end | ||
766 | |||
767 | local co = coroutine.wrap(f) | ||
768 | co(10) | ||
769 | pcall(co) | ||
770 | pcall(co) | ||
771 | |||
772 | |||
773 | assert(type(debug.getregistry()) == "table") | ||
774 | |||
775 | |||
776 | -- test tagmethod information | ||
777 | local a = {} | ||
778 | local function f (t) | ||
779 | local info = debug.getinfo(1); | ||
780 | assert(info.namewhat == "metamethod") | ||
781 | a.op = info.name | ||
782 | return info.name | ||
783 | end | ||
784 | setmetatable(a, { | ||
785 | __index = f; __add = f; __div = f; __mod = f; __concat = f; __pow = f; | ||
786 | __mul = f; __idiv = f; __unm = f; __len = f; __sub = f; | ||
787 | __shl = f; __shr = f; __bor = f; __bxor = f; | ||
788 | __eq = f; __le = f; __lt = f; __unm = f; __len = f; __band = f; | ||
789 | __bnot = f; | ||
790 | }) | ||
791 | |||
792 | local b = setmetatable({}, getmetatable(a)) | ||
793 | |||
794 | assert(a[3] == "index" and a^3 == "pow" and a..a == "concat") | ||
795 | assert(a/3 == "div" and 3%a == "mod") | ||
796 | assert(a+3 == "add" and 3-a == "sub" and a*3 == "mul" and | ||
797 | -a == "unm" and #a == "len" and a&3 == "band") | ||
798 | assert(a|3 == "bor" and 3~a == "bxor" and a<<3 == "shift" and | ||
799 | a>>1 == "shift") | ||
800 | assert (a==b and a.op == "eq") | ||
801 | assert (a>=b and a.op == "order") | ||
802 | assert (a>b and a.op == "order") | ||
803 | assert(~a == "bnot") | ||
804 | |||
805 | do -- testing for-iterator name | ||
806 | local function f() | ||
807 | assert(debug.getinfo(1).name == "for iterator") | ||
808 | end | ||
809 | |||
810 | for i in f do end | ||
811 | end | ||
812 | |||
813 | |||
814 | do -- testing debug info for finalizers | ||
815 | local name = nil | ||
816 | |||
817 | -- create a piece of garbage with a finalizer | ||
818 | setmetatable({}, {__gc = function () | ||
819 | local t = debug.getinfo(2) -- get callee information | ||
820 | assert(t.namewhat == "metamethod") | ||
821 | name = t.name | ||
822 | end}) | ||
823 | |||
824 | -- repeat until previous finalizer runs (setting 'name') | ||
825 | repeat local a = {} until name | ||
826 | assert(name == "__gc") | ||
827 | end | ||
828 | |||
829 | |||
830 | do | ||
831 | print("testing traceback sizes") | ||
832 | |||
833 | local function countlines (s) | ||
834 | return select(2, string.gsub(s, "\n", "")) | ||
835 | end | ||
836 | |||
837 | local function deep (lvl, n) | ||
838 | if lvl == 0 then | ||
839 | return (debug.traceback("message", n)) | ||
840 | else | ||
841 | return (deep(lvl-1, n)) | ||
842 | end | ||
843 | end | ||
844 | |||
845 | local function checkdeep (total, start) | ||
846 | local s = deep(total, start) | ||
847 | local rest = string.match(s, "^message\nstack traceback:\n(.*)$") | ||
848 | local cl = countlines(rest) | ||
849 | -- at most 10 lines in first part, 11 in second, plus '...' | ||
850 | assert(cl <= 10 + 11 + 1) | ||
851 | local brk = string.find(rest, "%.%.%.") | ||
852 | if brk then -- does message have '...'? | ||
853 | local rest1 = string.sub(rest, 1, brk) | ||
854 | local rest2 = string.sub(rest, brk, #rest) | ||
855 | assert(countlines(rest1) == 10 and countlines(rest2) == 11) | ||
856 | else | ||
857 | assert(cl == total - start + 2) | ||
858 | end | ||
859 | end | ||
860 | |||
861 | for d = 1, 51, 10 do | ||
862 | for l = 1, d do | ||
863 | -- use coroutines to ensure complete control of the stack | ||
864 | coroutine.wrap(checkdeep)(d, l) | ||
865 | end | ||
866 | end | ||
867 | |||
868 | end | ||
869 | |||
870 | |||
871 | print("testing debug functions on chunk without debug info") | ||
872 | prog = [[-- program to be loaded without debug information | ||
873 | local debug = require'debug' | ||
874 | local a = 12 -- a local variable | ||
875 | |||
876 | local n, v = debug.getlocal(1, 1) | ||
877 | assert(n == "(*temporary)" and v == debug) -- unkown name but known value | ||
878 | n, v = debug.getlocal(1, 2) | ||
879 | assert(n == "(*temporary)" and v == 12) -- unkown name but known value | ||
880 | |||
881 | -- a function with an upvalue | ||
882 | local f = function () local x; return a end | ||
883 | n, v = debug.getupvalue(f, 1) | ||
884 | assert(n == "(*no name)" and v == 12) | ||
885 | assert(debug.setupvalue(f, 1, 13) == "(*no name)") | ||
886 | assert(a == 13) | ||
887 | |||
888 | local t = debug.getinfo(f) | ||
889 | assert(t.name == nil and t.linedefined > 0 and | ||
890 | t.lastlinedefined == t.linedefined and | ||
891 | t.short_src == "?") | ||
892 | assert(debug.getinfo(1).currentline == -1) | ||
893 | |||
894 | t = debug.getinfo(f, "L").activelines | ||
895 | assert(next(t) == nil) -- active lines are empty | ||
896 | |||
897 | -- dump/load a function without debug info | ||
898 | f = load(string.dump(f)) | ||
899 | |||
900 | t = debug.getinfo(f) | ||
901 | assert(t.name == nil and t.linedefined > 0 and | ||
902 | t.lastlinedefined == t.linedefined and | ||
903 | t.short_src == "?") | ||
904 | assert(debug.getinfo(1).currentline == -1) | ||
905 | |||
906 | return a | ||
907 | ]] | ||
908 | |||
909 | |||
910 | -- load 'prog' without debug info | ||
911 | local f = assert(load(string.dump(load(prog), true))) | ||
912 | |||
913 | assert(f() == 13) | ||
914 | |||
915 | do -- tests for 'source' in binary dumps | ||
916 | local prog = [[ | ||
917 | return function (x) | ||
918 | return function (y) | ||
919 | return x + y | ||
920 | end | ||
921 | end | ||
922 | ]] | ||
923 | local name = string.rep("x", 1000) | ||
924 | local p = assert(load(prog, name)) | ||
925 | -- load 'p' as a binary chunk with debug information | ||
926 | local c = string.dump(p) | ||
927 | assert(#c > 1000 and #c < 2000) -- no repetition of 'source' in dump | ||
928 | local f = assert(load(c)) | ||
929 | local g = f() | ||
930 | local h = g(3) | ||
931 | assert(h(5) == 8) | ||
932 | assert(debug.getinfo(f).source == name and -- all functions have 'source' | ||
933 | debug.getinfo(g).source == name and | ||
934 | debug.getinfo(h).source == name) | ||
935 | -- again, without debug info | ||
936 | local c = string.dump(p, true) | ||
937 | assert(#c < 500) -- no 'source' in dump | ||
938 | local f = assert(load(c)) | ||
939 | local g = f() | ||
940 | local h = g(30) | ||
941 | assert(h(50) == 80) | ||
942 | assert(debug.getinfo(f).source == '=?' and -- no function has 'source' | ||
943 | debug.getinfo(g).source == '=?' and | ||
944 | debug.getinfo(h).source == '=?') | ||
945 | end | ||
946 | |||
947 | print"OK" | ||
948 | |||
diff --git a/testes/errors.lua b/testes/errors.lua new file mode 100644 index 00000000..63a7b740 --- /dev/null +++ b/testes/errors.lua | |||
@@ -0,0 +1,554 @@ | |||
1 | -- $Id: errors.lua,v 1.97 2017/11/28 15:31:56 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print("testing errors") | ||
5 | |||
6 | local debug = require"debug" | ||
7 | |||
8 | -- avoid problems with 'strict' module (which may generate other error messages) | ||
9 | local mt = getmetatable(_G) or {} | ||
10 | local oldmm = mt.__index | ||
11 | mt.__index = nil | ||
12 | |||
13 | local function checkerr (msg, f, ...) | ||
14 | local st, err = pcall(f, ...) | ||
15 | assert(not st and string.find(err, msg)) | ||
16 | end | ||
17 | |||
18 | |||
19 | local function doit (s) | ||
20 | local f, msg = load(s) | ||
21 | if f == nil then return msg end | ||
22 | local cond, msg = pcall(f) | ||
23 | return (not cond) and msg | ||
24 | end | ||
25 | |||
26 | |||
27 | local function checkmessage (prog, msg) | ||
28 | local m = doit(prog) | ||
29 | assert(string.find(m, msg, 1, true)) | ||
30 | end | ||
31 | |||
32 | local function checksyntax (prog, extra, token, line) | ||
33 | local msg = doit(prog) | ||
34 | if not string.find(token, "^<%a") and not string.find(token, "^char%(") | ||
35 | then token = "'"..token.."'" end | ||
36 | token = string.gsub(token, "(%p)", "%%%1") | ||
37 | local pt = string.format([[^%%[string ".*"%%]:%d: .- near %s$]], | ||
38 | line, token) | ||
39 | assert(string.find(msg, pt)) | ||
40 | assert(string.find(msg, msg, 1, true)) | ||
41 | end | ||
42 | |||
43 | |||
44 | -- test error message with no extra info | ||
45 | assert(doit("error('hi', 0)") == 'hi') | ||
46 | |||
47 | -- test error message with no info | ||
48 | assert(doit("error()") == nil) | ||
49 | |||
50 | |||
51 | -- test common errors/errors that crashed in the past | ||
52 | assert(doit("table.unpack({}, 1, n=2^30)")) | ||
53 | assert(doit("a=math.sin()")) | ||
54 | assert(not doit("tostring(1)") and doit("tostring()")) | ||
55 | assert(doit"tonumber()") | ||
56 | assert(doit"repeat until 1; a") | ||
57 | assert(doit"return;;") | ||
58 | assert(doit"assert(false)") | ||
59 | assert(doit"assert(nil)") | ||
60 | assert(doit("function a (... , ...) end")) | ||
61 | assert(doit("function a (, ...) end")) | ||
62 | assert(doit("local t={}; t = t[#t] + 1")) | ||
63 | |||
64 | checksyntax([[ | ||
65 | local a = {4 | ||
66 | |||
67 | ]], "'}' expected (to close '{' at line 1)", "<eof>", 3) | ||
68 | |||
69 | |||
70 | if not T then | ||
71 | (Message or print) | ||
72 | ('\n >>> testC not active: skipping memory message test <<<\n') | ||
73 | else | ||
74 | print "testing memory error message" | ||
75 | local a = {} | ||
76 | for i = 1, 10000 do a[i] = true end -- preallocate array | ||
77 | collectgarbage() | ||
78 | T.totalmem(T.totalmem() + 10000) | ||
79 | -- force a memory error (by a small margin) | ||
80 | local st, msg = pcall(function() | ||
81 | for i = 1, 100000 do a[i] = tostring(i) end | ||
82 | end) | ||
83 | T.totalmem(0) | ||
84 | assert(not st and msg == "not enough" .. " memory") | ||
85 | end | ||
86 | |||
87 | |||
88 | -- tests for better error messages | ||
89 | |||
90 | checkmessage("a = {} + 1", "arithmetic") | ||
91 | checkmessage("a = {} | 1", "bitwise operation") | ||
92 | checkmessage("a = {} < 1", "attempt to compare") | ||
93 | checkmessage("a = {} <= 1", "attempt to compare") | ||
94 | |||
95 | checkmessage("a=1; bbbb=2; a=math.sin(3)+bbbb(3)", "global 'bbbb'") | ||
96 | checkmessage("a={}; do local a=1 end a:bbbb(3)", "method 'bbbb'") | ||
97 | checkmessage("local a={}; a.bbbb(3)", "field 'bbbb'") | ||
98 | assert(not string.find(doit"a={13}; local bbbb=1; a[bbbb](3)", "'bbbb'")) | ||
99 | checkmessage("a={13}; local bbbb=1; a[bbbb](3)", "number") | ||
100 | checkmessage("a=(1)..{}", "a table value") | ||
101 | |||
102 | checkmessage("a = #print", "length of a function value") | ||
103 | checkmessage("a = #3", "length of a number value") | ||
104 | |||
105 | aaa = nil | ||
106 | checkmessage("aaa.bbb:ddd(9)", "global 'aaa'") | ||
107 | checkmessage("local aaa={bbb=1}; aaa.bbb:ddd(9)", "field 'bbb'") | ||
108 | checkmessage("local aaa={bbb={}}; aaa.bbb:ddd(9)", "method 'ddd'") | ||
109 | checkmessage("local a,b,c; (function () a = b+1.1 end)()", "upvalue 'b'") | ||
110 | assert(not doit"local aaa={bbb={ddd=next}}; aaa.bbb:ddd(nil)") | ||
111 | |||
112 | -- upvalues being indexed do not go to the stack | ||
113 | checkmessage("local a,b,cc; (function () a = cc[1] end)()", "upvalue 'cc'") | ||
114 | checkmessage("local a,b,cc; (function () a.x = 1 end)()", "upvalue 'a'") | ||
115 | |||
116 | checkmessage("local _ENV = {x={}}; a = a + 1", "global 'a'") | ||
117 | |||
118 | checkmessage("b=1; local aaa={}; x=aaa+b", "local 'aaa'") | ||
119 | checkmessage("aaa={}; x=3.3/aaa", "global 'aaa'") | ||
120 | checkmessage("aaa=2; b=nil;x=aaa*b", "global 'b'") | ||
121 | checkmessage("aaa={}; x=-aaa", "global 'aaa'") | ||
122 | |||
123 | -- short circuit | ||
124 | checkmessage("a=1; local a,bbbb=2,3; a = math.sin(1) and bbbb(3)", | ||
125 | "local 'bbbb'") | ||
126 | checkmessage("a=1; local a,bbbb=2,3; a = bbbb(1) or a(3)", "local 'bbbb'") | ||
127 | checkmessage("local a,b,c,f = 1,1,1; f((a and b) or c)", "local 'f'") | ||
128 | checkmessage("local a,b,c = 1,1,1; ((a and b) or c)()", "call a number value") | ||
129 | assert(not string.find(doit"aaa={}; x=(aaa or aaa)+(aaa and aaa)", "'aaa'")) | ||
130 | assert(not string.find(doit"aaa={}; (aaa or aaa)()", "'aaa'")) | ||
131 | |||
132 | checkmessage("print(print < 10)", "function with number") | ||
133 | checkmessage("print(print < print)", "two function values") | ||
134 | checkmessage("print('10' < 10)", "string with number") | ||
135 | checkmessage("print(10 < '23')", "number with string") | ||
136 | |||
137 | -- float->integer conversions | ||
138 | checkmessage("local a = 2.0^100; x = a << 2", "local a") | ||
139 | checkmessage("local a = 1 >> 2.0^100", "has no integer representation") | ||
140 | checkmessage("local a = 10.1 << 2.0^100", "has no integer representation") | ||
141 | checkmessage("local a = 2.0^100 & 1", "has no integer representation") | ||
142 | checkmessage("local a = 2.0^100 & 1e100", "has no integer representation") | ||
143 | checkmessage("local a = 2.0 | 1e40", "has no integer representation") | ||
144 | checkmessage("local a = 2e100 ~ 1", "has no integer representation") | ||
145 | checkmessage("string.sub('a', 2.0^100)", "has no integer representation") | ||
146 | checkmessage("string.rep('a', 3.3)", "has no integer representation") | ||
147 | checkmessage("return 6e40 & 7", "has no integer representation") | ||
148 | checkmessage("return 34 << 7e30", "has no integer representation") | ||
149 | checkmessage("return ~-3e40", "has no integer representation") | ||
150 | checkmessage("return ~-3.009", "has no integer representation") | ||
151 | checkmessage("return 3.009 & 1", "has no integer representation") | ||
152 | checkmessage("return 34 >> {}", "table value") | ||
153 | checkmessage("a = 24 // 0", "divide by zero") | ||
154 | checkmessage("a = 1 % 0", "'n%0'") | ||
155 | |||
156 | |||
157 | -- passing light userdata instead of full userdata | ||
158 | _G.D = debug | ||
159 | checkmessage([[ | ||
160 | -- create light udata | ||
161 | local x = D.upvalueid(function () return debug end, 1) | ||
162 | D.setuservalue(x, {}) | ||
163 | ]], "light userdata") | ||
164 | _G.D = nil | ||
165 | |||
166 | do -- named objects (field '__name') | ||
167 | checkmessage("math.sin(io.input())", "(number expected, got FILE*)") | ||
168 | _G.XX = setmetatable({}, {__name = "My Type"}) | ||
169 | assert(string.find(tostring(XX), "^My Type")) | ||
170 | checkmessage("io.input(XX)", "(FILE* expected, got My Type)") | ||
171 | checkmessage("return XX + 1", "on a My Type value") | ||
172 | checkmessage("return ~io.stdin", "on a FILE* value") | ||
173 | checkmessage("return XX < XX", "two My Type values") | ||
174 | checkmessage("return {} < XX", "table with My Type") | ||
175 | checkmessage("return XX < io.stdin", "My Type with FILE*") | ||
176 | _G.XX = nil | ||
177 | end | ||
178 | |||
179 | -- global functions | ||
180 | checkmessage("(io.write or print){}", "io.write") | ||
181 | checkmessage("(collectgarbage or print){}", "collectgarbage") | ||
182 | |||
183 | -- errors in functions without debug info | ||
184 | do | ||
185 | local f = function (a) return a + 1 end | ||
186 | f = assert(load(string.dump(f, true))) | ||
187 | assert(f(3) == 4) | ||
188 | checkerr("^%?:%-1:", f, {}) | ||
189 | |||
190 | -- code with a move to a local var ('OP_MOV A B' with A<B) | ||
191 | f = function () local a; a = {}; return a + 2 end | ||
192 | -- no debug info (so that 'a' is unknown) | ||
193 | f = assert(load(string.dump(f, true))) | ||
194 | -- symbolic execution should not get lost | ||
195 | checkerr("^%?:%-1:.*table value", f) | ||
196 | end | ||
197 | |||
198 | |||
199 | -- tests for field accesses after RK limit | ||
200 | local t = {} | ||
201 | for i = 1, 1000 do | ||
202 | t[i] = "a = x" .. i | ||
203 | end | ||
204 | local s = table.concat(t, "; ") | ||
205 | t = nil | ||
206 | checkmessage(s.."; a = bbb + 1", "global 'bbb'") | ||
207 | checkmessage("local _ENV=_ENV;"..s.."; a = bbb + 1", "global 'bbb'") | ||
208 | checkmessage(s.."; local t = {}; a = t.bbb + 1", "field 'bbb'") | ||
209 | checkmessage(s.."; local t = {}; t:bbb()", "method 'bbb'") | ||
210 | |||
211 | checkmessage([[aaa=9 | ||
212 | repeat until 3==3 | ||
213 | local x=math.sin(math.cos(3)) | ||
214 | if math.sin(1) == x then return math.sin(1) end -- tail call | ||
215 | local a,b = 1, { | ||
216 | {x='a'..'b'..'c', y='b', z=x}, | ||
217 | {1,2,3,4,5} or 3+3<=3+3, | ||
218 | 3+1>3+1, | ||
219 | {d = x and aaa[x or y]}} | ||
220 | ]], "global 'aaa'") | ||
221 | |||
222 | checkmessage([[ | ||
223 | local x,y = {},1 | ||
224 | if math.sin(1) == 0 then return 3 end -- return | ||
225 | x.a()]], "field 'a'") | ||
226 | |||
227 | checkmessage([[ | ||
228 | prefix = nil | ||
229 | insert = nil | ||
230 | while 1 do | ||
231 | local a | ||
232 | if nil then break end | ||
233 | insert(prefix, a) | ||
234 | end]], "global 'insert'") | ||
235 | |||
236 | checkmessage([[ -- tail call | ||
237 | return math.sin("a") | ||
238 | ]], "'sin'") | ||
239 | |||
240 | checkmessage([[collectgarbage("nooption")]], "invalid option") | ||
241 | |||
242 | checkmessage([[x = print .. "a"]], "concatenate") | ||
243 | checkmessage([[x = "a" .. false]], "concatenate") | ||
244 | checkmessage([[x = {} .. 2]], "concatenate") | ||
245 | |||
246 | checkmessage("getmetatable(io.stdin).__gc()", "no value") | ||
247 | |||
248 | checkmessage([[ | ||
249 | local Var | ||
250 | local function main() | ||
251 | NoSuchName (function() Var=0 end) | ||
252 | end | ||
253 | main() | ||
254 | ]], "global 'NoSuchName'") | ||
255 | print'+' | ||
256 | |||
257 | a = {}; setmetatable(a, {__index = string}) | ||
258 | checkmessage("a:sub()", "bad self") | ||
259 | checkmessage("string.sub('a', {})", "#2") | ||
260 | checkmessage("('a'):sub{}", "#1") | ||
261 | |||
262 | checkmessage("table.sort({1,2,3}, table.sort)", "'table.sort'") | ||
263 | checkmessage("string.gsub('s', 's', setmetatable)", "'setmetatable'") | ||
264 | |||
265 | -- tests for errors in coroutines | ||
266 | |||
267 | local function f (n) | ||
268 | local c = coroutine.create(f) | ||
269 | local a,b = coroutine.resume(c) | ||
270 | return b | ||
271 | end | ||
272 | assert(string.find(f(), "C stack overflow")) | ||
273 | |||
274 | checkmessage("coroutine.yield()", "outside a coroutine") | ||
275 | |||
276 | f = coroutine.wrap(function () table.sort({1,2,3}, coroutine.yield) end) | ||
277 | checkerr("yield across", f) | ||
278 | |||
279 | |||
280 | -- testing size of 'source' info; size of buffer for that info is | ||
281 | -- LUA_IDSIZE, declared as 60 in luaconf. Get one position for '\0'. | ||
282 | idsize = 60 - 1 | ||
283 | local function checksize (source) | ||
284 | -- syntax error | ||
285 | local _, msg = load("x", source) | ||
286 | msg = string.match(msg, "^([^:]*):") -- get source (1st part before ':') | ||
287 | assert(msg:len() <= idsize) | ||
288 | end | ||
289 | |||
290 | for i = 60 - 10, 60 + 10 do -- check border cases around 60 | ||
291 | checksize("@" .. string.rep("x", i)) -- file names | ||
292 | checksize(string.rep("x", i - 10)) -- string sources | ||
293 | checksize("=" .. string.rep("x", i)) -- exact sources | ||
294 | end | ||
295 | |||
296 | |||
297 | -- testing line error | ||
298 | |||
299 | local function lineerror (s, l) | ||
300 | local err,msg = pcall(load(s)) | ||
301 | local line = string.match(msg, ":(%d+):") | ||
302 | assert((line and line+0) == l) | ||
303 | end | ||
304 | |||
305 | lineerror("local a\n for i=1,'a' do \n print(i) \n end", 2) | ||
306 | lineerror("\n local a \n for k,v in 3 \n do \n print(k) \n end", 3) | ||
307 | lineerror("\n\n for k,v in \n 3 \n do \n print(k) \n end", 4) | ||
308 | lineerror("function a.x.y ()\na=a+1\nend", 1) | ||
309 | |||
310 | lineerror("a = \na\n+\n{}", 3) | ||
311 | lineerror("a = \n3\n+\n(\n4\n/\nprint)", 6) | ||
312 | lineerror("a = \nprint\n+\n(\n4\n/\n7)", 3) | ||
313 | |||
314 | lineerror("a\n=\n-\n\nprint\n;", 3) | ||
315 | |||
316 | lineerror([[ | ||
317 | a | ||
318 | ( | ||
319 | 23) | ||
320 | ]], 1) | ||
321 | |||
322 | lineerror([[ | ||
323 | local a = {x = 13} | ||
324 | a | ||
325 | . | ||
326 | x | ||
327 | ( | ||
328 | 23 | ||
329 | ) | ||
330 | ]], 2) | ||
331 | |||
332 | lineerror([[ | ||
333 | local a = {x = 13} | ||
334 | a | ||
335 | . | ||
336 | x | ||
337 | ( | ||
338 | 23 + a | ||
339 | ) | ||
340 | ]], 6) | ||
341 | |||
342 | local p = [[ | ||
343 | function g() f() end | ||
344 | function f(x) error('a', X) end | ||
345 | g() | ||
346 | ]] | ||
347 | X=3;lineerror((p), 3) | ||
348 | X=0;lineerror((p), nil) | ||
349 | X=1;lineerror((p), 2) | ||
350 | X=2;lineerror((p), 1) | ||
351 | |||
352 | |||
353 | if not _soft then | ||
354 | -- several tests that exaust the Lua stack | ||
355 | collectgarbage() | ||
356 | print"testing stack overflow" | ||
357 | C = 0 | ||
358 | local l = debug.getinfo(1, "l").currentline; function y () C=C+1; y() end | ||
359 | |||
360 | local function checkstackmessage (m) | ||
361 | return (string.find(m, "stack overflow")) | ||
362 | end | ||
363 | -- repeated stack overflows (to check stack recovery) | ||
364 | assert(checkstackmessage(doit('y()'))) | ||
365 | print('+') | ||
366 | assert(checkstackmessage(doit('y()'))) | ||
367 | print('+') | ||
368 | assert(checkstackmessage(doit('y()'))) | ||
369 | print('+') | ||
370 | |||
371 | |||
372 | -- error lines in stack overflow | ||
373 | C = 0 | ||
374 | local l1 | ||
375 | local function g(x) | ||
376 | l1 = debug.getinfo(x, "l").currentline; y() | ||
377 | end | ||
378 | local _, stackmsg = xpcall(g, debug.traceback, 1) | ||
379 | print('+') | ||
380 | local stack = {} | ||
381 | for line in string.gmatch(stackmsg, "[^\n]*") do | ||
382 | local curr = string.match(line, ":(%d+):") | ||
383 | if curr then table.insert(stack, tonumber(curr)) end | ||
384 | end | ||
385 | local i=1 | ||
386 | while stack[i] ~= l1 do | ||
387 | assert(stack[i] == l) | ||
388 | i = i+1 | ||
389 | end | ||
390 | assert(i > 15) | ||
391 | |||
392 | |||
393 | -- error in error handling | ||
394 | local res, msg = xpcall(error, error) | ||
395 | assert(not res and type(msg) == 'string') | ||
396 | print('+') | ||
397 | |||
398 | local function f (x) | ||
399 | if x==0 then error('a\n') | ||
400 | else | ||
401 | local aux = function () return f(x-1) end | ||
402 | local a,b = xpcall(aux, aux) | ||
403 | return a,b | ||
404 | end | ||
405 | end | ||
406 | f(3) | ||
407 | |||
408 | local function loop (x,y,z) return 1 + loop(x, y, z) end | ||
409 | |||
410 | local res, msg = xpcall(loop, function (m) | ||
411 | assert(string.find(m, "stack overflow")) | ||
412 | checkerr("error handling", loop) | ||
413 | assert(math.sin(0) == 0) | ||
414 | return 15 | ||
415 | end) | ||
416 | assert(msg == 15) | ||
417 | |||
418 | local f = function () | ||
419 | for i = 999900, 1000000, 1 do table.unpack({}, 1, i) end | ||
420 | end | ||
421 | checkerr("too many results", f) | ||
422 | |||
423 | end | ||
424 | |||
425 | |||
426 | do | ||
427 | -- non string messages | ||
428 | local t = {} | ||
429 | local res, msg = pcall(function () error(t) end) | ||
430 | assert(not res and msg == t) | ||
431 | |||
432 | res, msg = pcall(function () error(nil) end) | ||
433 | assert(not res and msg == nil) | ||
434 | |||
435 | local function f() error{msg='x'} end | ||
436 | res, msg = xpcall(f, function (r) return {msg=r.msg..'y'} end) | ||
437 | assert(msg.msg == 'xy') | ||
438 | |||
439 | -- 'assert' with extra arguments | ||
440 | res, msg = pcall(assert, false, "X", t) | ||
441 | assert(not res and msg == "X") | ||
442 | |||
443 | -- 'assert' with no message | ||
444 | res, msg = pcall(function () assert(false) end) | ||
445 | local line = string.match(msg, "%w+%.lua:(%d+): assertion failed!$") | ||
446 | assert(tonumber(line) == debug.getinfo(1, "l").currentline - 2) | ||
447 | |||
448 | -- 'assert' with non-string messages | ||
449 | res, msg = pcall(assert, false, t) | ||
450 | assert(not res and msg == t) | ||
451 | |||
452 | res, msg = pcall(assert, nil, nil) | ||
453 | assert(not res and msg == nil) | ||
454 | |||
455 | -- 'assert' without arguments | ||
456 | res, msg = pcall(assert) | ||
457 | assert(not res and string.find(msg, "value expected")) | ||
458 | end | ||
459 | |||
460 | -- xpcall with arguments | ||
461 | a, b, c = xpcall(string.find, error, "alo", "al") | ||
462 | assert(a and b == 1 and c == 2) | ||
463 | a, b, c = xpcall(string.find, function (x) return {} end, true, "al") | ||
464 | assert(not a and type(b) == "table" and c == nil) | ||
465 | |||
466 | |||
467 | print("testing tokens in error messages") | ||
468 | checksyntax("syntax error", "", "error", 1) | ||
469 | checksyntax("1.000", "", "1.000", 1) | ||
470 | checksyntax("[[a]]", "", "[[a]]", 1) | ||
471 | checksyntax("'aa'", "", "'aa'", 1) | ||
472 | checksyntax("while << do end", "", "<<", 1) | ||
473 | checksyntax("for >> do end", "", ">>", 1) | ||
474 | |||
475 | -- test invalid non-printable char in a chunk | ||
476 | checksyntax("a\1a = 1", "", "<\\1>", 1) | ||
477 | |||
478 | -- test 255 as first char in a chunk | ||
479 | checksyntax("\255a = 1", "", "<\\255>", 1) | ||
480 | |||
481 | doit('I = load("a=9+"); a=3') | ||
482 | assert(a==3 and I == nil) | ||
483 | print('+') | ||
484 | |||
485 | lim = 1000 | ||
486 | if _soft then lim = 100 end | ||
487 | for i=1,lim do | ||
488 | doit('a = ') | ||
489 | doit('a = 4+nil') | ||
490 | end | ||
491 | |||
492 | |||
493 | -- testing syntax limits | ||
494 | |||
495 | local function testrep (init, rep, close, repc) | ||
496 | local s = init .. string.rep(rep, 100) .. close .. string.rep(repc, 100) | ||
497 | assert(load(s)) -- 100 levels is OK | ||
498 | s = init .. string.rep(rep, 10000) | ||
499 | local res, msg = load(s) -- 10000 levels not ok | ||
500 | assert(not res and (string.find(msg, "too many registers") or | ||
501 | string.find(msg, "stack overflow"))) | ||
502 | end | ||
503 | |||
504 | testrep("local a; a", ",a", "= 1", ",1") -- multiple assignment | ||
505 | testrep("local a; a=", "{", "0", "}") | ||
506 | testrep("local a; a=", "(", "2", ")") | ||
507 | testrep("local a; ", "a(", "2", ")") | ||
508 | testrep("", "do ", "", " end") | ||
509 | testrep("", "while a do ", "", " end") | ||
510 | testrep("local a; ", "if a then else ", "", " end") | ||
511 | testrep("", "function foo () ", "", " end") | ||
512 | testrep("local a; a=", "a..", "a", "") | ||
513 | testrep("local a; a=", "a^", "a", "") | ||
514 | |||
515 | checkmessage("a = f(x" .. string.rep(",x", 260) .. ")", "too many registers") | ||
516 | |||
517 | |||
518 | -- testing other limits | ||
519 | |||
520 | -- upvalues | ||
521 | local lim = 127 | ||
522 | local s = "local function fooA ()\n local " | ||
523 | for j = 1,lim do | ||
524 | s = s.."a"..j..", " | ||
525 | end | ||
526 | s = s.."b,c\n" | ||
527 | s = s.."local function fooB ()\n local " | ||
528 | for j = 1,lim do | ||
529 | s = s.."b"..j..", " | ||
530 | end | ||
531 | s = s.."b\n" | ||
532 | s = s.."function fooC () return b+c" | ||
533 | local c = 1+2 | ||
534 | for j = 1,lim do | ||
535 | s = s.."+a"..j.."+b"..j | ||
536 | c = c + 2 | ||
537 | end | ||
538 | s = s.."\nend end end" | ||
539 | local a,b = load(s) | ||
540 | assert(c > 255 and string.find(b, "too many upvalues") and | ||
541 | string.find(b, "line 5")) | ||
542 | |||
543 | -- local variables | ||
544 | s = "\nfunction foo ()\n local " | ||
545 | for j = 1,300 do | ||
546 | s = s.."a"..j..", " | ||
547 | end | ||
548 | s = s.."b\n" | ||
549 | local a,b = load(s) | ||
550 | assert(string.find(b, "line 2") and string.find(b, "too many local variables")) | ||
551 | |||
552 | mt.__index = oldmm | ||
553 | |||
554 | print('OK') | ||
diff --git a/testes/events.lua b/testes/events.lua new file mode 100644 index 00000000..cf064d3d --- /dev/null +++ b/testes/events.lua | |||
@@ -0,0 +1,476 @@ | |||
1 | -- $Id: events.lua,v 1.52 2018/03/12 13:51:02 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing metatables') | ||
5 | |||
6 | local debug = require'debug' | ||
7 | |||
8 | X = 20; B = 30 | ||
9 | |||
10 | _ENV = setmetatable({}, {__index=_G}) | ||
11 | |||
12 | collectgarbage() | ||
13 | |||
14 | X = X+10 | ||
15 | assert(X == 30 and _G.X == 20) | ||
16 | B = false | ||
17 | assert(B == false) | ||
18 | _ENV["B"] = undef | ||
19 | assert(B == 30) | ||
20 | |||
21 | assert(getmetatable{} == nil) | ||
22 | assert(getmetatable(4) == nil) | ||
23 | assert(getmetatable(nil) == nil) | ||
24 | a={name = "NAME"}; setmetatable(a, {__metatable = "xuxu", | ||
25 | __tostring=function(x) return x.name end}) | ||
26 | assert(getmetatable(a) == "xuxu") | ||
27 | assert(tostring(a) == "NAME") | ||
28 | -- cannot change a protected metatable | ||
29 | assert(pcall(setmetatable, a, {}) == false) | ||
30 | a.name = "gororoba" | ||
31 | assert(tostring(a) == "gororoba") | ||
32 | |||
33 | local a, t = {10,20,30; x="10", y="20"}, {} | ||
34 | assert(setmetatable(a,t) == a) | ||
35 | assert(getmetatable(a) == t) | ||
36 | assert(setmetatable(a,nil) == a) | ||
37 | assert(getmetatable(a) == nil) | ||
38 | assert(setmetatable(a,t) == a) | ||
39 | |||
40 | |||
41 | function f (t, i, e) | ||
42 | assert(not e) | ||
43 | local p = rawget(t, "parent") | ||
44 | return (p and p[i]+3), "dummy return" | ||
45 | end | ||
46 | |||
47 | t.__index = f | ||
48 | |||
49 | a.parent = {z=25, x=12, [4] = 24} | ||
50 | assert(a[1] == 10 and a.z == 28 and a[4] == 27 and a.x == "10") | ||
51 | |||
52 | collectgarbage() | ||
53 | |||
54 | a = setmetatable({}, t) | ||
55 | function f(t, i, v) rawset(t, i, v-3) end | ||
56 | setmetatable(t, t) -- causes a bug in 5.1 ! | ||
57 | t.__newindex = f | ||
58 | a[1] = 30; a.x = "101"; a[5] = 200 | ||
59 | assert(a[1] == 27 and a.x == 98 and a[5] == 197) | ||
60 | |||
61 | do -- bug in Lua 5.3.2 | ||
62 | local mt = {} | ||
63 | mt.__newindex = mt | ||
64 | local t = setmetatable({}, mt) | ||
65 | t[1] = 10 -- will segfault on some machines | ||
66 | assert(mt[1] == 10) | ||
67 | end | ||
68 | |||
69 | |||
70 | local c = {} | ||
71 | a = setmetatable({}, t) | ||
72 | t.__newindex = c | ||
73 | t.__index = c | ||
74 | a[1] = 10; a[2] = 20; a[3] = 90; | ||
75 | for i = 4, 20 do a[i] = i * 10 end | ||
76 | assert(a[1] == 10 and a[2] == 20 and a[3] == 90) | ||
77 | for i = 4, 20 do assert(a[i] == i * 10) end | ||
78 | assert(next(a) == nil) | ||
79 | |||
80 | |||
81 | do | ||
82 | local a; | ||
83 | a = setmetatable({}, {__index = setmetatable({}, | ||
84 | {__index = setmetatable({}, | ||
85 | {__index = function (_,n) return a[n-3]+4, "lixo" end})})}) | ||
86 | a[0] = 20 | ||
87 | for i=0,10 do | ||
88 | assert(a[i*3] == 20 + i*4) | ||
89 | end | ||
90 | end | ||
91 | |||
92 | |||
93 | do -- newindex | ||
94 | local foi | ||
95 | local a = {} | ||
96 | for i=1,10 do a[i] = 0; a['a'..i] = 0; end | ||
97 | setmetatable(a, {__newindex = function (t,k,v) foi=true; rawset(t,k,v) end}) | ||
98 | foi = false; a[1]=0; assert(not foi) | ||
99 | foi = false; a['a1']=0; assert(not foi) | ||
100 | foi = false; a['a11']=0; assert(foi) | ||
101 | foi = false; a[11]=0; assert(foi) | ||
102 | foi = false; a[1]=undef; assert(not foi) | ||
103 | a[1] = undef | ||
104 | foi = false; a[1]=nil; assert(foi) | ||
105 | end | ||
106 | |||
107 | |||
108 | setmetatable(t, nil) | ||
109 | function f (t, ...) return t, {...} end | ||
110 | t.__call = f | ||
111 | |||
112 | do | ||
113 | local x,y = a(table.unpack{'a', 1}) | ||
114 | assert(x==a and y[1]=='a' and y[2]==1 and y[3]==undef) | ||
115 | x,y = a() | ||
116 | assert(x==a and y[1]==undef) | ||
117 | end | ||
118 | |||
119 | |||
120 | local b = setmetatable({}, t) | ||
121 | setmetatable(b,t) | ||
122 | |||
123 | function f(op) | ||
124 | return function (...) cap = {[0] = op, ...} ; return (...) end | ||
125 | end | ||
126 | t.__add = f("add") | ||
127 | t.__sub = f("sub") | ||
128 | t.__mul = f("mul") | ||
129 | t.__div = f("div") | ||
130 | t.__idiv = f("idiv") | ||
131 | t.__mod = f("mod") | ||
132 | t.__unm = f("unm") | ||
133 | t.__pow = f("pow") | ||
134 | t.__len = f("len") | ||
135 | t.__band = f("band") | ||
136 | t.__bor = f("bor") | ||
137 | t.__bxor = f("bxor") | ||
138 | t.__shl = f("shl") | ||
139 | t.__shr = f("shr") | ||
140 | t.__bnot = f("bnot") | ||
141 | |||
142 | -- Some tests are done inside small anonymous functions to ensure | ||
143 | -- that constants go to constant table even in debug compilation, | ||
144 | -- when the constant table is very small. | ||
145 | assert(b+5 == b) | ||
146 | assert(cap[0] == "add" and cap[1] == b and cap[2] == 5 and cap[3]==undef) | ||
147 | assert(b+'5' == b) | ||
148 | assert(cap[0] == "add" and cap[1] == b and cap[2] == '5' and cap[3]==undef) | ||
149 | assert(5+b == 5) | ||
150 | assert(cap[0] == "add" and cap[1] == 5 and cap[2] == b and cap[3]==undef) | ||
151 | assert('5'+b == '5') | ||
152 | assert(cap[0] == "add" and cap[1] == '5' and cap[2] == b and cap[3]==undef) | ||
153 | b=b-3; assert(getmetatable(b) == t) | ||
154 | assert(cap[0] == "sub" and cap[1] == b and cap[2] == 3 and cap[3]==undef) | ||
155 | assert(5-a == 5) | ||
156 | assert(cap[0] == "sub" and cap[1] == 5 and cap[2] == a and cap[3]==undef) | ||
157 | assert('5'-a == '5') | ||
158 | assert(cap[0] == "sub" and cap[1] == '5' and cap[2] == a and cap[3]==undef) | ||
159 | assert(a*a == a) | ||
160 | assert(cap[0] == "mul" and cap[1] == a and cap[2] == a and cap[3]==undef) | ||
161 | assert(a/0 == a) | ||
162 | assert(cap[0] == "div" and cap[1] == a and cap[2] == 0 and cap[3]==undef) | ||
163 | assert(a%2 == a) | ||
164 | assert(cap[0] == "mod" and cap[1] == a and cap[2] == 2 and cap[3]==undef) | ||
165 | assert(a // (1/0) == a) | ||
166 | assert(cap[0] == "idiv" and cap[1] == a and cap[2] == 1/0 and cap[3]==undef) | ||
167 | ;(function () assert(a & "hi" == a) end)() | ||
168 | assert(cap[0] == "band" and cap[1] == a and cap[2] == "hi" and cap[3]==undef) | ||
169 | ;(function () assert(10 & a == 10) end)() | ||
170 | assert(cap[0] == "band" and cap[1] == 10 and cap[2] == a and cap[3]==undef) | ||
171 | ;(function () assert(a | 10 == a) end)() | ||
172 | assert(cap[0] == "bor" and cap[1] == a and cap[2] == 10 and cap[3]==undef) | ||
173 | assert(a | "hi" == a) | ||
174 | assert(cap[0] == "bor" and cap[1] == a and cap[2] == "hi" and cap[3]==undef) | ||
175 | assert("hi" ~ a == "hi") | ||
176 | assert(cap[0] == "bxor" and cap[1] == "hi" and cap[2] == a and cap[3]==undef) | ||
177 | ;(function () assert(10 ~ a == 10) end)() | ||
178 | assert(cap[0] == "bxor" and cap[1] == 10 and cap[2] == a and cap[3]==undef) | ||
179 | assert(-a == a) | ||
180 | assert(cap[0] == "unm" and cap[1] == a) | ||
181 | assert(a^4 == a) | ||
182 | assert(cap[0] == "pow" and cap[1] == a and cap[2] == 4 and cap[3]==undef) | ||
183 | assert(a^'4' == a) | ||
184 | assert(cap[0] == "pow" and cap[1] == a and cap[2] == '4' and cap[3]==undef) | ||
185 | assert(4^a == 4) | ||
186 | assert(cap[0] == "pow" and cap[1] == 4 and cap[2] == a and cap[3]==undef) | ||
187 | assert('4'^a == '4') | ||
188 | assert(cap[0] == "pow" and cap[1] == '4' and cap[2] == a and cap[3]==undef) | ||
189 | assert(#a == a) | ||
190 | assert(cap[0] == "len" and cap[1] == a) | ||
191 | assert(~a == a) | ||
192 | assert(cap[0] == "bnot" and cap[1] == a) | ||
193 | assert(a << 3 == a) | ||
194 | assert(cap[0] == "shl" and cap[1] == a and cap[2] == 3) | ||
195 | assert(1.5 >> a == 1.5) | ||
196 | assert(cap[0] == "shr" and cap[1] == 1.5 and cap[2] == a) | ||
197 | |||
198 | |||
199 | -- test for rawlen | ||
200 | t = setmetatable({1,2,3}, {__len = function () return 10 end}) | ||
201 | assert(#t == 10 and rawlen(t) == 3) | ||
202 | assert(rawlen"abc" == 3) | ||
203 | assert(not pcall(rawlen, io.stdin)) | ||
204 | assert(not pcall(rawlen, 34)) | ||
205 | assert(not pcall(rawlen)) | ||
206 | |||
207 | -- rawlen for long strings | ||
208 | assert(rawlen(string.rep('a', 1000)) == 1000) | ||
209 | |||
210 | |||
211 | t = {} | ||
212 | t.__lt = function (a,b,c) | ||
213 | collectgarbage() | ||
214 | assert(c == nil) | ||
215 | if type(a) == 'table' then a = a.x end | ||
216 | if type(b) == 'table' then b = b.x end | ||
217 | return a<b, "dummy" | ||
218 | end | ||
219 | |||
220 | function Op(x) return setmetatable({x=x}, t) end | ||
221 | |||
222 | local function test () | ||
223 | assert(not(Op(1)<Op(1)) and (Op(1)<Op(2)) and not(Op(2)<Op(1))) | ||
224 | assert(not(1 < Op(1)) and (Op(1) < 2) and not(2 < Op(1))) | ||
225 | assert(not(Op('a')<Op('a')) and (Op('a')<Op('b')) and not(Op('b')<Op('a'))) | ||
226 | assert(not('a' < Op('a')) and (Op('a') < 'b') and not(Op('b') < Op('a'))) | ||
227 | assert((Op(1)<=Op(1)) and (Op(1)<=Op(2)) and not(Op(2)<=Op(1))) | ||
228 | assert((Op('a')<=Op('a')) and (Op('a')<=Op('b')) and not(Op('b')<=Op('a'))) | ||
229 | assert(not(Op(1)>Op(1)) and not(Op(1)>Op(2)) and (Op(2)>Op(1))) | ||
230 | assert(not(Op('a')>Op('a')) and not(Op('a')>Op('b')) and (Op('b')>Op('a'))) | ||
231 | assert((Op(1)>=Op(1)) and not(Op(1)>=Op(2)) and (Op(2)>=Op(1))) | ||
232 | assert((1 >= Op(1)) and not(1 >= Op(2)) and (Op(2) >= 1)) | ||
233 | assert((Op('a')>=Op('a')) and not(Op('a')>=Op('b')) and (Op('b')>=Op('a'))) | ||
234 | assert(('a' >= Op('a')) and not(Op('a') >= 'b') and (Op('b') >= Op('a'))) | ||
235 | end | ||
236 | |||
237 | test() | ||
238 | |||
239 | t.__le = function (a,b,c) | ||
240 | assert(c == nil) | ||
241 | if type(a) == 'table' then a = a.x end | ||
242 | if type(b) == 'table' then b = b.x end | ||
243 | return a<=b, "dummy" | ||
244 | end | ||
245 | |||
246 | test() -- retest comparisons, now using both `lt' and `le' | ||
247 | |||
248 | |||
249 | -- test `partial order' | ||
250 | |||
251 | local function rawSet(x) | ||
252 | local y = {} | ||
253 | for _,k in pairs(x) do y[k] = 1 end | ||
254 | return y | ||
255 | end | ||
256 | |||
257 | local function Set(x) | ||
258 | return setmetatable(rawSet(x), t) | ||
259 | end | ||
260 | |||
261 | t.__lt = function (a,b) | ||
262 | for k in pairs(a) do | ||
263 | if not b[k] then return false end | ||
264 | b[k] = undef | ||
265 | end | ||
266 | return next(b) ~= nil | ||
267 | end | ||
268 | |||
269 | t.__le = nil | ||
270 | |||
271 | assert(Set{1,2,3} < Set{1,2,3,4}) | ||
272 | assert(not(Set{1,2,3,4} < Set{1,2,3,4})) | ||
273 | assert((Set{1,2,3,4} <= Set{1,2,3,4})) | ||
274 | assert((Set{1,2,3,4} >= Set{1,2,3,4})) | ||
275 | assert((Set{1,3} <= Set{3,5})) -- wrong!! model needs a `le' method ;-) | ||
276 | |||
277 | t.__le = function (a,b) | ||
278 | for k in pairs(a) do | ||
279 | if not b[k] then return false end | ||
280 | end | ||
281 | return true | ||
282 | end | ||
283 | |||
284 | assert(not (Set{1,3} <= Set{3,5})) -- now its OK! | ||
285 | assert(not(Set{1,3} <= Set{3,5})) | ||
286 | assert(not(Set{1,3} >= Set{3,5})) | ||
287 | |||
288 | t.__eq = function (a,b) | ||
289 | for k in pairs(a) do | ||
290 | if not b[k] then return false end | ||
291 | b[k] = undef | ||
292 | end | ||
293 | return next(b) == nil | ||
294 | end | ||
295 | |||
296 | local s = Set{1,3,5} | ||
297 | assert(s == Set{3,5,1}) | ||
298 | assert(not rawequal(s, Set{3,5,1})) | ||
299 | assert(rawequal(s, s)) | ||
300 | assert(Set{1,3,5,1} == rawSet{3,5,1}) | ||
301 | assert(rawSet{1,3,5,1} == Set{3,5,1}) | ||
302 | assert(Set{1,3,5} ~= Set{3,5,1,6}) | ||
303 | |||
304 | -- '__eq' is not used for table accesses | ||
305 | t[Set{1,3,5}] = 1 | ||
306 | assert(t[Set{1,3,5}] == undef) | ||
307 | |||
308 | |||
309 | if not T then | ||
310 | (Message or print)('\n >>> testC not active: skipping tests for \z | ||
311 | userdata <<<\n') | ||
312 | else | ||
313 | local u1 = T.newuserdata(0, 1) | ||
314 | local u2 = T.newuserdata(0, 1) | ||
315 | local u3 = T.newuserdata(0, 1) | ||
316 | assert(u1 ~= u2 and u1 ~= u3) | ||
317 | debug.setuservalue(u1, 1); | ||
318 | debug.setuservalue(u2, 2); | ||
319 | debug.setuservalue(u3, 1); | ||
320 | debug.setmetatable(u1, {__eq = function (a, b) | ||
321 | return debug.getuservalue(a) == debug.getuservalue(b) | ||
322 | end}) | ||
323 | debug.setmetatable(u2, {__eq = function (a, b) | ||
324 | return true | ||
325 | end}) | ||
326 | assert(u1 == u3 and u3 == u1 and u1 ~= u2) | ||
327 | assert(u2 == u1 and u2 == u3 and u3 == u2) | ||
328 | assert(u2 ~= {}) -- different types cannot be equal | ||
329 | |||
330 | local mirror = {} | ||
331 | debug.setmetatable(u3, {__index = mirror, __newindex = mirror}) | ||
332 | for i = 1, 10 do u3[i] = i end | ||
333 | for i = 1, 10 do assert(u3[i] == i) end | ||
334 | end | ||
335 | |||
336 | |||
337 | t.__concat = function (a,b,c) | ||
338 | assert(c == nil) | ||
339 | if type(a) == 'table' then a = a.val end | ||
340 | if type(b) == 'table' then b = b.val end | ||
341 | if A then return a..b | ||
342 | else | ||
343 | return setmetatable({val=a..b}, t) | ||
344 | end | ||
345 | end | ||
346 | |||
347 | c = {val="c"}; setmetatable(c, t) | ||
348 | d = {val="d"}; setmetatable(d, t) | ||
349 | |||
350 | A = true | ||
351 | assert(c..d == 'cd') | ||
352 | assert(0 .."a".."b"..c..d.."e".."f"..(5+3).."g" == "0abcdef8g") | ||
353 | |||
354 | A = false | ||
355 | assert((c..d..c..d).val == 'cdcd') | ||
356 | x = c..d | ||
357 | assert(getmetatable(x) == t and x.val == 'cd') | ||
358 | x = 0 .."a".."b"..c..d.."e".."f".."g" | ||
359 | assert(x.val == "0abcdefg") | ||
360 | |||
361 | |||
362 | -- concat metamethod x numbers (bug in 5.1.1) | ||
363 | c = {} | ||
364 | local x | ||
365 | setmetatable(c, {__concat = function (a,b) | ||
366 | assert(type(a) == "number" and b == c or type(b) == "number" and a == c) | ||
367 | return c | ||
368 | end}) | ||
369 | assert(c..5 == c and 5 .. c == c) | ||
370 | assert(4 .. c .. 5 == c and 4 .. 5 .. 6 .. 7 .. c == c) | ||
371 | |||
372 | |||
373 | -- test comparison compatibilities | ||
374 | local t1, t2, c, d | ||
375 | t1 = {}; c = {}; setmetatable(c, t1) | ||
376 | d = {} | ||
377 | t1.__eq = function () return true end | ||
378 | t1.__lt = function () return true end | ||
379 | setmetatable(d, t1) | ||
380 | assert(c == d and c < d and not(d <= c)) | ||
381 | t2 = {} | ||
382 | t2.__eq = t1.__eq | ||
383 | t2.__lt = t1.__lt | ||
384 | setmetatable(d, t2) | ||
385 | assert(c == d and c < d and not(d <= c)) | ||
386 | |||
387 | |||
388 | |||
389 | -- test for several levels of calls | ||
390 | local i | ||
391 | local tt = { | ||
392 | __call = function (t, ...) | ||
393 | i = i+1 | ||
394 | if t.f then return t.f(...) | ||
395 | else return {...} | ||
396 | end | ||
397 | end | ||
398 | } | ||
399 | |||
400 | local a = setmetatable({}, tt) | ||
401 | local b = setmetatable({f=a}, tt) | ||
402 | local c = setmetatable({f=b}, tt) | ||
403 | |||
404 | i = 0 | ||
405 | x = c(3,4,5) | ||
406 | assert(i == 3 and x[1] == 3 and x[3] == 5) | ||
407 | |||
408 | |||
409 | assert(_G.X == 20) | ||
410 | |||
411 | print'+' | ||
412 | |||
413 | local _g = _G | ||
414 | _ENV = setmetatable({}, {__index=function (_,k) return _g[k] end}) | ||
415 | |||
416 | |||
417 | a = {} | ||
418 | rawset(a, "x", 1, 2, 3) | ||
419 | assert(a.x == 1 and rawget(a, "x", 3) == 1) | ||
420 | |||
421 | print '+' | ||
422 | |||
423 | -- testing metatables for basic types | ||
424 | mt = {__index = function (a,b) return a+b end, | ||
425 | __len = function (x) return math.floor(x) end} | ||
426 | debug.setmetatable(10, mt) | ||
427 | assert(getmetatable(-2) == mt) | ||
428 | assert((10)[3] == 13) | ||
429 | assert((10)["3"] == 13) | ||
430 | assert(#3.45 == 3) | ||
431 | debug.setmetatable(23, nil) | ||
432 | assert(getmetatable(-2) == nil) | ||
433 | |||
434 | debug.setmetatable(true, mt) | ||
435 | assert(getmetatable(false) == mt) | ||
436 | mt.__index = function (a,b) return a or b end | ||
437 | assert((true)[false] == true) | ||
438 | assert((false)[false] == false) | ||
439 | debug.setmetatable(false, nil) | ||
440 | assert(getmetatable(true) == nil) | ||
441 | |||
442 | debug.setmetatable(nil, mt) | ||
443 | assert(getmetatable(nil) == mt) | ||
444 | mt.__add = function (a,b) return (a or 1) + (b or 2) end | ||
445 | assert(10 + nil == 12) | ||
446 | assert(nil + 23 == 24) | ||
447 | assert(nil + nil == 3) | ||
448 | debug.setmetatable(nil, nil) | ||
449 | assert(getmetatable(nil) == nil) | ||
450 | |||
451 | debug.setmetatable(nil, {}) | ||
452 | |||
453 | |||
454 | -- loops in delegation | ||
455 | a = {}; setmetatable(a, a); a.__index = a; a.__newindex = a | ||
456 | assert(not pcall(function (a,b) return a[b] end, a, 10)) | ||
457 | assert(not pcall(function (a,b,c) a[b] = c end, a, 10, true)) | ||
458 | |||
459 | -- bug in 5.1 | ||
460 | T, K, V = nil | ||
461 | grandparent = {} | ||
462 | grandparent.__newindex = function(t,k,v) T=t; K=k; V=v end | ||
463 | |||
464 | parent = {} | ||
465 | parent.__newindex = parent | ||
466 | setmetatable(parent, grandparent) | ||
467 | |||
468 | child = setmetatable({}, parent) | ||
469 | child.foo = 10 --> CRASH (on some machines) | ||
470 | assert(T == parent and K == "foo" and V == 10) | ||
471 | |||
472 | print 'OK' | ||
473 | |||
474 | return 12 | ||
475 | |||
476 | |||
diff --git a/testes/files.lua b/testes/files.lua new file mode 100644 index 00000000..b2c7c202 --- /dev/null +++ b/testes/files.lua | |||
@@ -0,0 +1,832 @@ | |||
1 | -- $Id: files.lua,v 1.101 2018/03/12 13:51:02 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | local debug = require "debug" | ||
5 | |||
6 | local maxint = math.maxinteger | ||
7 | |||
8 | assert(type(os.getenv"PATH") == "string") | ||
9 | |||
10 | assert(io.input(io.stdin) == io.stdin) | ||
11 | assert(not pcall(io.input, "non-existent-file")) | ||
12 | assert(io.output(io.stdout) == io.stdout) | ||
13 | |||
14 | |||
15 | local function testerr (msg, f, ...) | ||
16 | local stat, err = pcall(f, ...) | ||
17 | return (not stat and string.find(err, msg, 1, true)) | ||
18 | end | ||
19 | |||
20 | |||
21 | local function checkerr (msg, f, ...) | ||
22 | assert(testerr(msg, f, ...)) | ||
23 | end | ||
24 | |||
25 | |||
26 | -- cannot close standard files | ||
27 | assert(not io.close(io.stdin) and | ||
28 | not io.stdout:close() and | ||
29 | not io.stderr:close()) | ||
30 | |||
31 | -- cannot call close method without an argument (new in 5.3.5) | ||
32 | checkerr("got no value", io.stdin.close) | ||
33 | |||
34 | |||
35 | assert(type(io.input()) == "userdata" and io.type(io.output()) == "file") | ||
36 | assert(type(io.stdin) == "userdata" and io.type(io.stderr) == "file") | ||
37 | assert(not io.type(8)) | ||
38 | local a = {}; setmetatable(a, {}) | ||
39 | assert(not io.type(a)) | ||
40 | |||
41 | assert(getmetatable(io.input()).__name == "FILE*") | ||
42 | |||
43 | local a,b,c = io.open('xuxu_nao_existe') | ||
44 | assert(not a and type(b) == "string" and type(c) == "number") | ||
45 | |||
46 | a,b,c = io.open('/a/b/c/d', 'w') | ||
47 | assert(not a and type(b) == "string" and type(c) == "number") | ||
48 | |||
49 | local file = os.tmpname() | ||
50 | local f, msg = io.open(file, "w") | ||
51 | if not f then | ||
52 | (Message or print)("'os.tmpname' file cannot be open; skipping file tests") | ||
53 | |||
54 | else --{ most tests here need tmpname | ||
55 | f:close() | ||
56 | |||
57 | print('testing i/o') | ||
58 | |||
59 | local otherfile = os.tmpname() | ||
60 | |||
61 | checkerr("invalid mode", io.open, file, "rw") | ||
62 | checkerr("invalid mode", io.open, file, "rb+") | ||
63 | checkerr("invalid mode", io.open, file, "r+bk") | ||
64 | checkerr("invalid mode", io.open, file, "") | ||
65 | checkerr("invalid mode", io.open, file, "+") | ||
66 | checkerr("invalid mode", io.open, file, "b") | ||
67 | assert(io.open(file, "r+b")):close() | ||
68 | assert(io.open(file, "r+")):close() | ||
69 | assert(io.open(file, "rb")):close() | ||
70 | |||
71 | assert(os.setlocale('C', 'all')) | ||
72 | |||
73 | io.input(io.stdin); io.output(io.stdout); | ||
74 | |||
75 | os.remove(file) | ||
76 | assert(not loadfile(file)) | ||
77 | checkerr("", dofile, file) | ||
78 | assert(not io.open(file)) | ||
79 | io.output(file) | ||
80 | assert(io.output() ~= io.stdout) | ||
81 | |||
82 | if not _port then -- invalid seek | ||
83 | local status, msg, code = io.stdin:seek("set", 1000) | ||
84 | assert(not status and type(msg) == "string" and type(code) == "number") | ||
85 | end | ||
86 | |||
87 | assert(io.output():seek() == 0) | ||
88 | assert(io.write("alo alo"):seek() == string.len("alo alo")) | ||
89 | assert(io.output():seek("cur", -3) == string.len("alo alo")-3) | ||
90 | assert(io.write("joao")) | ||
91 | assert(io.output():seek("end") == string.len("alo joao")) | ||
92 | |||
93 | assert(io.output():seek("set") == 0) | ||
94 | |||
95 | assert(io.write('"álo"', "{a}\n", "second line\n", "third line \n")) | ||
96 | assert(io.write('çfourth_line')) | ||
97 | io.output(io.stdout) | ||
98 | collectgarbage() -- file should be closed by GC | ||
99 | assert(io.input() == io.stdin and rawequal(io.output(), io.stdout)) | ||
100 | print('+') | ||
101 | |||
102 | -- test GC for files | ||
103 | collectgarbage() | ||
104 | for i=1,120 do | ||
105 | for i=1,5 do | ||
106 | io.input(file) | ||
107 | assert(io.open(file, 'r')) | ||
108 | io.lines(file) | ||
109 | end | ||
110 | collectgarbage() | ||
111 | end | ||
112 | |||
113 | io.input():close() | ||
114 | io.close() | ||
115 | |||
116 | assert(os.rename(file, otherfile)) | ||
117 | assert(not os.rename(file, otherfile)) | ||
118 | |||
119 | io.output(io.open(otherfile, "ab")) | ||
120 | assert(io.write("\n\n\t\t ", 3450, "\n")); | ||
121 | io.close() | ||
122 | |||
123 | -- test writing/reading numbers | ||
124 | f = assert(io.open(file, "w")) | ||
125 | f:write(maxint, '\n') | ||
126 | f:write(string.format("0X%x\n", maxint)) | ||
127 | f:write("0xABCp-3", '\n') | ||
128 | f:write(0, '\n') | ||
129 | f:write(-maxint, '\n') | ||
130 | f:write(string.format("0x%X\n", -maxint)) | ||
131 | f:write("-0xABCp-3", '\n') | ||
132 | assert(f:close()) | ||
133 | f = assert(io.open(file, "r")) | ||
134 | assert(f:read("n") == maxint) | ||
135 | assert(f:read("n") == maxint) | ||
136 | assert(f:read("n") == 0xABCp-3) | ||
137 | assert(f:read("n") == 0) | ||
138 | assert(f:read("*n") == -maxint) -- test old format (with '*') | ||
139 | assert(f:read("n") == -maxint) | ||
140 | assert(f:read("*n") == -0xABCp-3) -- test old format (with '*') | ||
141 | assert(f:close()) | ||
142 | assert(os.remove(file)) | ||
143 | |||
144 | |||
145 | -- testing multiple arguments to io.read | ||
146 | do | ||
147 | local f = assert(io.open(file, "w")) | ||
148 | f:write[[ | ||
149 | a line | ||
150 | another line | ||
151 | 1234 | ||
152 | 3.45 | ||
153 | one | ||
154 | two | ||
155 | three | ||
156 | ]] | ||
157 | local l1, l2, l3, l4, n1, n2, c, dummy | ||
158 | assert(f:close()) | ||
159 | f = assert(io.open(file, "r")) | ||
160 | l1, l2, n1, n2, dummy = f:read("l", "L", "n", "n") | ||
161 | assert(l1 == "a line" and l2 == "another line\n" and | ||
162 | n1 == 1234 and n2 == 3.45 and dummy == nil) | ||
163 | assert(f:close()) | ||
164 | f = assert(io.open(file, "r")) | ||
165 | l1, l2, n1, n2, c, l3, l4, dummy = f:read(7, "l", "n", "n", 1, "l", "l") | ||
166 | assert(l1 == "a line\n" and l2 == "another line" and c == '\n' and | ||
167 | n1 == 1234 and n2 == 3.45 and l3 == "one" and l4 == "two" | ||
168 | and dummy == nil) | ||
169 | assert(f:close()) | ||
170 | f = assert(io.open(file, "r")) | ||
171 | -- second item failing | ||
172 | l1, n1, n2, dummy = f:read("l", "n", "n", "l") | ||
173 | assert(l1 == "a line" and n1 == nil) | ||
174 | assert(f:close()) | ||
175 | assert(os.remove(file)) | ||
176 | end | ||
177 | |||
178 | |||
179 | |||
180 | -- test yielding during 'dofile' | ||
181 | f = assert(io.open(file, "w")) | ||
182 | f:write[[ | ||
183 | local x, z = coroutine.yield(10) | ||
184 | local y = coroutine.yield(20) | ||
185 | return x + y * z | ||
186 | ]] | ||
187 | assert(f:close()) | ||
188 | f = coroutine.wrap(dofile) | ||
189 | assert(f(file) == 10) | ||
190 | print(f(100, 101) == 20) | ||
191 | assert(f(200) == 100 + 200 * 101) | ||
192 | assert(os.remove(file)) | ||
193 | |||
194 | |||
195 | f = assert(io.open(file, "w")) | ||
196 | -- test number termination | ||
197 | f:write[[ | ||
198 | -12.3- -0xffff+ .3|5.E-3X +234e+13E 0xDEADBEEFDEADBEEFx | ||
199 | 0x1.13Ap+3e | ||
200 | ]] | ||
201 | -- very long number | ||
202 | f:write("1234"); for i = 1, 1000 do f:write("0") end; f:write("\n") | ||
203 | -- invalid sequences (must read and discard valid prefixes) | ||
204 | f:write[[ | ||
205 | .e+ 0.e; --; 0xX; | ||
206 | ]] | ||
207 | assert(f:close()) | ||
208 | f = assert(io.open(file, "r")) | ||
209 | assert(f:read("n") == -12.3); assert(f:read(1) == "-") | ||
210 | assert(f:read("n") == -0xffff); assert(f:read(2) == "+ ") | ||
211 | assert(f:read("n") == 0.3); assert(f:read(1) == "|") | ||
212 | assert(f:read("n") == 5e-3); assert(f:read(1) == "X") | ||
213 | assert(f:read("n") == 234e13); assert(f:read(1) == "E") | ||
214 | assert(f:read("n") == 0Xdeadbeefdeadbeef); assert(f:read(2) == "x\n") | ||
215 | assert(f:read("n") == 0x1.13aP3); assert(f:read(1) == "e") | ||
216 | |||
217 | do -- attempt to read too long number | ||
218 | assert(f:read("n") == nil) -- fails | ||
219 | local s = f:read("L") -- read rest of line | ||
220 | assert(string.find(s, "^00*\n$")) -- lots of 0's left | ||
221 | end | ||
222 | |||
223 | assert(not f:read("n")); assert(f:read(2) == "e+") | ||
224 | assert(not f:read("n")); assert(f:read(1) == ";") | ||
225 | assert(not f:read("n")); assert(f:read(2) == "-;") | ||
226 | assert(not f:read("n")); assert(f:read(1) == "X") | ||
227 | assert(not f:read("n")); assert(f:read(1) == ";") | ||
228 | assert(not f:read("n")); assert(not f:read(0)) -- end of file | ||
229 | assert(f:close()) | ||
230 | assert(os.remove(file)) | ||
231 | |||
232 | |||
233 | -- test line generators | ||
234 | assert(not pcall(io.lines, "non-existent-file")) | ||
235 | assert(os.rename(otherfile, file)) | ||
236 | io.output(otherfile) | ||
237 | local n = 0 | ||
238 | local f = io.lines(file) | ||
239 | while f() do n = n + 1 end; | ||
240 | assert(n == 6) -- number of lines in the file | ||
241 | checkerr("file is already closed", f) | ||
242 | checkerr("file is already closed", f) | ||
243 | -- copy from file to otherfile | ||
244 | n = 0 | ||
245 | for l in io.lines(file) do io.write(l, "\n"); n = n + 1 end | ||
246 | io.close() | ||
247 | assert(n == 6) | ||
248 | -- copy from otherfile back to file | ||
249 | local f = assert(io.open(otherfile)) | ||
250 | assert(io.type(f) == "file") | ||
251 | io.output(file) | ||
252 | assert(not io.output():read()) | ||
253 | n = 0 | ||
254 | for l in f:lines() do io.write(l, "\n"); n = n + 1 end | ||
255 | assert(tostring(f):sub(1, 5) == "file ") | ||
256 | assert(f:close()); io.close() | ||
257 | assert(n == 6) | ||
258 | checkerr("closed file", io.close, f) | ||
259 | assert(tostring(f) == "file (closed)") | ||
260 | assert(io.type(f) == "closed file") | ||
261 | io.input(file) | ||
262 | f = io.open(otherfile):lines() | ||
263 | n = 0 | ||
264 | for l in io.lines() do assert(l == f()); n = n + 1 end | ||
265 | f = nil; collectgarbage() | ||
266 | assert(n == 6) | ||
267 | assert(os.remove(otherfile)) | ||
268 | |||
269 | do -- bug in 5.3.1 | ||
270 | io.output(otherfile) | ||
271 | io.write(string.rep("a", 300), "\n") | ||
272 | io.close() | ||
273 | local t ={}; for i = 1, 250 do t[i] = 1 end | ||
274 | t = {io.lines(otherfile, table.unpack(t))()} | ||
275 | -- everything ok here | ||
276 | assert(#t == 250 and t[1] == 'a' and t[#t] == 'a') | ||
277 | t[#t + 1] = 1 -- one too many | ||
278 | checkerr("too many arguments", io.lines, otherfile, table.unpack(t)) | ||
279 | collectgarbage() -- ensure 'otherfile' is closed | ||
280 | assert(os.remove(otherfile)) | ||
281 | end | ||
282 | |||
283 | io.input(file) | ||
284 | do -- test error returns | ||
285 | local a,b,c = io.input():write("xuxu") | ||
286 | assert(not a and type(b) == "string" and type(c) == "number") | ||
287 | end | ||
288 | checkerr("invalid format", io.read, "x") | ||
289 | assert(io.read(0) == "") -- not eof | ||
290 | assert(io.read(5, 'l') == '"álo"') | ||
291 | assert(io.read(0) == "") | ||
292 | assert(io.read() == "second line") | ||
293 | local x = io.input():seek() | ||
294 | assert(io.read() == "third line ") | ||
295 | assert(io.input():seek("set", x)) | ||
296 | assert(io.read('L') == "third line \n") | ||
297 | assert(io.read(1) == "ç") | ||
298 | assert(io.read(string.len"fourth_line") == "fourth_line") | ||
299 | assert(io.input():seek("cur", -string.len"fourth_line")) | ||
300 | assert(io.read() == "fourth_line") | ||
301 | assert(io.read() == "") -- empty line | ||
302 | assert(io.read('n') == 3450) | ||
303 | assert(io.read(1) == '\n') | ||
304 | assert(io.read(0) == nil) -- end of file | ||
305 | assert(io.read(1) == nil) -- end of file | ||
306 | assert(io.read(30000) == nil) -- end of file | ||
307 | assert(({io.read(1)})[2] == undef) | ||
308 | assert(io.read() == nil) -- end of file | ||
309 | assert(({io.read()})[2] == undef) | ||
310 | assert(io.read('n') == nil) -- end of file | ||
311 | assert(({io.read('n')})[2] == undef) | ||
312 | assert(io.read('a') == '') -- end of file (OK for 'a') | ||
313 | assert(io.read('a') == '') -- end of file (OK for 'a') | ||
314 | collectgarbage() | ||
315 | print('+') | ||
316 | io.close(io.input()) | ||
317 | checkerr(" input file is closed", io.read) | ||
318 | |||
319 | assert(os.remove(file)) | ||
320 | |||
321 | local t = '0123456789' | ||
322 | for i=1,10 do t = t..t; end | ||
323 | assert(string.len(t) == 10*2^10) | ||
324 | |||
325 | io.output(file) | ||
326 | io.write("alo"):write("\n") | ||
327 | io.close() | ||
328 | checkerr(" output file is closed", io.write) | ||
329 | local f = io.open(file, "a+b") | ||
330 | io.output(f) | ||
331 | collectgarbage() | ||
332 | |||
333 | assert(io.write(' ' .. t .. ' ')) | ||
334 | assert(io.write(';', 'end of file\n')) | ||
335 | f:flush(); io.flush() | ||
336 | f:close() | ||
337 | print('+') | ||
338 | |||
339 | io.input(file) | ||
340 | assert(io.read() == "alo") | ||
341 | assert(io.read(1) == ' ') | ||
342 | assert(io.read(string.len(t)) == t) | ||
343 | assert(io.read(1) == ' ') | ||
344 | assert(io.read(0)) | ||
345 | assert(io.read('a') == ';end of file\n') | ||
346 | assert(io.read(0) == nil) | ||
347 | assert(io.close(io.input())) | ||
348 | |||
349 | |||
350 | -- test errors in read/write | ||
351 | do | ||
352 | local function ismsg (m) | ||
353 | -- error message is not a code number | ||
354 | return (type(m) == "string" and tonumber(m) == nil) | ||
355 | end | ||
356 | |||
357 | -- read | ||
358 | local f = io.open(file, "w") | ||
359 | local r, m, c = f:read() | ||
360 | assert(not r and ismsg(m) and type(c) == "number") | ||
361 | assert(f:close()) | ||
362 | -- write | ||
363 | f = io.open(file, "r") | ||
364 | r, m, c = f:write("whatever") | ||
365 | assert(not r and ismsg(m) and type(c) == "number") | ||
366 | assert(f:close()) | ||
367 | -- lines | ||
368 | f = io.open(file, "w") | ||
369 | r, m = pcall(f:lines()) | ||
370 | assert(r == false and ismsg(m)) | ||
371 | assert(f:close()) | ||
372 | end | ||
373 | |||
374 | assert(os.remove(file)) | ||
375 | |||
376 | -- test for L format | ||
377 | io.output(file); io.write"\n\nline\nother":close() | ||
378 | io.input(file) | ||
379 | assert(io.read"L" == "\n") | ||
380 | assert(io.read"L" == "\n") | ||
381 | assert(io.read"L" == "line\n") | ||
382 | assert(io.read"L" == "other") | ||
383 | assert(io.read"L" == nil) | ||
384 | io.input():close() | ||
385 | |||
386 | local f = assert(io.open(file)) | ||
387 | local s = "" | ||
388 | for l in f:lines("L") do s = s .. l end | ||
389 | assert(s == "\n\nline\nother") | ||
390 | f:close() | ||
391 | |||
392 | io.input(file) | ||
393 | s = "" | ||
394 | for l in io.lines(nil, "L") do s = s .. l end | ||
395 | assert(s == "\n\nline\nother") | ||
396 | io.input():close() | ||
397 | |||
398 | s = "" | ||
399 | for l in io.lines(file, "L") do s = s .. l end | ||
400 | assert(s == "\n\nline\nother") | ||
401 | |||
402 | s = "" | ||
403 | for l in io.lines(file, "l") do s = s .. l end | ||
404 | assert(s == "lineother") | ||
405 | |||
406 | io.output(file); io.write"a = 10 + 34\na = 2*a\na = -a\n":close() | ||
407 | local t = {} | ||
408 | assert(load(io.lines(file, "L"), nil, nil, t))() | ||
409 | assert(t.a == -((10 + 34) * 2)) | ||
410 | |||
411 | |||
412 | -- test for multipe arguments in 'lines' | ||
413 | io.output(file); io.write"0123456789\n":close() | ||
414 | for a,b in io.lines(file, 1, 1) do | ||
415 | if a == "\n" then assert(b == nil) | ||
416 | else assert(tonumber(a) == tonumber(b) - 1) | ||
417 | end | ||
418 | end | ||
419 | |||
420 | for a,b,c in io.lines(file, 1, 2, "a") do | ||
421 | assert(a == "0" and b == "12" and c == "3456789\n") | ||
422 | end | ||
423 | |||
424 | for a,b,c in io.lines(file, "a", 0, 1) do | ||
425 | if a == "" then break end | ||
426 | assert(a == "0123456789\n" and b == nil and c == nil) | ||
427 | end | ||
428 | collectgarbage() -- to close file in previous iteration | ||
429 | |||
430 | io.output(file); io.write"00\n10\n20\n30\n40\n":close() | ||
431 | for a, b in io.lines(file, "n", "n") do | ||
432 | if a == 40 then assert(b == nil) | ||
433 | else assert(a == b - 10) | ||
434 | end | ||
435 | end | ||
436 | |||
437 | |||
438 | -- test load x lines | ||
439 | io.output(file); | ||
440 | io.write[[ | ||
441 | local y | ||
442 | = X | ||
443 | X = | ||
444 | X * | ||
445 | 2 + | ||
446 | X; | ||
447 | X = | ||
448 | X | ||
449 | - y; | ||
450 | ]]:close() | ||
451 | _G.X = 1 | ||
452 | assert(not load(io.lines(file))) | ||
453 | collectgarbage() -- to close file in previous iteration | ||
454 | load(io.lines(file, "L"))() | ||
455 | assert(_G.X == 2) | ||
456 | load(io.lines(file, 1))() | ||
457 | assert(_G.X == 4) | ||
458 | load(io.lines(file, 3))() | ||
459 | assert(_G.X == 8) | ||
460 | |||
461 | print('+') | ||
462 | |||
463 | local x1 = "string\n\n\\com \"\"''coisas [[estranhas]] ]]'" | ||
464 | io.output(file) | ||
465 | assert(io.write(string.format("x2 = %q\n-- comment without ending EOS", x1))) | ||
466 | io.close() | ||
467 | assert(loadfile(file))() | ||
468 | assert(x1 == x2) | ||
469 | print('+') | ||
470 | assert(os.remove(file)) | ||
471 | assert(not os.remove(file)) | ||
472 | assert(not os.remove(otherfile)) | ||
473 | |||
474 | -- testing loadfile | ||
475 | local function testloadfile (s, expres) | ||
476 | io.output(file) | ||
477 | if s then io.write(s) end | ||
478 | io.close() | ||
479 | local res = assert(loadfile(file))() | ||
480 | assert(os.remove(file)) | ||
481 | assert(res == expres) | ||
482 | end | ||
483 | |||
484 | -- loading empty file | ||
485 | testloadfile(nil, nil) | ||
486 | |||
487 | -- loading file with initial comment without end of line | ||
488 | testloadfile("# a non-ending comment", nil) | ||
489 | |||
490 | |||
491 | -- checking Unicode BOM in files | ||
492 | testloadfile("\xEF\xBB\xBF# some comment\nreturn 234", 234) | ||
493 | testloadfile("\xEF\xBB\xBFreturn 239", 239) | ||
494 | testloadfile("\xEF\xBB\xBF", nil) -- empty file with a BOM | ||
495 | |||
496 | |||
497 | -- checking line numbers in files with initial comments | ||
498 | testloadfile("# a comment\nreturn require'debug'.getinfo(1).currentline", 2) | ||
499 | |||
500 | |||
501 | -- loading binary file | ||
502 | io.output(io.open(file, "wb")) | ||
503 | assert(io.write(string.dump(function () return 10, '\0alo\255', 'hi' end))) | ||
504 | io.close() | ||
505 | a, b, c = assert(loadfile(file))() | ||
506 | assert(a == 10 and b == "\0alo\255" and c == "hi") | ||
507 | assert(os.remove(file)) | ||
508 | |||
509 | -- bug in 5.2.1 | ||
510 | do | ||
511 | io.output(io.open(file, "wb")) | ||
512 | -- save function with no upvalues | ||
513 | assert(io.write(string.dump(function () return 1 end))) | ||
514 | io.close() | ||
515 | f = assert(loadfile(file, "b", {})) | ||
516 | assert(type(f) == "function" and f() == 1) | ||
517 | assert(os.remove(file)) | ||
518 | end | ||
519 | |||
520 | -- loading binary file with initial comment | ||
521 | io.output(io.open(file, "wb")) | ||
522 | assert(io.write("#this is a comment for a binary file\0\n", | ||
523 | string.dump(function () return 20, '\0\0\0' end))) | ||
524 | io.close() | ||
525 | a, b, c = assert(loadfile(file))() | ||
526 | assert(a == 20 and b == "\0\0\0" and c == nil) | ||
527 | assert(os.remove(file)) | ||
528 | |||
529 | |||
530 | -- 'loadfile' with 'env' | ||
531 | do | ||
532 | local f = io.open(file, 'w') | ||
533 | f:write[[ | ||
534 | if (...) then a = 15; return b, c, d | ||
535 | else return _ENV | ||
536 | end | ||
537 | ]] | ||
538 | f:close() | ||
539 | local t = {b = 12, c = "xuxu", d = print} | ||
540 | local f = assert(loadfile(file, 't', t)) | ||
541 | local b, c, d = f(1) | ||
542 | assert(t.a == 15 and b == 12 and c == t.c and d == print) | ||
543 | assert(f() == t) | ||
544 | f = assert(loadfile(file, 't', nil)) | ||
545 | assert(f() == nil) | ||
546 | f = assert(loadfile(file)) | ||
547 | assert(f() == _G) | ||
548 | assert(os.remove(file)) | ||
549 | end | ||
550 | |||
551 | |||
552 | -- 'loadfile' x modes | ||
553 | do | ||
554 | io.open(file, 'w'):write("return 10"):close() | ||
555 | local s, m = loadfile(file, 'b') | ||
556 | assert(not s and string.find(m, "a text chunk")) | ||
557 | io.open(file, 'w'):write("\27 return 10"):close() | ||
558 | local s, m = loadfile(file, 't') | ||
559 | assert(not s and string.find(m, "a binary chunk")) | ||
560 | assert(os.remove(file)) | ||
561 | end | ||
562 | |||
563 | |||
564 | io.output(file) | ||
565 | assert(io.write("qualquer coisa\n")) | ||
566 | assert(io.write("mais qualquer coisa")) | ||
567 | io.close() | ||
568 | assert(io.output(assert(io.open(otherfile, 'wb'))) | ||
569 | :write("outra coisa\0\1\3\0\0\0\0\255\0") | ||
570 | :close()) | ||
571 | |||
572 | local filehandle = assert(io.open(file, 'r+')) | ||
573 | local otherfilehandle = assert(io.open(otherfile, 'rb')) | ||
574 | assert(filehandle ~= otherfilehandle) | ||
575 | assert(type(filehandle) == "userdata") | ||
576 | assert(filehandle:read('l') == "qualquer coisa") | ||
577 | io.input(otherfilehandle) | ||
578 | assert(io.read(string.len"outra coisa") == "outra coisa") | ||
579 | assert(filehandle:read('l') == "mais qualquer coisa") | ||
580 | filehandle:close(); | ||
581 | assert(type(filehandle) == "userdata") | ||
582 | io.input(otherfilehandle) | ||
583 | assert(io.read(4) == "\0\1\3\0") | ||
584 | assert(io.read(3) == "\0\0\0") | ||
585 | assert(io.read(0) == "") -- 255 is not eof | ||
586 | assert(io.read(1) == "\255") | ||
587 | assert(io.read('a') == "\0") | ||
588 | assert(not io.read(0)) | ||
589 | assert(otherfilehandle == io.input()) | ||
590 | otherfilehandle:close() | ||
591 | assert(os.remove(file)) | ||
592 | assert(os.remove(otherfile)) | ||
593 | collectgarbage() | ||
594 | |||
595 | io.output(file) | ||
596 | :write[[ | ||
597 | 123.4 -56e-2 not a number | ||
598 | second line | ||
599 | third line | ||
600 | |||
601 | and the rest of the file | ||
602 | ]] | ||
603 | :close() | ||
604 | io.input(file) | ||
605 | local _,a,b,c,d,e,h,__ = io.read(1, 'n', 'n', 'l', 'l', 'l', 'a', 10) | ||
606 | assert(io.close(io.input())) | ||
607 | assert(_ == ' ' and __ == nil) | ||
608 | assert(type(a) == 'number' and a==123.4 and b==-56e-2) | ||
609 | assert(d=='second line' and e=='third line') | ||
610 | assert(h==[[ | ||
611 | |||
612 | and the rest of the file | ||
613 | ]]) | ||
614 | assert(os.remove(file)) | ||
615 | collectgarbage() | ||
616 | |||
617 | -- testing buffers | ||
618 | do | ||
619 | local f = assert(io.open(file, "w")) | ||
620 | local fr = assert(io.open(file, "r")) | ||
621 | assert(f:setvbuf("full", 2000)) | ||
622 | f:write("x") | ||
623 | assert(fr:read("all") == "") -- full buffer; output not written yet | ||
624 | f:close() | ||
625 | fr:seek("set") | ||
626 | assert(fr:read("all") == "x") -- `close' flushes it | ||
627 | f = assert(io.open(file), "w") | ||
628 | assert(f:setvbuf("no")) | ||
629 | f:write("x") | ||
630 | fr:seek("set") | ||
631 | assert(fr:read("all") == "x") -- no buffer; output is ready | ||
632 | f:close() | ||
633 | f = assert(io.open(file, "a")) | ||
634 | assert(f:setvbuf("line")) | ||
635 | f:write("x") | ||
636 | fr:seek("set", 1) | ||
637 | assert(fr:read("all") == "") -- line buffer; no output without `\n' | ||
638 | f:write("a\n"):seek("set", 1) | ||
639 | assert(fr:read("all") == "xa\n") -- now we have a whole line | ||
640 | f:close(); fr:close() | ||
641 | assert(os.remove(file)) | ||
642 | end | ||
643 | |||
644 | |||
645 | if not _soft then | ||
646 | print("testing large files (> BUFSIZ)") | ||
647 | io.output(file) | ||
648 | for i=1,5001 do io.write('0123456789123') end | ||
649 | io.write('\n12346'):close() | ||
650 | io.input(file) | ||
651 | local x = io.read('a') | ||
652 | io.input():seek('set', 0) | ||
653 | local y = io.read(30001)..io.read(1005)..io.read(0).. | ||
654 | io.read(1)..io.read(100003) | ||
655 | assert(x == y and string.len(x) == 5001*13 + 6) | ||
656 | io.input():seek('set', 0) | ||
657 | y = io.read() -- huge line | ||
658 | assert(x == y..'\n'..io.read()) | ||
659 | assert(io.read() == nil) | ||
660 | io.close(io.input()) | ||
661 | assert(os.remove(file)) | ||
662 | x = nil; y = nil | ||
663 | end | ||
664 | |||
665 | if not _port then | ||
666 | local progname | ||
667 | do -- get name of running executable | ||
668 | local arg = arg or ARG | ||
669 | local i = 0 | ||
670 | while arg[i] do i = i - 1 end | ||
671 | progname = '"' .. arg[i + 1] .. '"' | ||
672 | end | ||
673 | print("testing popen/pclose and execute") | ||
674 | local tests = { | ||
675 | -- command, what, code | ||
676 | {"ls > /dev/null", "ok"}, | ||
677 | {"not-to-be-found-command", "exit"}, | ||
678 | {"exit 3", "exit", 3}, | ||
679 | {"exit 129", "exit", 129}, | ||
680 | {"kill -s HUP $$", "signal", 1}, | ||
681 | {"kill -s KILL $$", "signal", 9}, | ||
682 | {"sh -c 'kill -s HUP $$'", "exit"}, | ||
683 | {progname .. ' -e " "', "ok"}, | ||
684 | {progname .. ' -e "os.exit(0, true)"', "ok"}, | ||
685 | {progname .. ' -e "os.exit(20, true)"', "exit", 20}, | ||
686 | } | ||
687 | print("\n(some error messages are expected now)") | ||
688 | for _, v in ipairs(tests) do | ||
689 | local x, y, z = io.popen(v[1]):close() | ||
690 | local x1, y1, z1 = os.execute(v[1]) | ||
691 | assert(x == x1 and y == y1 and z == z1) | ||
692 | if v[2] == "ok" then | ||
693 | assert(x and y == 'exit' and z == 0) | ||
694 | else | ||
695 | assert(not x and y == v[2]) -- correct status and 'what' | ||
696 | -- correct code if known (but always different from 0) | ||
697 | assert((v[3] == nil and z > 0) or v[3] == z) | ||
698 | end | ||
699 | end | ||
700 | end | ||
701 | |||
702 | |||
703 | -- testing tmpfile | ||
704 | f = io.tmpfile() | ||
705 | assert(io.type(f) == "file") | ||
706 | f:write("alo") | ||
707 | f:seek("set") | ||
708 | assert(f:read"a" == "alo") | ||
709 | |||
710 | end --} | ||
711 | |||
712 | print'+' | ||
713 | |||
714 | print("testing date/time") | ||
715 | |||
716 | assert(os.date("") == "") | ||
717 | assert(os.date("!") == "") | ||
718 | assert(os.date("\0\0") == "\0\0") | ||
719 | assert(os.date("!\0\0") == "\0\0") | ||
720 | local x = string.rep("a", 10000) | ||
721 | assert(os.date(x) == x) | ||
722 | local t = os.time() | ||
723 | D = os.date("*t", t) | ||
724 | assert(os.date(string.rep("%d", 1000), t) == | ||
725 | string.rep(os.date("%d", t), 1000)) | ||
726 | assert(os.date(string.rep("%", 200)) == string.rep("%", 100)) | ||
727 | |||
728 | local t = os.time() | ||
729 | D = os.date("*t", t) | ||
730 | load(os.date([[assert(D.year==%Y and D.month==%m and D.day==%d and | ||
731 | D.hour==%H and D.min==%M and D.sec==%S and | ||
732 | D.wday==%w+1 and D.yday==%j and type(D.isdst) == 'boolean')]], t))() | ||
733 | |||
734 | checkerr("invalid conversion specifier", os.date, "%") | ||
735 | checkerr("invalid conversion specifier", os.date, "%9") | ||
736 | checkerr("invalid conversion specifier", os.date, "%") | ||
737 | checkerr("invalid conversion specifier", os.date, "%O") | ||
738 | checkerr("invalid conversion specifier", os.date, "%E") | ||
739 | checkerr("invalid conversion specifier", os.date, "%Ea") | ||
740 | |||
741 | checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour='x'}) | ||
742 | checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour=1.5}) | ||
743 | |||
744 | checkerr("missing", os.time, {hour = 12}) -- missing date | ||
745 | |||
746 | if not _port then | ||
747 | -- test Posix-specific modifiers | ||
748 | assert(type(os.date("%Ex")) == 'string') | ||
749 | assert(type(os.date("%Oy")) == 'string') | ||
750 | |||
751 | |||
752 | -- test out-of-range dates (at least for Unix) | ||
753 | if maxint >= 2^62 then -- cannot do these tests in Small Lua | ||
754 | -- no arith overflows | ||
755 | checkerr("out-of-bound", os.time, {year = -maxint, month = 1, day = 1}) | ||
756 | if string.packsize("i") == 4 then -- 4-byte ints | ||
757 | if testerr("out-of-bound", os.date, "%Y", 2^40) then | ||
758 | -- time_t has 4 bytes and therefore cannot represent year 4000 | ||
759 | print(" 4-byte time_t") | ||
760 | checkerr("cannot be represented", os.time, {year=4000, month=1, day=1}) | ||
761 | else | ||
762 | -- time_t has 8 bytes; an int year cannot represent a huge time | ||
763 | print(" 8-byte time_t") | ||
764 | checkerr("cannot be represented", os.date, "%Y", 2^60) | ||
765 | -- it should have no problems with year 4000 | ||
766 | assert(tonumber(os.time{year=4000, month=1, day=1})) | ||
767 | end | ||
768 | else -- 8-byte ints | ||
769 | -- assume time_t has 8 bytes too | ||
770 | print(" 8-byte time_t") | ||
771 | assert(tonumber(os.date("%Y", 2^60))) | ||
772 | -- but still cannot represent a huge year | ||
773 | checkerr("cannot be represented", os.time, {year=2^60, month=1, day=1}) | ||
774 | end | ||
775 | end | ||
776 | end | ||
777 | |||
778 | |||
779 | D = os.date("!*t", t) | ||
780 | load(os.date([[!assert(D.year==%Y and D.month==%m and D.day==%d and | ||
781 | D.hour==%H and D.min==%M and D.sec==%S and | ||
782 | D.wday==%w+1 and D.yday==%j and type(D.isdst) == 'boolean')]], t))() | ||
783 | |||
784 | do | ||
785 | local D = os.date("*t") | ||
786 | local t = os.time(D) | ||
787 | assert(type(D.isdst) == 'boolean') | ||
788 | D.isdst = nil | ||
789 | local t1 = os.time(D) | ||
790 | assert(t == t1) -- if isdst is absent uses correct default | ||
791 | end | ||
792 | |||
793 | t = os.time(D) | ||
794 | D.year = D.year-1; | ||
795 | local t1 = os.time(D) | ||
796 | -- allow for leap years | ||
797 | assert(math.abs(os.difftime(t,t1)/(24*3600) - 365) < 2) | ||
798 | |||
799 | -- should not take more than 1 second to execute these two lines | ||
800 | t = os.time() | ||
801 | t1 = os.time(os.date("*t")) | ||
802 | local diff = os.difftime(t1,t) | ||
803 | assert(0 <= diff and diff <= 1) | ||
804 | diff = os.difftime(t,t1) | ||
805 | assert(-1 <= diff and diff <= 0) | ||
806 | |||
807 | local t1 = os.time{year=2000, month=10, day=1, hour=23, min=12} | ||
808 | local t2 = os.time{year=2000, month=10, day=1, hour=23, min=10, sec=19} | ||
809 | assert(os.difftime(t1,t2) == 60*2-19) | ||
810 | |||
811 | -- since 5.3.3, 'os.time' normalizes table fields | ||
812 | t1 = {year = 2005, month = 1, day = 1, hour = 1, min = 0, sec = -3602} | ||
813 | os.time(t1) | ||
814 | assert(t1.day == 31 and t1.month == 12 and t1.year == 2004 and | ||
815 | t1.hour == 23 and t1.min == 59 and t1.sec == 58 and | ||
816 | t1.yday == 366) | ||
817 | |||
818 | io.output(io.stdout) | ||
819 | local t = os.date('%d %m %Y %H %M %S') | ||
820 | local d, m, a, h, min, s = string.match(t, | ||
821 | "(%d+) (%d+) (%d+) (%d+) (%d+) (%d+)") | ||
822 | d = tonumber(d) | ||
823 | m = tonumber(m) | ||
824 | a = tonumber(a) | ||
825 | h = tonumber(h) | ||
826 | min = tonumber(min) | ||
827 | s = tonumber(s) | ||
828 | io.write(string.format('test done on %2.2d/%2.2d/%d', d, m, a)) | ||
829 | io.write(string.format(', at %2.2d:%2.2d:%2.2d\n', h, min, s)) | ||
830 | io.write(string.format('%s\n', _VERSION)) | ||
831 | |||
832 | |||
diff --git a/testes/gc.lua b/testes/gc.lua new file mode 100644 index 00000000..9647cd54 --- /dev/null +++ b/testes/gc.lua | |||
@@ -0,0 +1,661 @@ | |||
1 | -- $Id: gc.lua,v 1.82 2018/03/12 14:19:36 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing garbage collection') | ||
5 | |||
6 | local debug = require"debug" | ||
7 | |||
8 | assert(collectgarbage("isrunning")) | ||
9 | |||
10 | collectgarbage() | ||
11 | |||
12 | local oldmode = collectgarbage("incremental") | ||
13 | |||
14 | |||
15 | local function gcinfo () | ||
16 | return collectgarbage"count" * 1024 | ||
17 | end | ||
18 | |||
19 | |||
20 | -- test weird parameters to 'collectgarbage' | ||
21 | do | ||
22 | -- save original parameters | ||
23 | local a = collectgarbage("setpause", 200) | ||
24 | local b = collectgarbage("setstepmul", 200) | ||
25 | local t = {0, 2, 10, 90, 500, 5000, 30000, 0x7ffffffe} | ||
26 | for i = 1, #t do | ||
27 | local p = t[i] | ||
28 | for j = 1, #t do | ||
29 | local m = t[j] | ||
30 | collectgarbage("setpause", p) | ||
31 | collectgarbage("setstepmul", m) | ||
32 | collectgarbage("step", 0) | ||
33 | collectgarbage("step", 10000) | ||
34 | end | ||
35 | end | ||
36 | -- restore original parameters | ||
37 | collectgarbage("setpause", a) | ||
38 | collectgarbage("setstepmul", b) | ||
39 | collectgarbage() | ||
40 | end | ||
41 | |||
42 | |||
43 | _G["while"] = 234 | ||
44 | |||
45 | |||
46 | -- | ||
47 | -- tests for GC activation when creating different kinds of objects | ||
48 | -- | ||
49 | local function GC1 () | ||
50 | local u | ||
51 | local b -- (above 'u' it in the stack) | ||
52 | local finish = false | ||
53 | u = setmetatable({}, {__gc = function () finish = true end}) | ||
54 | b = {34} | ||
55 | repeat u = {} until finish | ||
56 | assert(b[1] == 34) -- 'u' was collected, but 'b' was not | ||
57 | |||
58 | finish = false; local i = 1 | ||
59 | u = setmetatable({}, {__gc = function () finish = true end}) | ||
60 | repeat i = i + 1; u = tostring(i) .. tostring(i) until finish | ||
61 | assert(b[1] == 34) -- 'u' was collected, but 'b' was not | ||
62 | |||
63 | finish = false | ||
64 | u = setmetatable({}, {__gc = function () finish = true end}) | ||
65 | repeat local i; u = function () return i end until finish | ||
66 | assert(b[1] == 34) -- 'u' was collected, but 'b' was not | ||
67 | end | ||
68 | |||
69 | local function GC2 () | ||
70 | local u | ||
71 | local finish = false | ||
72 | u = {setmetatable({}, {__gc = function () finish = true end})} | ||
73 | local b = {34} | ||
74 | repeat u = {{}} until finish | ||
75 | assert(b[1] == 34) -- 'u' was collected, but 'b' was not | ||
76 | |||
77 | finish = false; local i = 1 | ||
78 | u = {setmetatable({}, {__gc = function () finish = true end})} | ||
79 | repeat i = i + 1; u = {tostring(i) .. tostring(i)} until finish | ||
80 | assert(b[1] == 34) -- 'u' was collected, but 'b' was not | ||
81 | |||
82 | finish = false | ||
83 | u = {setmetatable({}, {__gc = function () finish = true end})} | ||
84 | repeat local i; u = {function () return i end} until finish | ||
85 | assert(b[1] == 34) -- 'u' was collected, but 'b' was not | ||
86 | end | ||
87 | |||
88 | local function GC() GC1(); GC2() end | ||
89 | |||
90 | |||
91 | do | ||
92 | print("creating many objects") | ||
93 | |||
94 | local contCreate = 0 | ||
95 | |||
96 | local limit = 5000 | ||
97 | |||
98 | while contCreate <= limit do | ||
99 | local a = {}; a = nil | ||
100 | contCreate = contCreate+1 | ||
101 | end | ||
102 | |||
103 | local a = "a" | ||
104 | |||
105 | contCreate = 0 | ||
106 | while contCreate <= limit do | ||
107 | a = contCreate .. "b"; | ||
108 | a = string.gsub(a, '(%d%d*)', string.upper) | ||
109 | a = "a" | ||
110 | contCreate = contCreate+1 | ||
111 | end | ||
112 | |||
113 | |||
114 | contCreate = 0 | ||
115 | |||
116 | a = {} | ||
117 | |||
118 | function a:test () | ||
119 | while contCreate <= limit do | ||
120 | load(string.format("function temp(a) return 'a%d' end", contCreate), "")() | ||
121 | assert(temp() == string.format('a%d', contCreate)) | ||
122 | contCreate = contCreate+1 | ||
123 | end | ||
124 | end | ||
125 | |||
126 | a:test() | ||
127 | |||
128 | end | ||
129 | |||
130 | |||
131 | -- collection of functions without locals, globals, etc. | ||
132 | do local f = function () end end | ||
133 | |||
134 | |||
135 | print("functions with errors") | ||
136 | prog = [[ | ||
137 | do | ||
138 | a = 10; | ||
139 | function foo(x,y) | ||
140 | a = sin(a+0.456-0.23e-12); | ||
141 | return function (z) return sin(%x+z) end | ||
142 | end | ||
143 | local x = function (w) a=a+w; end | ||
144 | end | ||
145 | ]] | ||
146 | do | ||
147 | local step = 1 | ||
148 | if _soft then step = 13 end | ||
149 | for i=1, string.len(prog), step do | ||
150 | for j=i, string.len(prog), step do | ||
151 | pcall(load(string.sub(prog, i, j), "")) | ||
152 | end | ||
153 | end | ||
154 | end | ||
155 | |||
156 | foo = nil | ||
157 | print('long strings') | ||
158 | x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789" | ||
159 | assert(string.len(x)==80) | ||
160 | s = '' | ||
161 | n = 0 | ||
162 | k = math.min(300, (math.maxinteger // 80) // 2) | ||
163 | while n < k do s = s..x; n=n+1; j=tostring(n) end | ||
164 | assert(string.len(s) == k*80) | ||
165 | s = string.sub(s, 1, 10000) | ||
166 | s, i = string.gsub(s, '(%d%d%d%d)', '') | ||
167 | assert(i==10000 // 4) | ||
168 | s = nil | ||
169 | x = nil | ||
170 | |||
171 | assert(_G["while"] == 234) | ||
172 | |||
173 | |||
174 | -- | ||
175 | -- test the "size" of basic GC steps (whatever they mean...) | ||
176 | -- | ||
177 | do | ||
178 | print("steps") | ||
179 | |||
180 | print("steps (2)") | ||
181 | |||
182 | local function dosteps (siz) | ||
183 | collectgarbage() | ||
184 | local a = {} | ||
185 | for i=1,100 do a[i] = {{}}; local b = {} end | ||
186 | local x = gcinfo() | ||
187 | local i = 0 | ||
188 | repeat -- do steps until it completes a collection cycle | ||
189 | i = i+1 | ||
190 | until collectgarbage("step", siz) | ||
191 | assert(gcinfo() < x) | ||
192 | return i -- number of steps | ||
193 | end | ||
194 | |||
195 | collectgarbage"stop" | ||
196 | |||
197 | if not _port then | ||
198 | assert(dosteps(10) < dosteps(2)) | ||
199 | end | ||
200 | |||
201 | -- collector should do a full collection with so many steps | ||
202 | assert(dosteps(20000) == 1) | ||
203 | assert(collectgarbage("step", 20000) == true) | ||
204 | assert(collectgarbage("step", 20000) == true) | ||
205 | |||
206 | assert(not collectgarbage("isrunning")) | ||
207 | collectgarbage"restart" | ||
208 | assert(collectgarbage("isrunning")) | ||
209 | |||
210 | end | ||
211 | |||
212 | |||
213 | if not _port then | ||
214 | -- test the pace of the collector | ||
215 | collectgarbage(); collectgarbage() | ||
216 | local x = gcinfo() | ||
217 | collectgarbage"stop" | ||
218 | repeat | ||
219 | local a = {} | ||
220 | until gcinfo() > 3 * x | ||
221 | collectgarbage"restart" | ||
222 | assert(collectgarbage("isrunning")) | ||
223 | repeat | ||
224 | local a = {} | ||
225 | until gcinfo() <= x * 2 | ||
226 | end | ||
227 | |||
228 | |||
229 | print("clearing tables") | ||
230 | lim = 15 | ||
231 | a = {} | ||
232 | -- fill a with `collectable' indices | ||
233 | for i=1,lim do a[{}] = i end | ||
234 | b = {} | ||
235 | for k,v in pairs(a) do b[k]=v end | ||
236 | -- remove all indices and collect them | ||
237 | for n in pairs(b) do | ||
238 | a[n] = undef | ||
239 | assert(type(n) == 'table' and next(n) == nil) | ||
240 | collectgarbage() | ||
241 | end | ||
242 | b = nil | ||
243 | collectgarbage() | ||
244 | for n in pairs(a) do error'cannot be here' end | ||
245 | for i=1,lim do a[i] = i end | ||
246 | for i=1,lim do assert(a[i] == i) end | ||
247 | |||
248 | |||
249 | print('weak tables') | ||
250 | a = {}; setmetatable(a, {__mode = 'k'}); | ||
251 | -- fill a with some `collectable' indices | ||
252 | for i=1,lim do a[{}] = i end | ||
253 | -- and some non-collectable ones | ||
254 | for i=1,lim do a[i] = i end | ||
255 | for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end | ||
256 | collectgarbage() | ||
257 | local i = 0 | ||
258 | for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end | ||
259 | assert(i == 2*lim) | ||
260 | |||
261 | a = {}; setmetatable(a, {__mode = 'v'}); | ||
262 | a[1] = string.rep('b', 21) | ||
263 | collectgarbage() | ||
264 | assert(a[1]) -- strings are *values* | ||
265 | a[1] = undef | ||
266 | -- fill a with some `collectable' values (in both parts of the table) | ||
267 | for i=1,lim do a[i] = {} end | ||
268 | for i=1,lim do a[i..'x'] = {} end | ||
269 | -- and some non-collectable ones | ||
270 | for i=1,lim do local t={}; a[t]=t end | ||
271 | for i=1,lim do a[i+lim]=i..'x' end | ||
272 | collectgarbage() | ||
273 | local i = 0 | ||
274 | for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end | ||
275 | assert(i == 2*lim) | ||
276 | |||
277 | a = {}; setmetatable(a, {__mode = 'kv'}); | ||
278 | local x, y, z = {}, {}, {} | ||
279 | -- keep only some items | ||
280 | a[1], a[2], a[3] = x, y, z | ||
281 | a[string.rep('$', 11)] = string.rep('$', 11) | ||
282 | -- fill a with some `collectable' values | ||
283 | for i=4,lim do a[i] = {} end | ||
284 | for i=1,lim do a[{}] = i end | ||
285 | for i=1,lim do local t={}; a[t]=t end | ||
286 | collectgarbage() | ||
287 | assert(next(a) ~= nil) | ||
288 | local i = 0 | ||
289 | for k,v in pairs(a) do | ||
290 | assert((k == 1 and v == x) or | ||
291 | (k == 2 and v == y) or | ||
292 | (k == 3 and v == z) or k==v); | ||
293 | i = i+1 | ||
294 | end | ||
295 | assert(i == 4) | ||
296 | x,y,z=nil | ||
297 | collectgarbage() | ||
298 | assert(next(a) == string.rep('$', 11)) | ||
299 | |||
300 | |||
301 | -- 'bug' in 5.1 | ||
302 | a = {} | ||
303 | local t = {x = 10} | ||
304 | local C = setmetatable({key = t}, {__mode = 'v'}) | ||
305 | local C1 = setmetatable({[t] = 1}, {__mode = 'k'}) | ||
306 | a.x = t -- this should not prevent 't' from being removed from | ||
307 | -- weak table 'C' by the time 'a' is finalized | ||
308 | |||
309 | setmetatable(a, {__gc = function (u) | ||
310 | assert(C.key == nil) | ||
311 | assert(type(next(C1)) == 'table') | ||
312 | end}) | ||
313 | |||
314 | a, t = nil | ||
315 | collectgarbage() | ||
316 | collectgarbage() | ||
317 | assert(next(C) == nil and next(C1) == nil) | ||
318 | C, C1 = nil | ||
319 | |||
320 | |||
321 | -- ephemerons | ||
322 | local mt = {__mode = 'k'} | ||
323 | a = {{10},{20},{30},{40}}; setmetatable(a, mt) | ||
324 | x = nil | ||
325 | for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end | ||
326 | GC() | ||
327 | local n = x | ||
328 | local i = 0 | ||
329 | while n do n = a[n].k[1]; i = i + 1 end | ||
330 | assert(i == 100) | ||
331 | x = nil | ||
332 | GC() | ||
333 | for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = undef end | ||
334 | assert(next(a) == nil) | ||
335 | |||
336 | local K = {} | ||
337 | a[K] = {} | ||
338 | for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end | ||
339 | x = nil | ||
340 | local k = 1 | ||
341 | for j = 1,100 do | ||
342 | local n = {}; local nk = k%10 + 1 | ||
343 | a[a[K][nk]][n] = {x, k = k}; x = n; k = nk | ||
344 | end | ||
345 | GC() | ||
346 | local n = x | ||
347 | local i = 0 | ||
348 | while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end | ||
349 | assert(i == 100) | ||
350 | K = nil | ||
351 | GC() | ||
352 | -- assert(next(a) == nil) | ||
353 | |||
354 | |||
355 | -- testing errors during GC | ||
356 | do | ||
357 | collectgarbage("stop") -- stop collection | ||
358 | local u = {} | ||
359 | local s = {}; setmetatable(s, {__mode = 'k'}) | ||
360 | setmetatable(u, {__gc = function (o) | ||
361 | local i = s[o] | ||
362 | s[i] = true | ||
363 | assert(not s[i - 1]) -- check proper finalization order | ||
364 | if i == 8 then error("here") end -- error during GC | ||
365 | end}) | ||
366 | |||
367 | for i = 6, 10 do | ||
368 | local n = setmetatable({}, getmetatable(u)) | ||
369 | s[n] = i | ||
370 | end | ||
371 | |||
372 | assert(not pcall(collectgarbage)) | ||
373 | for i = 8, 10 do assert(s[i]) end | ||
374 | |||
375 | for i = 1, 5 do | ||
376 | local n = setmetatable({}, getmetatable(u)) | ||
377 | s[n] = i | ||
378 | end | ||
379 | |||
380 | collectgarbage() | ||
381 | for i = 1, 10 do assert(s[i]) end | ||
382 | |||
383 | getmetatable(u).__gc = false | ||
384 | |||
385 | |||
386 | -- __gc errors with non-string messages | ||
387 | setmetatable({}, {__gc = function () error{} end}) | ||
388 | local a, b = pcall(collectgarbage) | ||
389 | assert(not a and type(b) == "string" and string.find(b, "error in __gc")) | ||
390 | |||
391 | end | ||
392 | print '+' | ||
393 | |||
394 | |||
395 | -- testing userdata | ||
396 | if T==nil then | ||
397 | (Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n') | ||
398 | |||
399 | else | ||
400 | |||
401 | local function newproxy(u) | ||
402 | return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u)) | ||
403 | end | ||
404 | |||
405 | collectgarbage("stop") -- stop collection | ||
406 | local u = newproxy(nil) | ||
407 | debug.setmetatable(u, {__gc = true}) | ||
408 | local s = 0 | ||
409 | local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'}) | ||
410 | for i=1,10 do a[newproxy(u)] = i end | ||
411 | for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end | ||
412 | local a1 = {}; for k,v in pairs(a) do a1[k] = v end | ||
413 | for k,v in pairs(a1) do a[v] = k end | ||
414 | for i =1,10 do assert(a[i]) end | ||
415 | getmetatable(u).a = a1 | ||
416 | getmetatable(u).u = u | ||
417 | do | ||
418 | local u = u | ||
419 | getmetatable(u).__gc = function (o) | ||
420 | assert(a[o] == 10-s) | ||
421 | assert(a[10-s] == undef) -- udata already removed from weak table | ||
422 | assert(getmetatable(o) == getmetatable(u)) | ||
423 | assert(getmetatable(o).a[o] == 10-s) | ||
424 | s=s+1 | ||
425 | end | ||
426 | end | ||
427 | a1, u = nil | ||
428 | assert(next(a) ~= nil) | ||
429 | collectgarbage() | ||
430 | assert(s==11) | ||
431 | collectgarbage() | ||
432 | assert(next(a) == nil) -- finalized keys are removed in two cycles | ||
433 | end | ||
434 | |||
435 | |||
436 | -- __gc x weak tables | ||
437 | local u = setmetatable({}, {__gc = true}) | ||
438 | -- __gc metamethod should be collected before running | ||
439 | setmetatable(getmetatable(u), {__mode = "v"}) | ||
440 | getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen | ||
441 | u = nil | ||
442 | collectgarbage() | ||
443 | |||
444 | local u = setmetatable({}, {__gc = true}) | ||
445 | local m = getmetatable(u) | ||
446 | m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"}); | ||
447 | m.__gc = function (o) | ||
448 | assert(next(getmetatable(o).x) == nil) | ||
449 | m = 10 | ||
450 | end | ||
451 | u, m = nil | ||
452 | collectgarbage() | ||
453 | assert(m==10) | ||
454 | |||
455 | do -- tests for string keys in weak tables | ||
456 | collectgarbage(); collectgarbage() | ||
457 | local m = collectgarbage("count") -- current memory | ||
458 | local a = setmetatable({}, {__mode = "kv"}) | ||
459 | a[string.rep("a", 2^22)] = 25 -- long string key -> number value | ||
460 | a[string.rep("b", 2^22)] = {} -- long string key -> colectable value | ||
461 | a[{}] = 14 -- colectable key | ||
462 | assert(collectgarbage("count") > m + 2^13) -- 2^13 == 2 * 2^22 in KB | ||
463 | collectgarbage() | ||
464 | assert(collectgarbage("count") >= m + 2^12 and | ||
465 | collectgarbage("count") < m + 2^13) -- one key was collected | ||
466 | local k, v = next(a) -- string key with number value preserved | ||
467 | assert(k == string.rep("a", 2^22) and v == 25) | ||
468 | assert(next(a, k) == nil) -- everything else cleared | ||
469 | assert(a[string.rep("b", 2^22)] == undef) | ||
470 | a[k] = undef -- erase this last entry | ||
471 | k = nil | ||
472 | collectgarbage() | ||
473 | assert(next(a) == nil) | ||
474 | -- make sure will not try to compare with dead key | ||
475 | assert(a[string.rep("b", 100)] == undef) | ||
476 | assert(collectgarbage("count") <= m + 1) -- eveything collected | ||
477 | end | ||
478 | |||
479 | |||
480 | -- errors during collection | ||
481 | u = setmetatable({}, {__gc = function () error "!!!" end}) | ||
482 | u = nil | ||
483 | assert(not pcall(collectgarbage)) | ||
484 | |||
485 | |||
486 | if not _soft then | ||
487 | print("long list") | ||
488 | local a = {} | ||
489 | for i = 1,200000 do | ||
490 | a = {next = a} | ||
491 | end | ||
492 | a = nil | ||
493 | collectgarbage() | ||
494 | end | ||
495 | |||
496 | -- create many threads with self-references and open upvalues | ||
497 | print("self-referenced threads") | ||
498 | local thread_id = 0 | ||
499 | local threads = {} | ||
500 | |||
501 | local function fn (thread) | ||
502 | local x = {} | ||
503 | threads[thread_id] = function() | ||
504 | thread = x | ||
505 | end | ||
506 | coroutine.yield() | ||
507 | end | ||
508 | |||
509 | while thread_id < 1000 do | ||
510 | local thread = coroutine.create(fn) | ||
511 | coroutine.resume(thread, thread) | ||
512 | thread_id = thread_id + 1 | ||
513 | end | ||
514 | |||
515 | |||
516 | -- Create a closure (function inside 'f') with an upvalue ('param') that | ||
517 | -- points (through a table) to the closure itself and to the thread | ||
518 | -- ('co' and the initial value of 'param') where closure is running. | ||
519 | -- Then, assert that table (and therefore everything else) will be | ||
520 | -- collected. | ||
521 | do | ||
522 | local collected = false -- to detect collection | ||
523 | collectgarbage(); collectgarbage("stop") | ||
524 | do | ||
525 | local function f (param) | ||
526 | ;(function () | ||
527 | assert(type(f) == 'function' and type(param) == 'thread') | ||
528 | param = {param, f} | ||
529 | setmetatable(param, {__gc = function () collected = true end}) | ||
530 | coroutine.yield(100) | ||
531 | end)() | ||
532 | end | ||
533 | local co = coroutine.create(f) | ||
534 | assert(coroutine.resume(co, co)) | ||
535 | end | ||
536 | -- Now, thread and closure are not reacheable any more. | ||
537 | collectgarbage() | ||
538 | assert(collected) | ||
539 | collectgarbage("restart") | ||
540 | end | ||
541 | |||
542 | |||
543 | do | ||
544 | collectgarbage() | ||
545 | collectgarbage"stop" | ||
546 | collectgarbage("step", 0) -- steps should not unblock the collector | ||
547 | local x = gcinfo() | ||
548 | repeat | ||
549 | for i=1,1000 do _ENV.a = {} end -- no collection during the loop | ||
550 | until gcinfo() > 2 * x | ||
551 | collectgarbage"restart" | ||
552 | end | ||
553 | |||
554 | |||
555 | if T then -- tests for weird cases collecting upvalues | ||
556 | |||
557 | local function foo () | ||
558 | local a = {x = 20} | ||
559 | coroutine.yield(function () return a.x end) -- will run collector | ||
560 | assert(a.x == 20) -- 'a' is 'ok' | ||
561 | a = {x = 30} -- create a new object | ||
562 | assert(T.gccolor(a) == "white") -- of course it is new... | ||
563 | coroutine.yield(100) -- 'a' is still local to this thread | ||
564 | end | ||
565 | |||
566 | local t = setmetatable({}, {__mode = "kv"}) | ||
567 | collectgarbage(); collectgarbage('stop') | ||
568 | -- create coroutine in a weak table, so it will never be marked | ||
569 | t.co = coroutine.wrap(foo) | ||
570 | local f = t.co() -- create function to access local 'a' | ||
571 | T.gcstate("atomic") -- ensure all objects are traversed | ||
572 | assert(T.gcstate() == "atomic") | ||
573 | assert(t.co() == 100) -- resume coroutine, creating new table for 'a' | ||
574 | assert(T.gccolor(t.co) == "white") -- thread was not traversed | ||
575 | T.gcstate("pause") -- collect thread, but should mark 'a' before that | ||
576 | assert(t.co == nil and f() == 30) -- ensure correct access to 'a' | ||
577 | |||
578 | collectgarbage("restart") | ||
579 | |||
580 | -- test barrier in sweep phase (backing userdata to gray) | ||
581 | local u = T.newuserdata(0, 1) -- create a userdata | ||
582 | collectgarbage() | ||
583 | collectgarbage"stop" | ||
584 | local a = {} -- avoid 'u' as first element in 'allgc' | ||
585 | T.gcstate"atomic" | ||
586 | T.gcstate"sweepallgc" | ||
587 | local x = {} | ||
588 | assert(T.gccolor(u) == "black") -- userdata is "old" (black) | ||
589 | assert(T.gccolor(x) == "white") -- table is "new" (white) | ||
590 | debug.setuservalue(u, x) -- trigger barrier | ||
591 | assert(T.gccolor(u) == "gray") -- userdata changed back to gray | ||
592 | collectgarbage"restart" | ||
593 | |||
594 | print"+" | ||
595 | end | ||
596 | |||
597 | |||
598 | if T then | ||
599 | local debug = require "debug" | ||
600 | collectgarbage("stop") | ||
601 | local x = T.newuserdata(0) | ||
602 | local y = T.newuserdata(0) | ||
603 | debug.setmetatable(y, {__gc = true}) -- bless the new udata before... | ||
604 | debug.setmetatable(x, {__gc = true}) -- ...the old one | ||
605 | assert(T.gccolor(y) == "white") | ||
606 | T.checkmemory() | ||
607 | collectgarbage("restart") | ||
608 | end | ||
609 | |||
610 | |||
611 | if T then | ||
612 | print("emergency collections") | ||
613 | collectgarbage() | ||
614 | collectgarbage() | ||
615 | T.totalmem(T.totalmem() + 200) | ||
616 | for i=1,200 do local a = {} end | ||
617 | T.totalmem(0) | ||
618 | collectgarbage() | ||
619 | local t = T.totalmem("table") | ||
620 | local a = {{}, {}, {}} -- create 4 new tables | ||
621 | assert(T.totalmem("table") == t + 4) | ||
622 | t = T.totalmem("function") | ||
623 | a = function () end -- create 1 new closure | ||
624 | assert(T.totalmem("function") == t + 1) | ||
625 | t = T.totalmem("thread") | ||
626 | a = coroutine.create(function () end) -- create 1 new coroutine | ||
627 | assert(T.totalmem("thread") == t + 1) | ||
628 | end | ||
629 | |||
630 | -- create an object to be collected when state is closed | ||
631 | do | ||
632 | local setmetatable,assert,type,print,getmetatable = | ||
633 | setmetatable,assert,type,print,getmetatable | ||
634 | local tt = {} | ||
635 | tt.__gc = function (o) | ||
636 | assert(getmetatable(o) == tt) | ||
637 | -- create new objects during GC | ||
638 | local a = 'xuxu'..(10+3)..'joao', {} | ||
639 | ___Glob = o -- ressurect object! | ||
640 | setmetatable({}, tt) -- creates a new one with same metatable | ||
641 | print(">>> closing state " .. "<<<\n") | ||
642 | end | ||
643 | local u = setmetatable({}, tt) | ||
644 | ___Glob = {u} -- avoid object being collected before program end | ||
645 | end | ||
646 | |||
647 | -- create several objects to raise errors when collected while closing state | ||
648 | do | ||
649 | local mt = {__gc = function (o) return o + 1 end} | ||
650 | for i = 1,10 do | ||
651 | -- create object and preserve it until the end | ||
652 | table.insert(___Glob, setmetatable({}, mt)) | ||
653 | end | ||
654 | end | ||
655 | |||
656 | -- just to make sure | ||
657 | assert(collectgarbage'isrunning') | ||
658 | |||
659 | collectgarbage(oldmode) | ||
660 | |||
661 | print('OK') | ||
diff --git a/testes/goto.lua b/testes/goto.lua new file mode 100644 index 00000000..d22601f9 --- /dev/null +++ b/testes/goto.lua | |||
@@ -0,0 +1,256 @@ | |||
1 | -- $Id: goto.lua,v 1.15 2017/11/30 13:31:07 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | collectgarbage() | ||
5 | |||
6 | local function errmsg (code, m) | ||
7 | local st, msg = load(code) | ||
8 | assert(not st and string.find(msg, m)) | ||
9 | end | ||
10 | |||
11 | -- cannot see label inside block | ||
12 | errmsg([[ goto l1; do ::l1:: end ]], "label 'l1'") | ||
13 | errmsg([[ do ::l1:: end goto l1; ]], "label 'l1'") | ||
14 | |||
15 | -- repeated label | ||
16 | errmsg([[ ::l1:: ::l1:: ]], "label 'l1'") | ||
17 | |||
18 | |||
19 | -- undefined label | ||
20 | errmsg([[ goto l1; local aa ::l1:: ::l2:: print(3) ]], "local 'aa'") | ||
21 | |||
22 | -- jumping over variable definition | ||
23 | errmsg([[ | ||
24 | do local bb, cc; goto l1; end | ||
25 | local aa | ||
26 | ::l1:: print(3) | ||
27 | ]], "local 'aa'") | ||
28 | |||
29 | -- jumping into a block | ||
30 | errmsg([[ do ::l1:: end goto l1 ]], "label 'l1'") | ||
31 | errmsg([[ goto l1 do ::l1:: end ]], "label 'l1'") | ||
32 | |||
33 | -- cannot continue a repeat-until with variables | ||
34 | errmsg([[ | ||
35 | repeat | ||
36 | if x then goto cont end | ||
37 | local xuxu = 10 | ||
38 | ::cont:: | ||
39 | until xuxu < x | ||
40 | ]], "local 'xuxu'") | ||
41 | |||
42 | -- simple gotos | ||
43 | local x | ||
44 | do | ||
45 | local y = 12 | ||
46 | goto l1 | ||
47 | ::l2:: x = x + 1; goto l3 | ||
48 | ::l1:: x = y; goto l2 | ||
49 | end | ||
50 | ::l3:: ::l3_1:: assert(x == 13) | ||
51 | |||
52 | |||
53 | -- long labels | ||
54 | do | ||
55 | local prog = [[ | ||
56 | do | ||
57 | local a = 1 | ||
58 | goto l%sa; a = a + 1 | ||
59 | ::l%sa:: a = a + 10 | ||
60 | goto l%sb; a = a + 2 | ||
61 | ::l%sb:: a = a + 20 | ||
62 | return a | ||
63 | end | ||
64 | ]] | ||
65 | local label = string.rep("0123456789", 40) | ||
66 | prog = string.format(prog, label, label, label, label) | ||
67 | assert(assert(load(prog))() == 31) | ||
68 | end | ||
69 | |||
70 | -- goto to correct label when nested | ||
71 | do goto l3; ::l3:: end -- does not loop jumping to previous label 'l3' | ||
72 | |||
73 | -- ok to jump over local dec. to end of block | ||
74 | do | ||
75 | goto l1 | ||
76 | local a = 23 | ||
77 | x = a | ||
78 | ::l1::; | ||
79 | end | ||
80 | |||
81 | while true do | ||
82 | goto l4 | ||
83 | goto l1 -- ok to jump over local dec. to end of block | ||
84 | goto l1 -- multiple uses of same label | ||
85 | local x = 45 | ||
86 | ::l1:: ;;; | ||
87 | end | ||
88 | ::l4:: assert(x == 13) | ||
89 | |||
90 | if print then | ||
91 | goto l1 -- ok to jump over local dec. to end of block | ||
92 | error("should not be here") | ||
93 | goto l2 -- ok to jump over local dec. to end of block | ||
94 | local x | ||
95 | ::l1:: ; ::l2:: ;; | ||
96 | else end | ||
97 | |||
98 | -- to repeat a label in a different function is OK | ||
99 | local function foo () | ||
100 | local a = {} | ||
101 | goto l3 | ||
102 | ::l1:: a[#a + 1] = 1; goto l2; | ||
103 | ::l2:: a[#a + 1] = 2; goto l5; | ||
104 | ::l3:: | ||
105 | ::l3a:: a[#a + 1] = 3; goto l1; | ||
106 | ::l4:: a[#a + 1] = 4; goto l6; | ||
107 | ::l5:: a[#a + 1] = 5; goto l4; | ||
108 | ::l6:: assert(a[1] == 3 and a[2] == 1 and a[3] == 2 and | ||
109 | a[4] == 5 and a[5] == 4) | ||
110 | if not a[6] then a[6] = true; goto l3a end -- do it twice | ||
111 | end | ||
112 | |||
113 | ::l6:: foo() | ||
114 | |||
115 | |||
116 | do -- bug in 5.2 -> 5.3.2 | ||
117 | local x | ||
118 | ::L1:: | ||
119 | local y -- cannot join this SETNIL with previous one | ||
120 | assert(y == nil) | ||
121 | y = true | ||
122 | if x == nil then | ||
123 | x = 1 | ||
124 | goto L1 | ||
125 | else | ||
126 | x = x + 1 | ||
127 | end | ||
128 | assert(x == 2 and y == true) | ||
129 | end | ||
130 | |||
131 | -- bug in 5.3 | ||
132 | do | ||
133 | local first = true | ||
134 | local a = false | ||
135 | if true then | ||
136 | goto LBL | ||
137 | ::loop:: | ||
138 | a = true | ||
139 | ::LBL:: | ||
140 | if first then | ||
141 | first = false | ||
142 | goto loop | ||
143 | end | ||
144 | end | ||
145 | assert(a) | ||
146 | end | ||
147 | |||
148 | do -- compiling infinite loops | ||
149 | goto escape -- do not run the infinite loops | ||
150 | ::a:: goto a | ||
151 | ::b:: goto c | ||
152 | ::c:: goto b | ||
153 | end | ||
154 | ::escape:: | ||
155 | -------------------------------------------------------------------------------- | ||
156 | -- testing closing of upvalues | ||
157 | |||
158 | local debug = require 'debug' | ||
159 | |||
160 | local function foo () | ||
161 | local t = {} | ||
162 | do | ||
163 | local i = 1 | ||
164 | local a, b, c, d | ||
165 | t[1] = function () return a, b, c, d end | ||
166 | ::l1:: | ||
167 | local b | ||
168 | do | ||
169 | local c | ||
170 | t[#t + 1] = function () return a, b, c, d end -- t[2], t[4], t[6] | ||
171 | if i > 2 then goto l2 end | ||
172 | do | ||
173 | local d | ||
174 | t[#t + 1] = function () return a, b, c, d end -- t[3], t[5] | ||
175 | i = i + 1 | ||
176 | local a | ||
177 | goto l1 | ||
178 | end | ||
179 | end | ||
180 | end | ||
181 | ::l2:: return t | ||
182 | end | ||
183 | |||
184 | local a = foo() | ||
185 | assert(#a == 6) | ||
186 | |||
187 | -- all functions share same 'a' | ||
188 | for i = 2, 6 do | ||
189 | assert(debug.upvalueid(a[1], 1) == debug.upvalueid(a[i], 1)) | ||
190 | end | ||
191 | |||
192 | -- 'b' and 'c' are shared among some of them | ||
193 | for i = 2, 6 do | ||
194 | -- only a[1] uses external 'b'/'b' | ||
195 | assert(debug.upvalueid(a[1], 2) ~= debug.upvalueid(a[i], 2)) | ||
196 | assert(debug.upvalueid(a[1], 3) ~= debug.upvalueid(a[i], 3)) | ||
197 | end | ||
198 | |||
199 | for i = 3, 5, 2 do | ||
200 | -- inner functions share 'b'/'c' with previous ones | ||
201 | assert(debug.upvalueid(a[i], 2) == debug.upvalueid(a[i - 1], 2)) | ||
202 | assert(debug.upvalueid(a[i], 3) == debug.upvalueid(a[i - 1], 3)) | ||
203 | -- but not with next ones | ||
204 | assert(debug.upvalueid(a[i], 2) ~= debug.upvalueid(a[i + 1], 2)) | ||
205 | assert(debug.upvalueid(a[i], 3) ~= debug.upvalueid(a[i + 1], 3)) | ||
206 | end | ||
207 | |||
208 | -- only external 'd' is shared | ||
209 | for i = 2, 6, 2 do | ||
210 | assert(debug.upvalueid(a[1], 4) == debug.upvalueid(a[i], 4)) | ||
211 | end | ||
212 | |||
213 | -- internal 'd's are all different | ||
214 | for i = 3, 5, 2 do | ||
215 | for j = 1, 6 do | ||
216 | assert((debug.upvalueid(a[i], 4) == debug.upvalueid(a[j], 4)) | ||
217 | == (i == j)) | ||
218 | end | ||
219 | end | ||
220 | |||
221 | -------------------------------------------------------------------------------- | ||
222 | -- testing if x goto optimizations | ||
223 | |||
224 | local function testG (a) | ||
225 | if a == 1 then | ||
226 | goto l1 | ||
227 | error("should never be here!") | ||
228 | elseif a == 2 then goto l2 | ||
229 | elseif a == 3 then goto l3 | ||
230 | elseif a == 4 then | ||
231 | goto l1 -- go to inside the block | ||
232 | error("should never be here!") | ||
233 | ::l1:: a = a + 1 -- must go to 'if' end | ||
234 | else | ||
235 | goto l4 | ||
236 | ::l4a:: a = a * 2; goto l4b | ||
237 | error("should never be here!") | ||
238 | ::l4:: goto l4a | ||
239 | error("should never be here!") | ||
240 | ::l4b:: | ||
241 | end | ||
242 | do return a end | ||
243 | ::l2:: do return "2" end | ||
244 | ::l3:: do return "3" end | ||
245 | ::l1:: return "1" | ||
246 | end | ||
247 | |||
248 | assert(testG(1) == "1") | ||
249 | assert(testG(2) == "2") | ||
250 | assert(testG(3) == "3") | ||
251 | assert(testG(4) == 5) | ||
252 | assert(testG(5) == 10) | ||
253 | -------------------------------------------------------------------------------- | ||
254 | |||
255 | |||
256 | print'OK' | ||
diff --git a/testes/libs/lib1.c b/testes/libs/lib1.c new file mode 100644 index 00000000..56b6ef41 --- /dev/null +++ b/testes/libs/lib1.c | |||
@@ -0,0 +1,44 @@ | |||
1 | #include "lua.h" | ||
2 | #include "lauxlib.h" | ||
3 | |||
4 | static int id (lua_State *L) { | ||
5 | return lua_gettop(L); | ||
6 | } | ||
7 | |||
8 | |||
9 | static const struct luaL_Reg funcs[] = { | ||
10 | {"id", id}, | ||
11 | {NULL, NULL} | ||
12 | }; | ||
13 | |||
14 | |||
15 | /* function used by lib11.c */ | ||
16 | LUAMOD_API int lib1_export (lua_State *L) { | ||
17 | lua_pushstring(L, "exported"); | ||
18 | return 1; | ||
19 | } | ||
20 | |||
21 | |||
22 | LUAMOD_API int onefunction (lua_State *L) { | ||
23 | luaL_checkversion(L); | ||
24 | lua_settop(L, 2); | ||
25 | lua_pushvalue(L, 1); | ||
26 | return 2; | ||
27 | } | ||
28 | |||
29 | |||
30 | LUAMOD_API int anotherfunc (lua_State *L) { | ||
31 | luaL_checkversion(L); | ||
32 | lua_pushfstring(L, "%d%%%d\n", (int)lua_tointeger(L, 1), | ||
33 | (int)lua_tointeger(L, 2)); | ||
34 | return 1; | ||
35 | } | ||
36 | |||
37 | |||
38 | LUAMOD_API int luaopen_lib1_sub (lua_State *L) { | ||
39 | lua_setglobal(L, "y"); /* 2nd arg: extra value (file name) */ | ||
40 | lua_setglobal(L, "x"); /* 1st arg: module name */ | ||
41 | luaL_newlib(L, funcs); | ||
42 | return 1; | ||
43 | } | ||
44 | |||
diff --git a/testes/libs/lib11.c b/testes/libs/lib11.c new file mode 100644 index 00000000..377d0c48 --- /dev/null +++ b/testes/libs/lib11.c | |||
@@ -0,0 +1,10 @@ | |||
1 | #include "lua.h" | ||
2 | |||
3 | /* function from lib1.c */ | ||
4 | int lib1_export (lua_State *L); | ||
5 | |||
6 | LUAMOD_API int luaopen_lib11 (lua_State *L) { | ||
7 | return lib1_export(L); | ||
8 | } | ||
9 | |||
10 | |||
diff --git a/testes/libs/lib2.c b/testes/libs/lib2.c new file mode 100644 index 00000000..bc9651ee --- /dev/null +++ b/testes/libs/lib2.c | |||
@@ -0,0 +1,23 @@ | |||
1 | #include "lua.h" | ||
2 | #include "lauxlib.h" | ||
3 | |||
4 | static int id (lua_State *L) { | ||
5 | return lua_gettop(L); | ||
6 | } | ||
7 | |||
8 | |||
9 | static const struct luaL_Reg funcs[] = { | ||
10 | {"id", id}, | ||
11 | {NULL, NULL} | ||
12 | }; | ||
13 | |||
14 | |||
15 | LUAMOD_API int luaopen_lib2 (lua_State *L) { | ||
16 | lua_settop(L, 2); | ||
17 | lua_setglobal(L, "y"); /* y gets 2nd parameter */ | ||
18 | lua_setglobal(L, "x"); /* x gets 1st parameter */ | ||
19 | luaL_newlib(L, funcs); | ||
20 | return 1; | ||
21 | } | ||
22 | |||
23 | |||
diff --git a/testes/libs/lib21.c b/testes/libs/lib21.c new file mode 100644 index 00000000..a39b683d --- /dev/null +++ b/testes/libs/lib21.c | |||
@@ -0,0 +1,10 @@ | |||
1 | #include "lua.h" | ||
2 | |||
3 | |||
4 | int luaopen_lib2 (lua_State *L); | ||
5 | |||
6 | LUAMOD_API int luaopen_lib21 (lua_State *L) { | ||
7 | return luaopen_lib2(L); | ||
8 | } | ||
9 | |||
10 | |||
diff --git a/testes/libs/makefile b/testes/libs/makefile new file mode 100644 index 00000000..9925fb00 --- /dev/null +++ b/testes/libs/makefile | |||
@@ -0,0 +1,26 @@ | |||
1 | # change this variable to point to the directory with Lua headers | ||
2 | # of the version being tested | ||
3 | LUA_DIR = ../../ | ||
4 | |||
5 | CC = gcc | ||
6 | |||
7 | # compilation should generate Dynamic-Link Libraries | ||
8 | CFLAGS = -Wall -std=gnu99 -O2 -I$(LUA_DIR) -fPIC -shared | ||
9 | |||
10 | # libraries used by the tests | ||
11 | all: lib1.so lib11.so lib2.so lib21.so lib2-v2.so | ||
12 | |||
13 | lib1.so: lib1.c | ||
14 | $(CC) $(CFLAGS) -o lib1.so lib1.c | ||
15 | |||
16 | lib11.so: lib11.c | ||
17 | $(CC) $(CFLAGS) -o lib11.so lib11.c | ||
18 | |||
19 | lib2.so: lib2.c | ||
20 | $(CC) $(CFLAGS) -o lib2.so lib2.c | ||
21 | |||
22 | lib21.so: lib21.c | ||
23 | $(CC) $(CFLAGS) -o lib21.so lib21.c | ||
24 | |||
25 | lib2-v2.so: lib2.so | ||
26 | mv lib2.so ./lib2-v2.so | ||
diff --git a/testes/literals.lua b/testes/literals.lua new file mode 100644 index 00000000..3922b3f5 --- /dev/null +++ b/testes/literals.lua | |||
@@ -0,0 +1,302 @@ | |||
1 | -- $Id: literals.lua,v 1.36 2016/11/07 13:11:28 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing scanner') | ||
5 | |||
6 | local debug = require "debug" | ||
7 | |||
8 | |||
9 | local function dostring (x) return assert(load(x), "")() end | ||
10 | |||
11 | dostring("x \v\f = \t\r 'a\0a' \v\f\f") | ||
12 | assert(x == 'a\0a' and string.len(x) == 3) | ||
13 | |||
14 | -- escape sequences | ||
15 | assert('\n\"\'\\' == [[ | ||
16 | |||
17 | "'\]]) | ||
18 | |||
19 | assert(string.find("\a\b\f\n\r\t\v", "^%c%c%c%c%c%c%c$")) | ||
20 | |||
21 | -- assume ASCII just for tests: | ||
22 | assert("\09912" == 'c12') | ||
23 | assert("\99ab" == 'cab') | ||
24 | assert("\099" == '\99') | ||
25 | assert("\099\n" == 'c\10') | ||
26 | assert('\0\0\0alo' == '\0' .. '\0\0' .. 'alo') | ||
27 | |||
28 | assert(010 .. 020 .. -030 == "1020-30") | ||
29 | |||
30 | -- hexadecimal escapes | ||
31 | assert("\x00\x05\x10\x1f\x3C\xfF\xe8" == "\0\5\16\31\60\255\232") | ||
32 | |||
33 | local function lexstring (x, y, n) | ||
34 | local f = assert(load('return ' .. x .. | ||
35 | ', require"debug".getinfo(1).currentline', '')) | ||
36 | local s, l = f() | ||
37 | assert(s == y and l == n) | ||
38 | end | ||
39 | |||
40 | lexstring("'abc\\z \n efg'", "abcefg", 2) | ||
41 | lexstring("'abc\\z \n\n\n'", "abc", 4) | ||
42 | lexstring("'\\z \n\t\f\v\n'", "", 3) | ||
43 | lexstring("[[\nalo\nalo\n\n]]", "alo\nalo\n\n", 5) | ||
44 | lexstring("[[\nalo\ralo\n\n]]", "alo\nalo\n\n", 5) | ||
45 | lexstring("[[\nalo\ralo\r\n]]", "alo\nalo\n", 4) | ||
46 | lexstring("[[\ralo\n\ralo\r\n]]", "alo\nalo\n", 4) | ||
47 | lexstring("[[alo]\n]alo]]", "alo]\n]alo", 2) | ||
48 | |||
49 | assert("abc\z | ||
50 | def\z | ||
51 | ghi\z | ||
52 | " == 'abcdefghi') | ||
53 | |||
54 | |||
55 | -- UTF-8 sequences | ||
56 | assert("\u{0}\u{00000000}\x00\0" == string.char(0, 0, 0, 0)) | ||
57 | |||
58 | -- limits for 1-byte sequences | ||
59 | assert("\u{0}\u{7F}" == "\x00\z\x7F") | ||
60 | |||
61 | -- limits for 2-byte sequences | ||
62 | assert("\u{80}\u{7FF}" == "\xC2\x80\z\xDF\xBF") | ||
63 | |||
64 | -- limits for 3-byte sequences | ||
65 | assert("\u{800}\u{FFFF}" == "\xE0\xA0\x80\z\xEF\xBF\xBF") | ||
66 | |||
67 | -- limits for 4-byte sequences | ||
68 | assert("\u{10000}\u{10FFFF}" == "\xF0\x90\x80\x80\z\xF4\x8F\xBF\xBF") | ||
69 | |||
70 | |||
71 | -- Error in escape sequences | ||
72 | local function lexerror (s, err) | ||
73 | local st, msg = load('return ' .. s, '') | ||
74 | if err ~= '<eof>' then err = err .. "'" end | ||
75 | assert(not st and string.find(msg, "near .-" .. err)) | ||
76 | end | ||
77 | |||
78 | lexerror([["abc\x"]], [[\x"]]) | ||
79 | lexerror([["abc\x]], [[\x]]) | ||
80 | lexerror([["\x]], [[\x]]) | ||
81 | lexerror([["\x5"]], [[\x5"]]) | ||
82 | lexerror([["\x5]], [[\x5]]) | ||
83 | lexerror([["\xr"]], [[\xr]]) | ||
84 | lexerror([["\xr]], [[\xr]]) | ||
85 | lexerror([["\x.]], [[\x.]]) | ||
86 | lexerror([["\x8%"]], [[\x8%%]]) | ||
87 | lexerror([["\xAG]], [[\xAG]]) | ||
88 | lexerror([["\g"]], [[\g]]) | ||
89 | lexerror([["\g]], [[\g]]) | ||
90 | lexerror([["\."]], [[\%.]]) | ||
91 | |||
92 | lexerror([["\999"]], [[\999"]]) | ||
93 | lexerror([["xyz\300"]], [[\300"]]) | ||
94 | lexerror([[" \256"]], [[\256"]]) | ||
95 | |||
96 | -- errors in UTF-8 sequences | ||
97 | lexerror([["abc\u{110000}"]], [[abc\u{110000]]) -- too large | ||
98 | lexerror([["abc\u11r"]], [[abc\u1]]) -- missing '{' | ||
99 | lexerror([["abc\u"]], [[abc\u"]]) -- missing '{' | ||
100 | lexerror([["abc\u{11r"]], [[abc\u{11r]]) -- missing '}' | ||
101 | lexerror([["abc\u{11"]], [[abc\u{11"]]) -- missing '}' | ||
102 | lexerror([["abc\u{11]], [[abc\u{11]]) -- missing '}' | ||
103 | lexerror([["abc\u{r"]], [[abc\u{r]]) -- no digits | ||
104 | |||
105 | -- unfinished strings | ||
106 | lexerror("[=[alo]]", "<eof>") | ||
107 | lexerror("[=[alo]=", "<eof>") | ||
108 | lexerror("[=[alo]", "<eof>") | ||
109 | lexerror("'alo", "<eof>") | ||
110 | lexerror("'alo \\z \n\n", "<eof>") | ||
111 | lexerror("'alo \\z", "<eof>") | ||
112 | lexerror([['alo \98]], "<eof>") | ||
113 | |||
114 | -- valid characters in variable names | ||
115 | for i = 0, 255 do | ||
116 | local s = string.char(i) | ||
117 | assert(not string.find(s, "[a-zA-Z_]") == not load(s .. "=1", "")) | ||
118 | assert(not string.find(s, "[a-zA-Z_0-9]") == | ||
119 | not load("a" .. s .. "1 = 1", "")) | ||
120 | end | ||
121 | |||
122 | |||
123 | -- long variable names | ||
124 | |||
125 | var1 = string.rep('a', 15000) .. '1' | ||
126 | var2 = string.rep('a', 15000) .. '2' | ||
127 | prog = string.format([[ | ||
128 | %s = 5 | ||
129 | %s = %s + 1 | ||
130 | return function () return %s - %s end | ||
131 | ]], var1, var2, var1, var1, var2) | ||
132 | local f = dostring(prog) | ||
133 | assert(_G[var1] == 5 and _G[var2] == 6 and f() == -1) | ||
134 | var1, var2, f = nil | ||
135 | print('+') | ||
136 | |||
137 | -- escapes -- | ||
138 | assert("\n\t" == [[ | ||
139 | |||
140 | ]]) | ||
141 | assert([[ | ||
142 | |||
143 | $debug]] == "\n $debug") | ||
144 | assert([[ [ ]] ~= [[ ] ]]) | ||
145 | -- long strings -- | ||
146 | b = "001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789" | ||
147 | assert(string.len(b) == 960) | ||
148 | prog = [=[ | ||
149 | print('+') | ||
150 | |||
151 | a1 = [["this is a 'string' with several 'quotes'"]] | ||
152 | a2 = "'quotes'" | ||
153 | |||
154 | assert(string.find(a1, a2) == 34) | ||
155 | print('+') | ||
156 | |||
157 | a1 = [==[temp = [[an arbitrary value]]; ]==] | ||
158 | assert(load(a1))() | ||
159 | assert(temp == 'an arbitrary value') | ||
160 | -- long strings -- | ||
161 | b = "001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789" | ||
162 | assert(string.len(b) == 960) | ||
163 | print('+') | ||
164 | |||
165 | a = [[00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
166 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
167 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
168 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
169 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
170 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
171 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
172 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
173 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
174 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
175 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
176 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
177 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
178 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
179 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
180 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
181 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
182 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
183 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
184 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
185 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
186 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
187 | 00123456789012345678901234567890123456789123456789012345678901234567890123456789 | ||
188 | ]] | ||
189 | assert(string.len(a) == 1863) | ||
190 | assert(string.sub(a, 1, 40) == string.sub(b, 1, 40)) | ||
191 | x = 1 | ||
192 | ]=] | ||
193 | |||
194 | print('+') | ||
195 | x = nil | ||
196 | dostring(prog) | ||
197 | assert(x) | ||
198 | |||
199 | prog = nil | ||
200 | a = nil | ||
201 | b = nil | ||
202 | |||
203 | |||
204 | -- testing line ends | ||
205 | prog = [[ | ||
206 | a = 1 -- a comment | ||
207 | b = 2 | ||
208 | |||
209 | |||
210 | x = [=[ | ||
211 | hi | ||
212 | ]=] | ||
213 | y = "\ | ||
214 | hello\r\n\ | ||
215 | " | ||
216 | return require"debug".getinfo(1).currentline | ||
217 | ]] | ||
218 | |||
219 | for _, n in pairs{"\n", "\r", "\n\r", "\r\n"} do | ||
220 | local prog, nn = string.gsub(prog, "\n", n) | ||
221 | assert(dostring(prog) == nn) | ||
222 | assert(_G.x == "hi\n" and _G.y == "\nhello\r\n\n") | ||
223 | end | ||
224 | |||
225 | |||
226 | -- testing comments and strings with long brackets | ||
227 | a = [==[]=]==] | ||
228 | assert(a == "]=") | ||
229 | |||
230 | a = [==[[===[[=[]]=][====[]]===]===]==] | ||
231 | assert(a == "[===[[=[]]=][====[]]===]===") | ||
232 | |||
233 | a = [====[[===[[=[]]=][====[]]===]===]====] | ||
234 | assert(a == "[===[[=[]]=][====[]]===]===") | ||
235 | |||
236 | a = [=[]]]]]]]]]=] | ||
237 | assert(a == "]]]]]]]]") | ||
238 | |||
239 | |||
240 | --[===[ | ||
241 | x y z [==[ blu foo | ||
242 | ]== | ||
243 | ] | ||
244 | ]=]==] | ||
245 | error error]=]===] | ||
246 | |||
247 | -- generate all strings of four of these chars | ||
248 | local x = {"=", "[", "]", "\n"} | ||
249 | local len = 4 | ||
250 | local function gen (c, n) | ||
251 | if n==0 then coroutine.yield(c) | ||
252 | else | ||
253 | for _, a in pairs(x) do | ||
254 | gen(c..a, n-1) | ||
255 | end | ||
256 | end | ||
257 | end | ||
258 | |||
259 | for s in coroutine.wrap(function () gen("", len) end) do | ||
260 | assert(s == load("return [====[\n"..s.."]====]", "")()) | ||
261 | end | ||
262 | |||
263 | |||
264 | -- testing decimal point locale | ||
265 | if os.setlocale("pt_BR") or os.setlocale("ptb") then | ||
266 | assert(tonumber("3,4") == 3.4 and tonumber"3.4" == 3.4) | ||
267 | assert(tonumber(" -.4 ") == -0.4) | ||
268 | assert(tonumber(" +0x.41 ") == 0X0.41) | ||
269 | assert(not load("a = (3,4)")) | ||
270 | assert(assert(load("return 3.4"))() == 3.4) | ||
271 | assert(assert(load("return .4,3"))() == .4) | ||
272 | assert(assert(load("return 4."))() == 4.) | ||
273 | assert(assert(load("return 4.+.5"))() == 4.5) | ||
274 | |||
275 | assert(" 0x.1 " + " 0x,1" + "-0X.1\t" == 0x0.1) | ||
276 | |||
277 | assert(tonumber"inf" == nil and tonumber"NAN" == nil) | ||
278 | |||
279 | assert(assert(load(string.format("return %q", 4.51)))() == 4.51) | ||
280 | |||
281 | local a,b = load("return 4.5.") | ||
282 | assert(string.find(b, "'4%.5%.'")) | ||
283 | |||
284 | assert(os.setlocale("C")) | ||
285 | else | ||
286 | (Message or print)( | ||
287 | '\n >>> pt_BR locale not available: skipping decimal point tests <<<\n') | ||
288 | end | ||
289 | |||
290 | |||
291 | -- testing %q x line ends | ||
292 | local s = "a string with \r and \n and \r\n and \n\r" | ||
293 | local c = string.format("return %q", s) | ||
294 | assert(assert(load(c))() == s) | ||
295 | |||
296 | -- testing errors | ||
297 | assert(not load"a = 'non-ending string") | ||
298 | assert(not load"a = 'non-ending string\n'") | ||
299 | assert(not load"a = '\\345'") | ||
300 | assert(not load"a = [=x]") | ||
301 | |||
302 | print('OK') | ||
diff --git a/testes/locals.lua b/testes/locals.lua new file mode 100644 index 00000000..f0780a03 --- /dev/null +++ b/testes/locals.lua | |||
@@ -0,0 +1,181 @@ | |||
1 | -- $Id: locals.lua,v 1.41 2018/06/19 12:25:39 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing local variables and environments') | ||
5 | |||
6 | local debug = require"debug" | ||
7 | |||
8 | |||
9 | -- bug in 5.1: | ||
10 | |||
11 | local function f(x) x = nil; return x end | ||
12 | assert(f(10) == nil) | ||
13 | |||
14 | local function f() local x; return x end | ||
15 | assert(f(10) == nil) | ||
16 | |||
17 | local function f(x) x = nil; local y; return x, y end | ||
18 | assert(f(10) == nil and select(2, f(20)) == nil) | ||
19 | |||
20 | do | ||
21 | local i = 10 | ||
22 | do local i = 100; assert(i==100) end | ||
23 | do local i = 1000; assert(i==1000) end | ||
24 | assert(i == 10) | ||
25 | if i ~= 10 then | ||
26 | local i = 20 | ||
27 | else | ||
28 | local i = 30 | ||
29 | assert(i == 30) | ||
30 | end | ||
31 | end | ||
32 | |||
33 | |||
34 | |||
35 | f = nil | ||
36 | |||
37 | local f | ||
38 | x = 1 | ||
39 | |||
40 | a = nil | ||
41 | load('local a = {}')() | ||
42 | assert(a == nil) | ||
43 | |||
44 | function f (a) | ||
45 | local _1, _2, _3, _4, _5 | ||
46 | local _6, _7, _8, _9, _10 | ||
47 | local x = 3 | ||
48 | local b = a | ||
49 | local c,d = a,b | ||
50 | if (d == b) then | ||
51 | local x = 'q' | ||
52 | x = b | ||
53 | assert(x == 2) | ||
54 | else | ||
55 | assert(nil) | ||
56 | end | ||
57 | assert(x == 3) | ||
58 | local f = 10 | ||
59 | end | ||
60 | |||
61 | local b=10 | ||
62 | local a; repeat local b; a,b=1,2; assert(a+1==b); until a+b==3 | ||
63 | |||
64 | |||
65 | assert(x == 1) | ||
66 | |||
67 | f(2) | ||
68 | assert(type(f) == 'function') | ||
69 | |||
70 | |||
71 | local function getenv (f) | ||
72 | local a,b = debug.getupvalue(f, 1) | ||
73 | assert(a == '_ENV') | ||
74 | return b | ||
75 | end | ||
76 | |||
77 | -- test for global table of loaded chunks | ||
78 | assert(getenv(load"a=3") == _G) | ||
79 | local c = {}; local f = load("a = 3", nil, nil, c) | ||
80 | assert(getenv(f) == c) | ||
81 | assert(c.a == nil) | ||
82 | f() | ||
83 | assert(c.a == 3) | ||
84 | |||
85 | -- old test for limits for special instructions (now just a generic test) | ||
86 | do | ||
87 | local i = 2 | ||
88 | local p = 4 -- p == 2^i | ||
89 | repeat | ||
90 | for j=-3,3 do | ||
91 | assert(load(string.format([[local a=%s; | ||
92 | a=a+%s; | ||
93 | assert(a ==2^%s)]], j, p-j, i), '')) () | ||
94 | assert(load(string.format([[local a=%s; | ||
95 | a=a-%s; | ||
96 | assert(a==-2^%s)]], -j, p-j, i), '')) () | ||
97 | assert(load(string.format([[local a,b=0,%s; | ||
98 | a=b-%s; | ||
99 | assert(a==-2^%s)]], -j, p-j, i), '')) () | ||
100 | end | ||
101 | p = 2 * p; i = i + 1 | ||
102 | until p <= 0 | ||
103 | end | ||
104 | |||
105 | print'+' | ||
106 | |||
107 | |||
108 | if rawget(_G, "T") then | ||
109 | -- testing clearing of dead elements from tables | ||
110 | collectgarbage("stop") -- stop GC | ||
111 | local a = {[{}] = 4, [3] = 0, alo = 1, | ||
112 | a1234567890123456789012345678901234567890 = 10} | ||
113 | |||
114 | local t = T.querytab(a) | ||
115 | |||
116 | for k,_ in pairs(a) do a[k] = undef end | ||
117 | collectgarbage() -- restore GC and collect dead fiels in `a' | ||
118 | for i=0,t-1 do | ||
119 | local k = querytab(a, i) | ||
120 | assert(k == nil or type(k) == 'number' or k == 'alo') | ||
121 | end | ||
122 | |||
123 | -- testing allocation errors during table insertions | ||
124 | local a = {} | ||
125 | local function additems () | ||
126 | a.x = true; a.y = true; a.z = true | ||
127 | a[1] = true | ||
128 | a[2] = true | ||
129 | end | ||
130 | for i = 1, math.huge do | ||
131 | T.alloccount(i) | ||
132 | local st, msg = pcall(additems) | ||
133 | T.alloccount() | ||
134 | local count = 0 | ||
135 | for k, v in pairs(a) do | ||
136 | assert(a[k] == v) | ||
137 | count = count + 1 | ||
138 | end | ||
139 | if st then assert(count == 5); break end | ||
140 | end | ||
141 | end | ||
142 | |||
143 | |||
144 | -- testing lexical environments | ||
145 | |||
146 | assert(_ENV == _G) | ||
147 | |||
148 | do | ||
149 | local dummy | ||
150 | local _ENV = (function (...) return ... end)(_G, dummy) -- { | ||
151 | |||
152 | do local _ENV = {assert=assert}; assert(true) end | ||
153 | mt = {_G = _G} | ||
154 | local foo,x | ||
155 | A = false -- "declare" A | ||
156 | do local _ENV = mt | ||
157 | function foo (x) | ||
158 | A = x | ||
159 | do local _ENV = _G; A = 1000 end | ||
160 | return function (x) return A .. x end | ||
161 | end | ||
162 | end | ||
163 | assert(getenv(foo) == mt) | ||
164 | x = foo('hi'); assert(mt.A == 'hi' and A == 1000) | ||
165 | assert(x('*') == mt.A .. '*') | ||
166 | |||
167 | do local _ENV = {assert=assert, A=10}; | ||
168 | do local _ENV = {assert=assert, A=20}; | ||
169 | assert(A==20);x=A | ||
170 | end | ||
171 | assert(A==10 and x==20) | ||
172 | end | ||
173 | assert(x==20) | ||
174 | |||
175 | |||
176 | print('OK') | ||
177 | |||
178 | return 5,f | ||
179 | |||
180 | end -- } | ||
181 | |||
diff --git a/testes/main.lua b/testes/main.lua new file mode 100644 index 00000000..582b39c0 --- /dev/null +++ b/testes/main.lua | |||
@@ -0,0 +1,381 @@ | |||
1 | # testing special comment on first line | ||
2 | -- $Id: main.lua,v 1.69 2018/06/19 12:23:50 roberto Exp $ | ||
3 | -- See Copyright Notice in file all.lua | ||
4 | |||
5 | -- most (all?) tests here assume a reasonable "Unix-like" shell | ||
6 | if _port then return end | ||
7 | |||
8 | -- use only "double quotes" inside shell scripts (better change to | ||
9 | -- run on Windows) | ||
10 | |||
11 | |||
12 | print ("testing stand-alone interpreter") | ||
13 | |||
14 | assert(os.execute()) -- machine has a system command | ||
15 | |||
16 | local arg = arg or ARG | ||
17 | |||
18 | local prog = os.tmpname() | ||
19 | local otherprog = os.tmpname() | ||
20 | local out = os.tmpname() | ||
21 | |||
22 | local progname | ||
23 | do | ||
24 | local i = 0 | ||
25 | while arg[i] do i=i-1 end | ||
26 | progname = arg[i+1] | ||
27 | end | ||
28 | print("progname: "..progname) | ||
29 | |||
30 | local prepfile = function (s, p) | ||
31 | p = p or prog | ||
32 | io.output(p) | ||
33 | io.write(s) | ||
34 | assert(io.close()) | ||
35 | end | ||
36 | |||
37 | local function getoutput () | ||
38 | io.input(out) | ||
39 | local t = io.read("a") | ||
40 | io.input():close() | ||
41 | assert(os.remove(out)) | ||
42 | return t | ||
43 | end | ||
44 | |||
45 | local function checkprogout (s) | ||
46 | local t = getoutput() | ||
47 | for line in string.gmatch(s, ".-\n") do | ||
48 | assert(string.find(t, line, 1, true)) | ||
49 | end | ||
50 | end | ||
51 | |||
52 | local function checkout (s) | ||
53 | local t = getoutput() | ||
54 | if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end | ||
55 | assert(s == t) | ||
56 | return t | ||
57 | end | ||
58 | |||
59 | |||
60 | local function RUN (p, ...) | ||
61 | p = string.gsub(p, "lua", '"'..progname..'"', 1) | ||
62 | local s = string.format(p, ...) | ||
63 | assert(os.execute(s)) | ||
64 | end | ||
65 | |||
66 | local function NoRun (msg, p, ...) | ||
67 | p = string.gsub(p, "lua", '"'..progname..'"', 1) | ||
68 | local s = string.format(p, ...) | ||
69 | s = string.format("%s 2> %s", s, out) -- will send error to 'out' | ||
70 | assert(not os.execute(s)) | ||
71 | assert(string.find(getoutput(), msg, 1, true)) -- check error message | ||
72 | end | ||
73 | |||
74 | RUN('lua -v') | ||
75 | |||
76 | print(string.format("(temporary program file used in these tests: %s)", prog)) | ||
77 | |||
78 | -- running stdin as a file | ||
79 | prepfile"" | ||
80 | RUN('lua - < %s > %s', prog, out) | ||
81 | checkout("") | ||
82 | |||
83 | prepfile[[ | ||
84 | print( | ||
85 | 1, a | ||
86 | ) | ||
87 | ]] | ||
88 | RUN('lua - < %s > %s', prog, out) | ||
89 | checkout("1\tnil\n") | ||
90 | |||
91 | RUN('echo "print(10)\nprint(2)\n" | lua > %s', out) | ||
92 | checkout("10\n2\n") | ||
93 | |||
94 | |||
95 | -- test option '-' | ||
96 | RUN('echo "print(arg[1])" | lua - -h > %s', out) | ||
97 | checkout("-h\n") | ||
98 | |||
99 | -- test environment variables used by Lua | ||
100 | |||
101 | prepfile("print(package.path)") | ||
102 | |||
103 | -- test LUA_PATH | ||
104 | RUN('env LUA_INIT= LUA_PATH=x lua %s > %s', prog, out) | ||
105 | checkout("x\n") | ||
106 | |||
107 | -- test LUA_PATH_version | ||
108 | RUN('env LUA_INIT= LUA_PATH_5_4=y LUA_PATH=x lua %s > %s', prog, out) | ||
109 | checkout("y\n") | ||
110 | |||
111 | -- test LUA_CPATH | ||
112 | prepfile("print(package.cpath)") | ||
113 | RUN('env LUA_INIT= LUA_CPATH=xuxu lua %s > %s', prog, out) | ||
114 | checkout("xuxu\n") | ||
115 | |||
116 | -- test LUA_CPATH_version | ||
117 | RUN('env LUA_INIT= LUA_CPATH_5_4=yacc LUA_CPATH=x lua %s > %s', prog, out) | ||
118 | checkout("yacc\n") | ||
119 | |||
120 | -- test LUA_INIT (and its access to 'arg' table) | ||
121 | prepfile("print(X)") | ||
122 | RUN('env LUA_INIT="X=tonumber(arg[1])" lua %s 3.2 > %s', prog, out) | ||
123 | checkout("3.2\n") | ||
124 | |||
125 | -- test LUA_INIT_version | ||
126 | prepfile("print(X)") | ||
127 | RUN('env LUA_INIT_5_4="X=10" LUA_INIT="X=3" lua %s > %s', prog, out) | ||
128 | checkout("10\n") | ||
129 | |||
130 | -- test LUA_INIT for files | ||
131 | prepfile("x = x or 10; print(x); x = x + 1") | ||
132 | RUN('env LUA_INIT="@%s" lua %s > %s', prog, prog, out) | ||
133 | checkout("10\n11\n") | ||
134 | |||
135 | -- test errors in LUA_INIT | ||
136 | NoRun('LUA_INIT:1: msg', 'env LUA_INIT="error(\'msg\')" lua') | ||
137 | |||
138 | -- test option '-E' | ||
139 | local defaultpath, defaultCpath | ||
140 | |||
141 | do | ||
142 | prepfile("print(package.path, package.cpath)") | ||
143 | RUN('env LUA_INIT="error(10)" LUA_PATH=xxx LUA_CPATH=xxx lua -E %s > %s', | ||
144 | prog, out) | ||
145 | local out = getoutput() | ||
146 | defaultpath = string.match(out, "^(.-)\t") | ||
147 | defaultCpath = string.match(out, "\t(.-)$") | ||
148 | end | ||
149 | |||
150 | -- paths did not changed | ||
151 | assert(not string.find(defaultpath, "xxx") and | ||
152 | string.find(defaultpath, "lua") and | ||
153 | not string.find(defaultCpath, "xxx") and | ||
154 | string.find(defaultCpath, "lua")) | ||
155 | |||
156 | |||
157 | -- test replacement of ';;' to default path | ||
158 | local function convert (p) | ||
159 | prepfile("print(package.path)") | ||
160 | RUN('env LUA_PATH="%s" lua %s > %s', p, prog, out) | ||
161 | local expected = getoutput() | ||
162 | expected = string.sub(expected, 1, -2) -- cut final end of line | ||
163 | assert(string.gsub(p, ";;", ";"..defaultpath..";") == expected) | ||
164 | end | ||
165 | |||
166 | convert(";") | ||
167 | convert(";;") | ||
168 | convert(";;;") | ||
169 | convert(";;;;") | ||
170 | convert(";;;;;") | ||
171 | convert(";;a;;;bc") | ||
172 | |||
173 | |||
174 | -- test -l over multiple libraries | ||
175 | prepfile("print(1); a=2; return {x=15}") | ||
176 | prepfile(("print(a); print(_G['%s'].x)"):format(prog), otherprog) | ||
177 | RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out) | ||
178 | checkout("1\n2\n15\n2\n15\n") | ||
179 | |||
180 | -- test 'arg' table | ||
181 | local a = [[ | ||
182 | assert(#arg == 3 and arg[1] == 'a' and | ||
183 | arg[2] == 'b' and arg[3] == 'c') | ||
184 | assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == '%s') | ||
185 | assert(arg[4] == undef and arg[-4] == undef) | ||
186 | local a, b, c = ... | ||
187 | assert(... == 'a' and a == 'a' and b == 'b' and c == 'c') | ||
188 | ]] | ||
189 | a = string.format(a, progname) | ||
190 | prepfile(a) | ||
191 | RUN('lua "-e " -- %s a b c', prog) -- "-e " runs an empty command | ||
192 | |||
193 | -- test 'arg' availability in libraries | ||
194 | prepfile"assert(arg)" | ||
195 | prepfile("assert(arg)", otherprog) | ||
196 | RUN('env LUA_PATH="?;;" lua -l%s - < %s', prog, otherprog) | ||
197 | |||
198 | -- test messing up the 'arg' table | ||
199 | RUN('echo "print(...)" | lua -e "arg[1] = 100" - > %s', out) | ||
200 | checkout("100\n") | ||
201 | NoRun("'arg' is not a table", 'echo "" | lua -e "arg = 1" -') | ||
202 | |||
203 | -- test error in 'print' | ||
204 | RUN('echo 10 | lua -e "print=nil" -i > /dev/null 2> %s', out) | ||
205 | assert(string.find(getoutput(), "error calling 'print'")) | ||
206 | |||
207 | -- test 'debug.debug' | ||
208 | RUN('echo "io.stderr:write(1000)\ncont" | lua -e "require\'debug\'.debug()" 2> %s', out) | ||
209 | checkout("lua_debug> 1000lua_debug> ") | ||
210 | |||
211 | -- test many arguments | ||
212 | prepfile[[print(({...})[30])]] | ||
213 | RUN('lua %s %s > %s', prog, string.rep(" a", 30), out) | ||
214 | checkout("a\n") | ||
215 | |||
216 | RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out) | ||
217 | checkout("1\n3\n") | ||
218 | |||
219 | -- test iteractive mode | ||
220 | prepfile[[ | ||
221 | (6*2-6) -- === | ||
222 | a = | ||
223 | 10 | ||
224 | print(a) | ||
225 | a]] | ||
226 | RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out) | ||
227 | checkprogout("6\n10\n10\n\n") | ||
228 | |||
229 | prepfile("a = [[b\nc\nd\ne]]\n=a") | ||
230 | RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out) | ||
231 | checkprogout("b\nc\nd\ne\n\n") | ||
232 | |||
233 | prompt = "alo" | ||
234 | prepfile[[ -- | ||
235 | a = 2 | ||
236 | ]] | ||
237 | RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out) | ||
238 | local t = getoutput() | ||
239 | assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt)) | ||
240 | |||
241 | -- test for error objects | ||
242 | prepfile[[ | ||
243 | debug = require "debug" | ||
244 | m = {x=0} | ||
245 | setmetatable(m, {__tostring = function(x) | ||
246 | return tostring(debug.getinfo(4).currentline + x.x) | ||
247 | end}) | ||
248 | error(m) | ||
249 | ]] | ||
250 | NoRun(progname .. ": 6\n", [[lua %s]], prog) | ||
251 | |||
252 | prepfile("error{}") | ||
253 | NoRun("error object is a table value", [[lua %s]], prog) | ||
254 | |||
255 | |||
256 | -- chunk broken in many lines | ||
257 | s = [=[ -- | ||
258 | function f ( x ) | ||
259 | local a = [[ | ||
260 | xuxu | ||
261 | ]] | ||
262 | local b = "\ | ||
263 | xuxu\n" | ||
264 | if x == 11 then return 1 + 12 , 2 + 20 end --[[ test multiple returns ]] | ||
265 | return x + 1 | ||
266 | --\\ | ||
267 | end | ||
268 | return( f( 100 ) ) | ||
269 | assert( a == b ) | ||
270 | do return f( 11 ) end ]=] | ||
271 | s = string.gsub(s, ' ', '\n\n') -- change all spaces for newlines | ||
272 | prepfile(s) | ||
273 | RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out) | ||
274 | checkprogout("101\n13\t22\n\n") | ||
275 | |||
276 | prepfile[[#comment in 1st line without \n at the end]] | ||
277 | RUN('lua %s', prog) | ||
278 | |||
279 | prepfile[[#test line number when file starts with comment line | ||
280 | debug = require"debug" | ||
281 | print(debug.getinfo(1).currentline) | ||
282 | ]] | ||
283 | RUN('lua %s > %s', prog, out) | ||
284 | checkprogout('3') | ||
285 | |||
286 | -- close Lua with an open file | ||
287 | prepfile(string.format([[io.output(%q); io.write('alo')]], out)) | ||
288 | RUN('lua %s', prog) | ||
289 | checkout('alo') | ||
290 | |||
291 | -- bug in 5.2 beta (extra \0 after version line) | ||
292 | RUN([[lua -v -e"print'hello'" > %s]], out) | ||
293 | t = getoutput() | ||
294 | assert(string.find(t, "PUC%-Rio\nhello")) | ||
295 | |||
296 | |||
297 | -- testing os.exit | ||
298 | prepfile("os.exit(nil, true)") | ||
299 | RUN('lua %s', prog) | ||
300 | prepfile("os.exit(0, true)") | ||
301 | RUN('lua %s', prog) | ||
302 | prepfile("os.exit(true, true)") | ||
303 | RUN('lua %s', prog) | ||
304 | prepfile("os.exit(1, true)") | ||
305 | NoRun("", "lua %s", prog) -- no message | ||
306 | prepfile("os.exit(false, true)") | ||
307 | NoRun("", "lua %s", prog) -- no message | ||
308 | |||
309 | -- remove temporary files | ||
310 | assert(os.remove(prog)) | ||
311 | assert(os.remove(otherprog)) | ||
312 | assert(not os.remove(out)) | ||
313 | |||
314 | -- invalid options | ||
315 | NoRun("unrecognized option '-h'", "lua -h") | ||
316 | NoRun("unrecognized option '---'", "lua ---") | ||
317 | NoRun("unrecognized option '-Ex'", "lua -Ex") | ||
318 | NoRun("unrecognized option '-vv'", "lua -vv") | ||
319 | NoRun("unrecognized option '-iv'", "lua -iv") | ||
320 | NoRun("'-e' needs argument", "lua -e") | ||
321 | NoRun("syntax error", "lua -e a") | ||
322 | NoRun("'-l' needs argument", "lua -l") | ||
323 | |||
324 | |||
325 | if T then -- auxiliary library? | ||
326 | print("testing 'not enough memory' to create a state") | ||
327 | NoRun("not enough memory", "env MEMLIMIT=100 lua") | ||
328 | end | ||
329 | print('+') | ||
330 | |||
331 | print('testing Ctrl C') | ||
332 | do | ||
333 | -- interrupt a script | ||
334 | local function kill (pid) | ||
335 | return os.execute(string.format('kill -INT %s 2> /dev/null', pid)) | ||
336 | end | ||
337 | |||
338 | -- function to run a script in background, returning its output file | ||
339 | -- descriptor and its pid | ||
340 | local function runback (luaprg) | ||
341 | -- shell script to run 'luaprg' in background and echo its pid | ||
342 | local shellprg = string.format('%s -e "%s" & echo $!', progname, luaprg) | ||
343 | local f = io.popen(shellprg, "r") -- run shell script | ||
344 | local pid = f:read() -- get pid for Lua script | ||
345 | print("(if test fails now, it may leave a Lua script running in \z | ||
346 | background, pid " .. pid .. ")") | ||
347 | return f, pid | ||
348 | end | ||
349 | |||
350 | -- Lua script that runs protected infinite loop and then prints '42' | ||
351 | local f, pid = runback[[ | ||
352 | pcall(function () print(12); while true do end end); print(42)]] | ||
353 | -- wait until script is inside 'pcall' | ||
354 | assert(f:read() == "12") | ||
355 | kill(pid) -- send INT signal to Lua script | ||
356 | -- check that 'pcall' captured the exception and script continued running | ||
357 | assert(f:read() == "42") -- expected output | ||
358 | assert(f:close()) | ||
359 | print("done") | ||
360 | |||
361 | -- Lua script in a long unbreakable search | ||
362 | local f, pid = runback[[ | ||
363 | print(15); string.find(string.rep('a', 100000), '.*b')]] | ||
364 | -- wait (so script can reach the loop) | ||
365 | assert(f:read() == "15") | ||
366 | assert(os.execute("sleep 1")) | ||
367 | -- must send at least two INT signals to stop this Lua script | ||
368 | local n = 100 | ||
369 | for i = 0, 100 do -- keep sending signals | ||
370 | if not kill(pid) then -- until it fails | ||
371 | n = i -- number of non-failed kills | ||
372 | break | ||
373 | end | ||
374 | end | ||
375 | assert(f:close()) | ||
376 | assert(n >= 2) | ||
377 | print(string.format("done (with %d kills)", n)) | ||
378 | |||
379 | end | ||
380 | |||
381 | print("OK") | ||
diff --git a/testes/math.lua b/testes/math.lua new file mode 100644 index 00000000..66998460 --- /dev/null +++ b/testes/math.lua | |||
@@ -0,0 +1,931 @@ | |||
1 | -- $Id: math.lua,v 1.86 2018/05/09 14:55:52 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print("testing numbers and math lib") | ||
5 | |||
6 | local minint = math.mininteger | ||
7 | local maxint = math.maxinteger | ||
8 | |||
9 | local intbits = math.floor(math.log(maxint, 2) + 0.5) + 1 | ||
10 | assert((1 << intbits) == 0) | ||
11 | |||
12 | assert(minint == 1 << (intbits - 1)) | ||
13 | assert(maxint == minint - 1) | ||
14 | |||
15 | -- number of bits in the mantissa of a floating-point number | ||
16 | local floatbits = 24 | ||
17 | do | ||
18 | local p = 2.0^floatbits | ||
19 | while p < p + 1.0 do | ||
20 | p = p * 2.0 | ||
21 | floatbits = floatbits + 1 | ||
22 | end | ||
23 | end | ||
24 | |||
25 | local function isNaN (x) | ||
26 | return (x ~= x) | ||
27 | end | ||
28 | |||
29 | assert(isNaN(0/0)) | ||
30 | assert(not isNaN(1/0)) | ||
31 | |||
32 | |||
33 | do | ||
34 | local x = 2.0^floatbits | ||
35 | assert(x > x - 1.0 and x == x + 1.0) | ||
36 | |||
37 | print(string.format("%d-bit integers, %d-bit (mantissa) floats", | ||
38 | intbits, floatbits)) | ||
39 | end | ||
40 | |||
41 | assert(math.type(0) == "integer" and math.type(0.0) == "float" | ||
42 | and math.type("10") == nil) | ||
43 | |||
44 | |||
45 | local function checkerror (msg, f, ...) | ||
46 | local s, err = pcall(f, ...) | ||
47 | assert(not s and string.find(err, msg)) | ||
48 | end | ||
49 | |||
50 | local msgf2i = "number.* has no integer representation" | ||
51 | |||
52 | -- float equality | ||
53 | function eq (a,b,limit) | ||
54 | if not limit then | ||
55 | if floatbits >= 50 then limit = 1E-11 | ||
56 | else limit = 1E-5 | ||
57 | end | ||
58 | end | ||
59 | -- a == b needed for +inf/-inf | ||
60 | return a == b or math.abs(a-b) <= limit | ||
61 | end | ||
62 | |||
63 | |||
64 | -- equality with types | ||
65 | function eqT (a,b) | ||
66 | return a == b and math.type(a) == math.type(b) | ||
67 | end | ||
68 | |||
69 | |||
70 | -- basic float notation | ||
71 | assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2) | ||
72 | |||
73 | do | ||
74 | local a,b,c = "2", " 3e0 ", " 10 " | ||
75 | assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0) | ||
76 | assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string') | ||
77 | assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ") | ||
78 | assert(c%a == 0 and a^b == 08) | ||
79 | a = 0 | ||
80 | assert(a == -a and 0 == -0) | ||
81 | end | ||
82 | |||
83 | do | ||
84 | local x = -1 | ||
85 | local mz = 0/x -- minus zero | ||
86 | t = {[0] = 10, 20, 30, 40, 50} | ||
87 | assert(t[mz] == t[0] and t[-0] == t[0]) | ||
88 | end | ||
89 | |||
90 | do -- tests for 'modf' | ||
91 | local a,b = math.modf(3.5) | ||
92 | assert(a == 3.0 and b == 0.5) | ||
93 | a,b = math.modf(-2.5) | ||
94 | assert(a == -2.0 and b == -0.5) | ||
95 | a,b = math.modf(-3e23) | ||
96 | assert(a == -3e23 and b == 0.0) | ||
97 | a,b = math.modf(3e35) | ||
98 | assert(a == 3e35 and b == 0.0) | ||
99 | a,b = math.modf(-1/0) -- -inf | ||
100 | assert(a == -1/0 and b == 0.0) | ||
101 | a,b = math.modf(1/0) -- inf | ||
102 | assert(a == 1/0 and b == 0.0) | ||
103 | a,b = math.modf(0/0) -- NaN | ||
104 | assert(isNaN(a) and isNaN(b)) | ||
105 | a,b = math.modf(3) -- integer argument | ||
106 | assert(eqT(a, 3) and eqT(b, 0.0)) | ||
107 | a,b = math.modf(minint) | ||
108 | assert(eqT(a, minint) and eqT(b, 0.0)) | ||
109 | end | ||
110 | |||
111 | assert(math.huge > 10e30) | ||
112 | assert(-math.huge < -10e30) | ||
113 | |||
114 | |||
115 | -- integer arithmetic | ||
116 | assert(minint < minint + 1) | ||
117 | assert(maxint - 1 < maxint) | ||
118 | assert(0 - minint == minint) | ||
119 | assert(minint * minint == 0) | ||
120 | assert(maxint * maxint * maxint == maxint) | ||
121 | |||
122 | |||
123 | -- testing floor division and conversions | ||
124 | |||
125 | for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do | ||
126 | for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do | ||
127 | for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float | ||
128 | for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float | ||
129 | local x = i + ti | ||
130 | local y = j + tj | ||
131 | assert(i//j == math.floor(i/j)) | ||
132 | end | ||
133 | end | ||
134 | end | ||
135 | end | ||
136 | |||
137 | assert(1//0.0 == 1/0) | ||
138 | assert(-1 // 0.0 == -1/0) | ||
139 | assert(eqT(3.5 // 1.5, 2.0)) | ||
140 | assert(eqT(3.5 // -1.5, -3.0)) | ||
141 | |||
142 | assert(maxint // maxint == 1) | ||
143 | assert(maxint // 1 == maxint) | ||
144 | assert((maxint - 1) // maxint == 0) | ||
145 | assert(maxint // (maxint - 1) == 1) | ||
146 | assert(minint // minint == 1) | ||
147 | assert(minint // minint == 1) | ||
148 | assert((minint + 1) // minint == 0) | ||
149 | assert(minint // (minint + 1) == 1) | ||
150 | assert(minint // 1 == minint) | ||
151 | |||
152 | assert(minint // -1 == -minint) | ||
153 | assert(minint // -2 == 2^(intbits - 2)) | ||
154 | assert(maxint // -1 == -maxint) | ||
155 | |||
156 | |||
157 | -- negative exponents | ||
158 | do | ||
159 | assert(2^-3 == 1 / 2^3) | ||
160 | assert(eq((-3)^-3, 1 / (-3)^3)) | ||
161 | for i = -3, 3 do -- variables avoid constant folding | ||
162 | for j = -3, 3 do | ||
163 | -- domain errors (0^(-n)) are not portable | ||
164 | if not _port or i ~= 0 or j > 0 then | ||
165 | assert(eq(i^j, 1 / i^(-j))) | ||
166 | end | ||
167 | end | ||
168 | end | ||
169 | end | ||
170 | |||
171 | -- comparison between floats and integers (border cases) | ||
172 | if floatbits < intbits then | ||
173 | assert(2.0^floatbits == (1 << floatbits)) | ||
174 | assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0) | ||
175 | assert(2.0^floatbits - 1.0 ~= (1 << floatbits)) | ||
176 | -- float is rounded, int is not | ||
177 | assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1) | ||
178 | else -- floats can express all integers with full accuracy | ||
179 | assert(maxint == maxint + 0.0) | ||
180 | assert(maxint - 1 == maxint - 1.0) | ||
181 | assert(minint + 1 == minint + 1.0) | ||
182 | assert(maxint ~= maxint - 1.0) | ||
183 | end | ||
184 | assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0) | ||
185 | assert(minint + 0.0 == minint) | ||
186 | assert(minint + 0.0 == -2.0^(intbits - 1)) | ||
187 | |||
188 | |||
189 | -- order between floats and integers | ||
190 | assert(1 < 1.1); assert(not (1 < 0.9)) | ||
191 | assert(1 <= 1.1); assert(not (1 <= 0.9)) | ||
192 | assert(-1 < -0.9); assert(not (-1 < -1.1)) | ||
193 | assert(1 <= 1.1); assert(not (-1 <= -1.1)) | ||
194 | assert(-1 < -0.9); assert(not (-1 < -1.1)) | ||
195 | assert(-1 <= -0.9); assert(not (-1 <= -1.1)) | ||
196 | assert(minint <= minint + 0.0) | ||
197 | assert(minint + 0.0 <= minint) | ||
198 | assert(not (minint < minint + 0.0)) | ||
199 | assert(not (minint + 0.0 < minint)) | ||
200 | assert(maxint < minint * -1.0) | ||
201 | assert(maxint <= minint * -1.0) | ||
202 | |||
203 | do | ||
204 | local fmaxi1 = 2^(intbits - 1) | ||
205 | assert(maxint < fmaxi1) | ||
206 | assert(maxint <= fmaxi1) | ||
207 | assert(not (fmaxi1 <= maxint)) | ||
208 | assert(minint <= -2^(intbits - 1)) | ||
209 | assert(-2^(intbits - 1) <= minint) | ||
210 | end | ||
211 | |||
212 | if floatbits < intbits then | ||
213 | print("testing order (floats cannot represent all integers)") | ||
214 | local fmax = 2^floatbits | ||
215 | local ifmax = fmax | 0 | ||
216 | assert(fmax < ifmax + 1) | ||
217 | assert(fmax - 1 < ifmax) | ||
218 | assert(-(fmax - 1) > -ifmax) | ||
219 | assert(not (fmax <= ifmax - 1)) | ||
220 | assert(-fmax > -(ifmax + 1)) | ||
221 | assert(not (-fmax >= -(ifmax - 1))) | ||
222 | |||
223 | assert(fmax/2 - 0.5 < ifmax//2) | ||
224 | assert(-(fmax/2 - 0.5) > -ifmax//2) | ||
225 | |||
226 | assert(maxint < 2^intbits) | ||
227 | assert(minint > -2^intbits) | ||
228 | assert(maxint <= 2^intbits) | ||
229 | assert(minint >= -2^intbits) | ||
230 | else | ||
231 | print("testing order (floats can represent all integers)") | ||
232 | assert(maxint < maxint + 1.0) | ||
233 | assert(maxint < maxint + 0.5) | ||
234 | assert(maxint - 1.0 < maxint) | ||
235 | assert(maxint - 0.5 < maxint) | ||
236 | assert(not (maxint + 0.0 < maxint)) | ||
237 | assert(maxint + 0.0 <= maxint) | ||
238 | assert(not (maxint < maxint + 0.0)) | ||
239 | assert(maxint + 0.0 <= maxint) | ||
240 | assert(maxint <= maxint + 0.0) | ||
241 | assert(not (maxint + 1.0 <= maxint)) | ||
242 | assert(not (maxint + 0.5 <= maxint)) | ||
243 | assert(not (maxint <= maxint - 1.0)) | ||
244 | assert(not (maxint <= maxint - 0.5)) | ||
245 | |||
246 | assert(minint < minint + 1.0) | ||
247 | assert(minint < minint + 0.5) | ||
248 | assert(minint <= minint + 0.5) | ||
249 | assert(minint - 1.0 < minint) | ||
250 | assert(minint - 1.0 <= minint) | ||
251 | assert(not (minint + 0.0 < minint)) | ||
252 | assert(not (minint + 0.5 < minint)) | ||
253 | assert(not (minint < minint + 0.0)) | ||
254 | assert(minint + 0.0 <= minint) | ||
255 | assert(minint <= minint + 0.0) | ||
256 | assert(not (minint + 1.0 <= minint)) | ||
257 | assert(not (minint + 0.5 <= minint)) | ||
258 | assert(not (minint <= minint - 1.0)) | ||
259 | end | ||
260 | |||
261 | do | ||
262 | local NaN = 0/0 | ||
263 | assert(not (NaN < 0)) | ||
264 | assert(not (NaN > minint)) | ||
265 | assert(not (NaN <= -9)) | ||
266 | assert(not (NaN <= maxint)) | ||
267 | assert(not (NaN < maxint)) | ||
268 | assert(not (minint <= NaN)) | ||
269 | assert(not (minint < NaN)) | ||
270 | assert(not (4 <= NaN)) | ||
271 | assert(not (4 < NaN)) | ||
272 | end | ||
273 | |||
274 | |||
275 | -- avoiding errors at compile time | ||
276 | local function checkcompt (msg, code) | ||
277 | checkerror(msg, assert(load(code))) | ||
278 | end | ||
279 | checkcompt("divide by zero", "return 2 // 0") | ||
280 | checkcompt(msgf2i, "return 2.3 >> 0") | ||
281 | checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1)) | ||
282 | checkcompt("field 'huge'", "return math.huge << 1") | ||
283 | checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1)) | ||
284 | checkcompt(msgf2i, "return 2.3 ~ 0.0") | ||
285 | |||
286 | |||
287 | -- testing overflow errors when converting from float to integer (runtime) | ||
288 | local function f2i (x) return x | x end | ||
289 | checkerror(msgf2i, f2i, math.huge) -- +inf | ||
290 | checkerror(msgf2i, f2i, -math.huge) -- -inf | ||
291 | checkerror(msgf2i, f2i, 0/0) -- NaN | ||
292 | |||
293 | if floatbits < intbits then | ||
294 | -- conversion tests when float cannot represent all integers | ||
295 | assert(maxint + 1.0 == maxint + 0.0) | ||
296 | assert(minint - 1.0 == minint + 0.0) | ||
297 | checkerror(msgf2i, f2i, maxint + 0.0) | ||
298 | assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2)) | ||
299 | assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2))) | ||
300 | assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1) | ||
301 | -- maximum integer representable as a float | ||
302 | local mf = maxint - (1 << (floatbits - intbits)) + 1 | ||
303 | assert(f2i(mf + 0.0) == mf) -- OK up to here | ||
304 | mf = mf + 1 | ||
305 | assert(f2i(mf + 0.0) ~= mf) -- no more representable | ||
306 | else | ||
307 | -- conversion tests when float can represent all integers | ||
308 | assert(maxint + 1.0 > maxint) | ||
309 | assert(minint - 1.0 < minint) | ||
310 | assert(f2i(maxint + 0.0) == maxint) | ||
311 | checkerror("no integer rep", f2i, maxint + 1.0) | ||
312 | checkerror("no integer rep", f2i, minint - 1.0) | ||
313 | end | ||
314 | |||
315 | -- 'minint' should be representable as a float no matter the precision | ||
316 | assert(f2i(minint + 0.0) == minint) | ||
317 | |||
318 | |||
319 | -- testing numeric strings | ||
320 | |||
321 | assert("2" + 1 == 3) | ||
322 | assert("2 " + 1 == 3) | ||
323 | assert(" -2 " + 1 == -1) | ||
324 | assert(" -0xa " + 1 == -9) | ||
325 | |||
326 | |||
327 | -- Literal integer Overflows (new behavior in 5.3.3) | ||
328 | do | ||
329 | -- no overflows | ||
330 | assert(eqT(tonumber(tostring(maxint)), maxint)) | ||
331 | assert(eqT(tonumber(tostring(minint)), minint)) | ||
332 | |||
333 | -- add 1 to last digit as a string (it cannot be 9...) | ||
334 | local function incd (n) | ||
335 | local s = string.format("%d", n) | ||
336 | s = string.gsub(s, "%d$", function (d) | ||
337 | assert(d ~= '9') | ||
338 | return string.char(string.byte(d) + 1) | ||
339 | end) | ||
340 | return s | ||
341 | end | ||
342 | |||
343 | -- 'tonumber' with overflow by 1 | ||
344 | assert(eqT(tonumber(incd(maxint)), maxint + 1.0)) | ||
345 | assert(eqT(tonumber(incd(minint)), minint - 1.0)) | ||
346 | |||
347 | -- large numbers | ||
348 | assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30)) | ||
349 | assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30)) | ||
350 | |||
351 | -- hexa format still wraps around | ||
352 | assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0)) | ||
353 | |||
354 | -- lexer in the limits | ||
355 | assert(minint == load("return " .. minint)()) | ||
356 | assert(eqT(maxint, load("return " .. maxint)())) | ||
357 | |||
358 | assert(eqT(10000000000000000000000.0, 10000000000000000000000)) | ||
359 | assert(eqT(-10000000000000000000000.0, -10000000000000000000000)) | ||
360 | end | ||
361 | |||
362 | |||
363 | -- testing 'tonumber' | ||
364 | |||
365 | -- 'tonumber' with numbers | ||
366 | assert(tonumber(3.4) == 3.4) | ||
367 | assert(eqT(tonumber(3), 3)) | ||
368 | assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint)) | ||
369 | assert(tonumber(1/0) == 1/0) | ||
370 | |||
371 | -- 'tonumber' with strings | ||
372 | assert(tonumber("0") == 0) | ||
373 | assert(tonumber("") == nil) | ||
374 | assert(tonumber(" ") == nil) | ||
375 | assert(tonumber("-") == nil) | ||
376 | assert(tonumber(" -0x ") == nil) | ||
377 | assert(tonumber{} == nil) | ||
378 | assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and | ||
379 | tonumber'.01' == 0.01 and tonumber'-1.' == -1 and | ||
380 | tonumber'+1.' == 1) | ||
381 | assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and | ||
382 | tonumber'1e' == nil and tonumber'1.0e+' == nil and | ||
383 | tonumber'.' == nil) | ||
384 | assert(tonumber('-012') == -010-2) | ||
385 | assert(tonumber('-1.2e2') == - - -120) | ||
386 | |||
387 | assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1) | ||
388 | assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1) | ||
389 | assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1) | ||
390 | |||
391 | -- testing 'tonumber' with base | ||
392 | assert(tonumber(' 001010 ', 2) == 10) | ||
393 | assert(tonumber(' 001010 ', 10) == 001010) | ||
394 | assert(tonumber(' -1010 ', 2) == -10) | ||
395 | assert(tonumber('10', 36) == 36) | ||
396 | assert(tonumber(' -10 ', 36) == -36) | ||
397 | assert(tonumber(' +1Z ', 36) == 36 + 35) | ||
398 | assert(tonumber(' -1z ', 36) == -36 + -35) | ||
399 | assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15))))))) | ||
400 | assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2)) | ||
401 | assert(tonumber('ffffFFFF', 16)+1 == (1 << 32)) | ||
402 | assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32)) | ||
403 | assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40)) | ||
404 | for i = 2,36 do | ||
405 | local i2 = i * i | ||
406 | local i10 = i2 * i2 * i2 * i2 * i2 -- i^10 | ||
407 | assert(tonumber('\t10000000000\t', i) == i10) | ||
408 | end | ||
409 | |||
410 | if not _soft then | ||
411 | -- tests with very long numerals | ||
412 | assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1) | ||
413 | assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1) | ||
414 | assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1) | ||
415 | assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1) | ||
416 | assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3) | ||
417 | assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10) | ||
418 | assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14)) | ||
419 | assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151)) | ||
420 | assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301)) | ||
421 | assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501)) | ||
422 | |||
423 | assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0) | ||
424 | assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4) | ||
425 | end | ||
426 | |||
427 | -- testing 'tonumber' for invalid formats | ||
428 | |||
429 | local function f (...) | ||
430 | if select('#', ...) == 1 then | ||
431 | return (...) | ||
432 | else | ||
433 | return "***" | ||
434 | end | ||
435 | end | ||
436 | |||
437 | assert(f(tonumber('fFfa', 15)) == nil) | ||
438 | assert(f(tonumber('099', 8)) == nil) | ||
439 | assert(f(tonumber('1\0', 2)) == nil) | ||
440 | assert(f(tonumber('', 8)) == nil) | ||
441 | assert(f(tonumber(' ', 9)) == nil) | ||
442 | assert(f(tonumber(' ', 9)) == nil) | ||
443 | assert(f(tonumber('0xf', 10)) == nil) | ||
444 | |||
445 | assert(f(tonumber('inf')) == nil) | ||
446 | assert(f(tonumber(' INF ')) == nil) | ||
447 | assert(f(tonumber('Nan')) == nil) | ||
448 | assert(f(tonumber('nan')) == nil) | ||
449 | |||
450 | assert(f(tonumber(' ')) == nil) | ||
451 | assert(f(tonumber('')) == nil) | ||
452 | assert(f(tonumber('1 a')) == nil) | ||
453 | assert(f(tonumber('1 a', 2)) == nil) | ||
454 | assert(f(tonumber('1\0')) == nil) | ||
455 | assert(f(tonumber('1 \0')) == nil) | ||
456 | assert(f(tonumber('1\0 ')) == nil) | ||
457 | assert(f(tonumber('e1')) == nil) | ||
458 | assert(f(tonumber('e 1')) == nil) | ||
459 | assert(f(tonumber(' 3.4.5 ')) == nil) | ||
460 | |||
461 | |||
462 | -- testing 'tonumber' for invalid hexadecimal formats | ||
463 | |||
464 | assert(tonumber('0x') == nil) | ||
465 | assert(tonumber('x') == nil) | ||
466 | assert(tonumber('x3') == nil) | ||
467 | assert(tonumber('0x3.3.3') == nil) -- two decimal points | ||
468 | assert(tonumber('00x2') == nil) | ||
469 | assert(tonumber('0x 2') == nil) | ||
470 | assert(tonumber('0 x2') == nil) | ||
471 | assert(tonumber('23x') == nil) | ||
472 | assert(tonumber('- 0xaa') == nil) | ||
473 | assert(tonumber('-0xaaP ') == nil) -- no exponent | ||
474 | assert(tonumber('0x0.51p') == nil) | ||
475 | assert(tonumber('0x5p+-2') == nil) | ||
476 | |||
477 | |||
478 | -- testing hexadecimal numerals | ||
479 | |||
480 | assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251) | ||
481 | assert(0x0p12 == 0 and 0x.0p-3 == 0) | ||
482 | assert(0xFFFFFFFF == (1 << 32) - 1) | ||
483 | assert(tonumber('+0x2') == 2) | ||
484 | assert(tonumber('-0xaA') == -170) | ||
485 | assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1) | ||
486 | |||
487 | -- possible confusion with decimal exponent | ||
488 | assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13) | ||
489 | |||
490 | |||
491 | -- floating hexas | ||
492 | |||
493 | assert(tonumber(' 0x2.5 ') == 0x25/16) | ||
494 | assert(tonumber(' -0x2.5 ') == -0x25/16) | ||
495 | assert(tonumber(' +0x0.51p+8 ') == 0x51) | ||
496 | assert(0x.FfffFFFF == 1 - '0x.00000001') | ||
497 | assert('0xA.a' + 0 == 10 + 10/16) | ||
498 | assert(0xa.aP4 == 0XAA) | ||
499 | assert(0x4P-2 == 1) | ||
500 | assert(0x1.1 == '0x1.' + '+0x.1') | ||
501 | assert(0Xabcdef.0 == 0x.ABCDEFp+24) | ||
502 | |||
503 | |||
504 | assert(1.1 == 1.+.1) | ||
505 | assert(100.0 == 1E2 and .01 == 1e-2) | ||
506 | assert(1111111111 - 1111111110 == 1000.00e-03) | ||
507 | assert(1.1 == '1.'+'.1') | ||
508 | assert(tonumber'1111111111' - tonumber'1111111110' == | ||
509 | tonumber" +0.001e+3 \n\t") | ||
510 | |||
511 | assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31) | ||
512 | |||
513 | assert(0.123456 > 0.123455) | ||
514 | |||
515 | assert(tonumber('+1.23E18') == 1.23*10.0^18) | ||
516 | |||
517 | -- testing order operators | ||
518 | assert(not(1<1) and (1<2) and not(2<1)) | ||
519 | assert(not('a'<'a') and ('a'<'b') and not('b'<'a')) | ||
520 | assert((1<=1) and (1<=2) and not(2<=1)) | ||
521 | assert(('a'<='a') and ('a'<='b') and not('b'<='a')) | ||
522 | assert(not(1>1) and not(1>2) and (2>1)) | ||
523 | assert(not('a'>'a') and not('a'>'b') and ('b'>'a')) | ||
524 | assert((1>=1) and not(1>=2) and (2>=1)) | ||
525 | assert(('a'>='a') and not('a'>='b') and ('b'>='a')) | ||
526 | assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3) | ||
527 | |||
528 | -- testing mod operator | ||
529 | assert(eqT(-4 % 3, 2)) | ||
530 | assert(eqT(4 % -3, -2)) | ||
531 | assert(eqT(-4.0 % 3, 2.0)) | ||
532 | assert(eqT(4 % -3.0, -2.0)) | ||
533 | assert(math.pi - math.pi % 1 == 3) | ||
534 | assert(math.pi - math.pi % 0.001 == 3.141) | ||
535 | |||
536 | assert(eqT(minint % minint, 0)) | ||
537 | assert(eqT(maxint % maxint, 0)) | ||
538 | assert((minint + 1) % minint == minint + 1) | ||
539 | assert((maxint - 1) % maxint == maxint - 1) | ||
540 | assert(minint % maxint == maxint - 1) | ||
541 | |||
542 | assert(minint % -1 == 0) | ||
543 | assert(minint % -2 == 0) | ||
544 | assert(maxint % -2 == -1) | ||
545 | |||
546 | -- non-portable tests because Windows C library cannot compute | ||
547 | -- fmod(1, huge) correctly | ||
548 | if not _port then | ||
549 | local function anan (x) assert(isNaN(x)) end -- assert Not a Number | ||
550 | anan(0.0 % 0) | ||
551 | anan(1.3 % 0) | ||
552 | anan(math.huge % 1) | ||
553 | anan(math.huge % 1e30) | ||
554 | anan(-math.huge % 1e30) | ||
555 | anan(-math.huge % -1e30) | ||
556 | assert(1 % math.huge == 1) | ||
557 | assert(1e30 % math.huge == 1e30) | ||
558 | assert(1e30 % -math.huge == -math.huge) | ||
559 | assert(-1 % math.huge == math.huge) | ||
560 | assert(-1 % -math.huge == -1) | ||
561 | end | ||
562 | |||
563 | |||
564 | -- testing unsigned comparisons | ||
565 | assert(math.ult(3, 4)) | ||
566 | assert(not math.ult(4, 4)) | ||
567 | assert(math.ult(-2, -1)) | ||
568 | assert(math.ult(2, -1)) | ||
569 | assert(not math.ult(-2, -2)) | ||
570 | assert(math.ult(maxint, minint)) | ||
571 | assert(not math.ult(minint, maxint)) | ||
572 | |||
573 | |||
574 | assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1)) | ||
575 | assert(eq(math.tan(math.pi/4), 1)) | ||
576 | assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0)) | ||
577 | assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and | ||
578 | eq(math.asin(1), math.pi/2)) | ||
579 | assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2)) | ||
580 | assert(math.abs(-10.43) == 10.43) | ||
581 | assert(eqT(math.abs(minint), minint)) | ||
582 | assert(eqT(math.abs(maxint), maxint)) | ||
583 | assert(eqT(math.abs(-maxint), maxint)) | ||
584 | assert(eq(math.atan(1,0), math.pi/2)) | ||
585 | assert(math.fmod(10,3) == 1) | ||
586 | assert(eq(math.sqrt(10)^2, 10)) | ||
587 | assert(eq(math.log(2, 10), math.log(2)/math.log(10))) | ||
588 | assert(eq(math.log(2, 2), 1)) | ||
589 | assert(eq(math.log(9, 3), 2)) | ||
590 | assert(eq(math.exp(0), 1)) | ||
591 | assert(eq(math.sin(10), math.sin(10%(2*math.pi)))) | ||
592 | |||
593 | |||
594 | assert(tonumber(' 1.3e-2 ') == 1.3e-2) | ||
595 | assert(tonumber(' -1.00000000000001 ') == -1.00000000000001) | ||
596 | |||
597 | -- testing constant limits | ||
598 | -- 2^23 = 8388608 | ||
599 | assert(8388609 + -8388609 == 0) | ||
600 | assert(8388608 + -8388608 == 0) | ||
601 | assert(8388607 + -8388607 == 0) | ||
602 | |||
603 | |||
604 | |||
605 | do -- testing floor & ceil | ||
606 | assert(eqT(math.floor(3.4), 3)) | ||
607 | assert(eqT(math.ceil(3.4), 4)) | ||
608 | assert(eqT(math.floor(-3.4), -4)) | ||
609 | assert(eqT(math.ceil(-3.4), -3)) | ||
610 | assert(eqT(math.floor(maxint), maxint)) | ||
611 | assert(eqT(math.ceil(maxint), maxint)) | ||
612 | assert(eqT(math.floor(minint), minint)) | ||
613 | assert(eqT(math.floor(minint + 0.0), minint)) | ||
614 | assert(eqT(math.ceil(minint), minint)) | ||
615 | assert(eqT(math.ceil(minint + 0.0), minint)) | ||
616 | assert(math.floor(1e50) == 1e50) | ||
617 | assert(math.ceil(1e50) == 1e50) | ||
618 | assert(math.floor(-1e50) == -1e50) | ||
619 | assert(math.ceil(-1e50) == -1e50) | ||
620 | for _, p in pairs{31,32,63,64} do | ||
621 | assert(math.floor(2^p) == 2^p) | ||
622 | assert(math.floor(2^p + 0.5) == 2^p) | ||
623 | assert(math.ceil(2^p) == 2^p) | ||
624 | assert(math.ceil(2^p - 0.5) == 2^p) | ||
625 | end | ||
626 | checkerror("number expected", math.floor, {}) | ||
627 | checkerror("number expected", math.ceil, print) | ||
628 | assert(eqT(math.tointeger(minint), minint)) | ||
629 | assert(eqT(math.tointeger(minint .. ""), minint)) | ||
630 | assert(eqT(math.tointeger(maxint), maxint)) | ||
631 | assert(eqT(math.tointeger(maxint .. ""), maxint)) | ||
632 | assert(eqT(math.tointeger(minint + 0.0), minint)) | ||
633 | assert(math.tointeger(0.0 - minint) == nil) | ||
634 | assert(math.tointeger(math.pi) == nil) | ||
635 | assert(math.tointeger(-math.pi) == nil) | ||
636 | assert(math.floor(math.huge) == math.huge) | ||
637 | assert(math.ceil(math.huge) == math.huge) | ||
638 | assert(math.tointeger(math.huge) == nil) | ||
639 | assert(math.floor(-math.huge) == -math.huge) | ||
640 | assert(math.ceil(-math.huge) == -math.huge) | ||
641 | assert(math.tointeger(-math.huge) == nil) | ||
642 | assert(math.tointeger("34.0") == 34) | ||
643 | assert(math.tointeger("34.3") == nil) | ||
644 | assert(math.tointeger({}) == nil) | ||
645 | assert(math.tointeger(0/0) == nil) -- NaN | ||
646 | end | ||
647 | |||
648 | |||
649 | -- testing fmod for integers | ||
650 | for i = -6, 6 do | ||
651 | for j = -6, 6 do | ||
652 | if j ~= 0 then | ||
653 | local mi = math.fmod(i, j) | ||
654 | local mf = math.fmod(i + 0.0, j) | ||
655 | assert(mi == mf) | ||
656 | assert(math.type(mi) == 'integer' and math.type(mf) == 'float') | ||
657 | if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then | ||
658 | assert(eqT(mi, i % j)) | ||
659 | end | ||
660 | end | ||
661 | end | ||
662 | end | ||
663 | assert(eqT(math.fmod(minint, minint), 0)) | ||
664 | assert(eqT(math.fmod(maxint, maxint), 0)) | ||
665 | assert(eqT(math.fmod(minint + 1, minint), minint + 1)) | ||
666 | assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1)) | ||
667 | |||
668 | checkerror("zero", math.fmod, 3, 0) | ||
669 | |||
670 | |||
671 | do -- testing max/min | ||
672 | checkerror("value expected", math.max) | ||
673 | checkerror("value expected", math.min) | ||
674 | assert(eqT(math.max(3), 3)) | ||
675 | assert(eqT(math.max(3, 5, 9, 1), 9)) | ||
676 | assert(math.max(maxint, 10e60) == 10e60) | ||
677 | assert(eqT(math.max(minint, minint + 1), minint + 1)) | ||
678 | assert(eqT(math.min(3), 3)) | ||
679 | assert(eqT(math.min(3, 5, 9, 1), 1)) | ||
680 | assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2) | ||
681 | assert(math.min(1.9, 1.7, 1.72) == 1.7) | ||
682 | assert(math.min(-10e60, minint) == -10e60) | ||
683 | assert(eqT(math.min(maxint, maxint - 1), maxint - 1)) | ||
684 | assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2)) | ||
685 | end | ||
686 | -- testing implicit convertions | ||
687 | |||
688 | local a,b = '10', '20' | ||
689 | assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20) | ||
690 | assert(a == '10' and b == '20') | ||
691 | |||
692 | |||
693 | do | ||
694 | print("testing -0 and NaN") | ||
695 | local mz, z = -0.0, 0.0 | ||
696 | assert(mz == z) | ||
697 | assert(1/mz < 0 and 0 < 1/z) | ||
698 | local a = {[mz] = 1} | ||
699 | assert(a[z] == 1 and a[mz] == 1) | ||
700 | a[z] = 2 | ||
701 | assert(a[z] == 2 and a[mz] == 2) | ||
702 | local inf = math.huge * 2 + 1 | ||
703 | mz, z = -1/inf, 1/inf | ||
704 | assert(mz == z) | ||
705 | assert(1/mz < 0 and 0 < 1/z) | ||
706 | local NaN = inf - inf | ||
707 | assert(NaN ~= NaN) | ||
708 | assert(not (NaN < NaN)) | ||
709 | assert(not (NaN <= NaN)) | ||
710 | assert(not (NaN > NaN)) | ||
711 | assert(not (NaN >= NaN)) | ||
712 | assert(not (0 < NaN) and not (NaN < 0)) | ||
713 | local NaN1 = 0/0 | ||
714 | assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN)) | ||
715 | local a = {} | ||
716 | assert(not pcall(rawset, a, NaN, 1)) | ||
717 | assert(a[NaN] == undef) | ||
718 | a[1] = 1 | ||
719 | assert(not pcall(rawset, a, NaN, 1)) | ||
720 | assert(a[NaN] == undef) | ||
721 | -- strings with same binary representation as 0.0 (might create problems | ||
722 | -- for constant manipulation in the pre-compiler) | ||
723 | local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0" | ||
724 | assert(a1 == a2 and a2 == a4 and a1 ~= a3) | ||
725 | assert(a3 == a5) | ||
726 | end | ||
727 | |||
728 | |||
729 | print("testing 'math.random'") | ||
730 | |||
731 | local random, max, min = math.random, math.max, math.min | ||
732 | |||
733 | local function testnear (val, ref, tol) | ||
734 | return (math.abs(val - ref) < ref * tol) | ||
735 | end | ||
736 | |||
737 | |||
738 | -- low-level!! For the current implementation of random in Lua, | ||
739 | -- the first call after seed 1007 should return 0x7a7040a5a323c9d6 | ||
740 | do | ||
741 | -- all computations assume at most 32-bit integers | ||
742 | local h = 0x7a7040a5 -- higher half | ||
743 | local l = 0xa323c9d6 -- lower half | ||
744 | |||
745 | math.randomseed(1007) | ||
746 | -- get the low 'intbits' of the 64-bit expected result | ||
747 | local res = (h << 32 | l) & ~(~0 << intbits) | ||
748 | assert(random(0) == res) | ||
749 | |||
750 | math.randomseed(1007, 0) | ||
751 | -- using lower bits to generate random floats; (the '% 2^32' converts | ||
752 | -- 32-bit integers to floats as unsigned) | ||
753 | local res | ||
754 | if floatbits <= 32 then | ||
755 | -- get all bits from the lower half | ||
756 | res = (l & ~(~0 << floatbits)) % 2^32 | ||
757 | else | ||
758 | -- get 32 bits from the lower half and the rest from the higher half | ||
759 | res = ((h & ~(~0 << (floatbits - 32))) % 2^32) * 2^32 + (l % 2^32) | ||
760 | end | ||
761 | assert(random() * 2^floatbits == res) | ||
762 | end | ||
763 | |||
764 | math.randomseed(0, os.time()) | ||
765 | |||
766 | do -- test random for floats | ||
767 | local randbits = math.min(floatbits, 64) -- at most 64 random bits | ||
768 | local mult = 2^randbits -- to make random float into an integral | ||
769 | local counts = {} -- counts for bits | ||
770 | for i = 1, randbits do counts[i] = 0 end | ||
771 | local up = -math.huge | ||
772 | local low = math.huge | ||
773 | local rounds = 100 * randbits -- 100 times for each bit | ||
774 | local totalrounds = 0 | ||
775 | ::doagain:: -- will repeat test until we get good statistics | ||
776 | for i = 0, rounds do | ||
777 | local t = random() | ||
778 | assert(0 <= t and t < 1) | ||
779 | up = max(up, t) | ||
780 | low = min(low, t) | ||
781 | assert(t * mult % 1 == 0) -- no extra bits | ||
782 | local bit = i % randbits -- bit to be tested | ||
783 | if (t * 2^bit) % 1 >= 0.5 then -- is bit set? | ||
784 | counts[bit + 1] = counts[bit + 1] + 1 -- increment its count | ||
785 | end | ||
786 | end | ||
787 | totalrounds = totalrounds + rounds | ||
788 | if not (eq(up, 1, 0.001) and eq(low, 0, 0.001)) then | ||
789 | goto doagain | ||
790 | end | ||
791 | -- all bit counts should be near 50% | ||
792 | local expected = (totalrounds / randbits / 2) | ||
793 | for i = 1, randbits do | ||
794 | if not testnear(counts[i], expected, 0.10) then | ||
795 | goto doagain | ||
796 | end | ||
797 | end | ||
798 | print(string.format("float random range in %d calls: [%f, %f]", | ||
799 | totalrounds, low, up)) | ||
800 | end | ||
801 | |||
802 | |||
803 | do -- test random for full integers | ||
804 | local up = 0 | ||
805 | local low = 0 | ||
806 | local counts = {} -- counts for bits | ||
807 | for i = 1, intbits do counts[i] = 0 end | ||
808 | local rounds = 100 * intbits -- 100 times for each bit | ||
809 | local totalrounds = 0 | ||
810 | ::doagain:: -- will repeat test until we get good statistics | ||
811 | for i = 0, rounds do | ||
812 | local t = random(0) | ||
813 | up = max(up, t) | ||
814 | low = min(low, t) | ||
815 | local bit = i % intbits -- bit to be tested | ||
816 | -- increment its count if it is set | ||
817 | counts[bit + 1] = counts[bit + 1] + ((t >> bit) & 1) | ||
818 | end | ||
819 | totalrounds = totalrounds + rounds | ||
820 | local lim = maxint >> 10 | ||
821 | if not (maxint - up < lim and low - minint < lim) then | ||
822 | goto doagain | ||
823 | end | ||
824 | -- all bit counts should be near 50% | ||
825 | local expected = (totalrounds / intbits / 2) | ||
826 | for i = 1, intbits do | ||
827 | if not testnear(counts[i], expected, 0.10) then | ||
828 | goto doagain | ||
829 | end | ||
830 | end | ||
831 | print(string.format( | ||
832 | "integer random range in %d calls: [minint + %.0fppm, maxint - %.0fppm]", | ||
833 | totalrounds, (minint - low) / minint * 1e6, | ||
834 | (maxint - up) / maxint * 1e6)) | ||
835 | end | ||
836 | |||
837 | do | ||
838 | -- test distribution for a dice | ||
839 | local count = {0, 0, 0, 0, 0, 0} | ||
840 | local rep = 200 | ||
841 | local totalrep = 0 | ||
842 | ::doagain:: | ||
843 | for i = 1, rep * 6 do | ||
844 | local r = random(6) | ||
845 | count[r] = count[r] + 1 | ||
846 | end | ||
847 | totalrep = totalrep + rep | ||
848 | for i = 1, 6 do | ||
849 | if not testnear(count[i], totalrep, 0.05) then | ||
850 | goto doagain | ||
851 | end | ||
852 | end | ||
853 | end | ||
854 | |||
855 | do | ||
856 | local function aux (x1, x2) -- test random for small intervals | ||
857 | local mark = {}; local count = 0 -- to check that all values appeared | ||
858 | while true do | ||
859 | local t = random(x1, x2) | ||
860 | assert(x1 <= t and t <= x2) | ||
861 | if not mark[t] then -- new value | ||
862 | mark[t] = true | ||
863 | count = count + 1 | ||
864 | if count == x2 - x1 + 1 then -- all values appeared; OK | ||
865 | goto ok | ||
866 | end | ||
867 | end | ||
868 | end | ||
869 | ::ok:: | ||
870 | end | ||
871 | |||
872 | aux(-10,0) | ||
873 | aux(1, 6) | ||
874 | aux(1, 2) | ||
875 | aux(1, 32) | ||
876 | aux(-10, 10) | ||
877 | aux(-10,-10) -- unit set | ||
878 | aux(minint, minint) -- unit set | ||
879 | aux(maxint, maxint) -- unit set | ||
880 | aux(minint, minint + 9) | ||
881 | aux(maxint - 3, maxint) | ||
882 | end | ||
883 | |||
884 | do | ||
885 | local function aux(p1, p2) -- test random for large intervals | ||
886 | local max = minint | ||
887 | local min = maxint | ||
888 | local n = 100 | ||
889 | local mark = {}; local count = 0 -- to count how many different values | ||
890 | ::doagain:: | ||
891 | for _ = 1, n do | ||
892 | local t = random(p1, p2) | ||
893 | if not mark[t] then -- new value | ||
894 | assert(p1 <= t and t <= p2) | ||
895 | max = math.max(max, t) | ||
896 | min = math.min(min, t) | ||
897 | mark[t] = true | ||
898 | count = count + 1 | ||
899 | end | ||
900 | end | ||
901 | -- at least 80% of values are different | ||
902 | if not (count >= n * 0.8) then | ||
903 | goto doagain | ||
904 | end | ||
905 | -- min and max not too far from formal min and max | ||
906 | local diff = (p2 - p1) >> 4 | ||
907 | if not (min < p1 + diff and max > p2 - diff) then | ||
908 | goto doagain | ||
909 | end | ||
910 | end | ||
911 | aux(0, maxint) | ||
912 | aux(1, maxint) | ||
913 | aux(minint, -1) | ||
914 | aux(minint // 2, maxint // 2) | ||
915 | aux(minint, maxint) | ||
916 | aux(minint + 1, maxint) | ||
917 | aux(minint, maxint - 1) | ||
918 | aux(0, 1 << (intbits - 5)) | ||
919 | end | ||
920 | |||
921 | |||
922 | assert(not pcall(random, 1, 2, 3)) -- too many arguments | ||
923 | |||
924 | -- empty interval | ||
925 | assert(not pcall(random, minint + 1, minint)) | ||
926 | assert(not pcall(random, maxint, maxint - 1)) | ||
927 | assert(not pcall(random, maxint, minint)) | ||
928 | |||
929 | |||
930 | |||
931 | print('OK') | ||
diff --git a/testes/nextvar.lua b/testes/nextvar.lua new file mode 100644 index 00000000..3ac3acd9 --- /dev/null +++ b/testes/nextvar.lua | |||
@@ -0,0 +1,669 @@ | |||
1 | -- $Id: nextvar.lua,v 1.85 2018/06/19 12:24:19 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing tables, next, and for') | ||
5 | |||
6 | local function checkerror (msg, f, ...) | ||
7 | local s, err = pcall(f, ...) | ||
8 | assert(not s and string.find(err, msg)) | ||
9 | end | ||
10 | |||
11 | |||
12 | local a = {} | ||
13 | |||
14 | -- make sure table has lots of space in hash part | ||
15 | for i=1,100 do a[i.."+"] = true end | ||
16 | for i=1,100 do a[i.."+"] = undef end | ||
17 | -- fill hash part with numeric indices testing size operator | ||
18 | for i=1,100 do | ||
19 | a[i] = true | ||
20 | assert(#a == i) | ||
21 | end | ||
22 | |||
23 | -- testing ipairs | ||
24 | local x = 0 | ||
25 | for k,v in ipairs{10,20,30;x=12} do | ||
26 | x = x + 1 | ||
27 | assert(k == x and v == x * 10) | ||
28 | end | ||
29 | |||
30 | for _ in ipairs{x=12, y=24} do assert(nil) end | ||
31 | |||
32 | -- test for 'false' x ipair | ||
33 | x = false | ||
34 | local i = 0 | ||
35 | for k,v in ipairs{true,false,true,false} do | ||
36 | i = i + 1 | ||
37 | x = not x | ||
38 | assert(x == v) | ||
39 | end | ||
40 | assert(i == 4) | ||
41 | |||
42 | -- iterator function is always the same | ||
43 | assert(type(ipairs{}) == 'function' and ipairs{} == ipairs{}) | ||
44 | |||
45 | |||
46 | if not T then | ||
47 | (Message or print) | ||
48 | ('\n >>> testC not active: skipping tests for table sizes <<<\n') | ||
49 | else --[ | ||
50 | -- testing table sizes | ||
51 | |||
52 | local function log2 (x) return math.log(x, 2) end | ||
53 | |||
54 | local function mp2 (n) -- minimum power of 2 >= n | ||
55 | local mp = 2^math.ceil(log2(n)) | ||
56 | assert(n == 0 or (mp/2 < n and n <= mp)) | ||
57 | return mp | ||
58 | end | ||
59 | |||
60 | local function fb (n) | ||
61 | local r, nn = T.int2fb(n) | ||
62 | assert(r < 256) | ||
63 | return nn | ||
64 | end | ||
65 | |||
66 | -- test fb function | ||
67 | for a = 1, 10000 do -- all numbers up to 10^4 | ||
68 | local n = fb(a) | ||
69 | assert(a <= n and n <= a*1.125) | ||
70 | end | ||
71 | local a = 1024 -- plus a few up to 2 ^30 | ||
72 | local lim = 2^30 | ||
73 | while a < lim do | ||
74 | local n = fb(a) | ||
75 | assert(a <= n and n <= a*1.125) | ||
76 | a = math.ceil(a*1.3) | ||
77 | end | ||
78 | |||
79 | |||
80 | local function check (t, na, nh) | ||
81 | local a, h = T.querytab(t) | ||
82 | if a ~= na or h ~= nh then | ||
83 | print(na, nh, a, h) | ||
84 | assert(nil) | ||
85 | end | ||
86 | end | ||
87 | |||
88 | |||
89 | -- testing C library sizes | ||
90 | do | ||
91 | local s = 0 | ||
92 | for _ in pairs(math) do s = s + 1 end | ||
93 | check(math, 0, mp2(s)) | ||
94 | end | ||
95 | |||
96 | |||
97 | -- testing constructor sizes | ||
98 | local lim = 40 | ||
99 | local s = 'return {' | ||
100 | for i=1,lim do | ||
101 | s = s..i..',' | ||
102 | local s = s | ||
103 | for k=0,lim do | ||
104 | local t = load(s..'}', '')() | ||
105 | assert(#t == i) | ||
106 | check(t, fb(i), mp2(k)) | ||
107 | s = string.format('%sa%d=%d,', s, k, k) | ||
108 | end | ||
109 | end | ||
110 | |||
111 | |||
112 | -- tests with unknown number of elements | ||
113 | local a = {} | ||
114 | for i=1,lim do a[i] = i end -- build auxiliary table | ||
115 | for k=0,lim do | ||
116 | local a = {table.unpack(a,1,k)} | ||
117 | assert(#a == k) | ||
118 | check(a, k, 0) | ||
119 | a = {1,2,3,table.unpack(a,1,k)} | ||
120 | check(a, k+3, 0) | ||
121 | assert(#a == k + 3) | ||
122 | end | ||
123 | |||
124 | |||
125 | -- testing tables dynamically built | ||
126 | local lim = 130 | ||
127 | local a = {}; a[2] = 1; check(a, 0, 1) | ||
128 | a = {}; a[0] = 1; check(a, 0, 1); a[2] = 1; check(a, 0, 2) | ||
129 | a = {}; a[0] = 1; a[1] = 1; check(a, 1, 1) | ||
130 | a = {} | ||
131 | for i = 1,lim do | ||
132 | a[i] = 1 | ||
133 | assert(#a == i) | ||
134 | check(a, mp2(i), 0) | ||
135 | end | ||
136 | |||
137 | a = {} | ||
138 | for i = 1,lim do | ||
139 | a['a'..i] = 1 | ||
140 | assert(#a == 0) | ||
141 | check(a, 0, mp2(i)) | ||
142 | end | ||
143 | |||
144 | a = {} | ||
145 | for i=1,16 do a[i] = i end | ||
146 | check(a, 16, 0) | ||
147 | do | ||
148 | for i=1,11 do a[i] = undef end | ||
149 | for i=30,50 do a[i] = true; a[i] = undef end -- force a rehash (?) | ||
150 | check(a, 0, 8) -- 5 elements in the table | ||
151 | a[10] = 1 | ||
152 | for i=30,50 do a[i] = true; a[i] = undef end -- force a rehash (?) | ||
153 | check(a, 0, 8) -- only 6 elements in the table | ||
154 | for i=1,14 do a[i] = true; a[i] = undef end | ||
155 | for i=18,50 do a[i] = true; a[i] = undef end -- force a rehash (?) | ||
156 | check(a, 0, 4) -- only 2 elements ([15] and [16]) | ||
157 | end | ||
158 | |||
159 | -- reverse filling | ||
160 | for i=1,lim do | ||
161 | local a = {} | ||
162 | for i=i,1,-1 do a[i] = i end -- fill in reverse | ||
163 | check(a, mp2(i), 0) | ||
164 | end | ||
165 | |||
166 | -- size tests for vararg | ||
167 | lim = 35 | ||
168 | function foo (n, ...) | ||
169 | local arg = {...} | ||
170 | check(arg, n, 0) | ||
171 | assert(select('#', ...) == n) | ||
172 | arg[n+1] = true | ||
173 | check(arg, mp2(n+1), 0) | ||
174 | arg.x = true | ||
175 | check(arg, mp2(n+1), 1) | ||
176 | end | ||
177 | local a = {} | ||
178 | for i=1,lim do a[i] = true; foo(i, table.unpack(a)) end | ||
179 | |||
180 | |||
181 | -- Table length with limit smaller than maximum value at array | ||
182 | local a = {} | ||
183 | for i = 1,64 do a[i] = true end -- make its array size 64 | ||
184 | for i = 1,64 do a[i] = nil end -- erase all elements | ||
185 | assert(T.querytab(a) == 64) -- array part has 64 elements | ||
186 | a[32] = true; a[48] = true; -- binary search will find these ones | ||
187 | a[51] = true -- binary search will miss this one | ||
188 | assert(#a == 48) -- this will set the limit | ||
189 | assert(select(4, T.querytab(a)) == 48) -- this is the limit now | ||
190 | a[50] = true -- this will set a new limit | ||
191 | assert(select(4, T.querytab(a)) == 50) -- this is the limit now | ||
192 | -- but the size is larger (and still inside the array part) | ||
193 | assert(#a == 51) | ||
194 | |||
195 | end --] | ||
196 | |||
197 | |||
198 | -- test size operation on tables with nils | ||
199 | assert(#{} == 0) | ||
200 | assert(#{nil} == 0) | ||
201 | assert(#{nil, nil} == 0) | ||
202 | assert(#{nil, nil, nil} == 0) | ||
203 | assert(#{nil, nil, nil, nil} == 0) | ||
204 | assert(#{1, 2, 3, nil, nil} == 3) | ||
205 | print'+' | ||
206 | |||
207 | |||
208 | local nofind = {} | ||
209 | |||
210 | a,b,c = 1,2,3 | ||
211 | a,b,c = nil | ||
212 | |||
213 | |||
214 | -- next uses always the same iteraction function | ||
215 | assert(next{} == next{}) | ||
216 | |||
217 | local function find (name) | ||
218 | local n,v | ||
219 | while 1 do | ||
220 | n,v = next(_G, n) | ||
221 | if not n then return nofind end | ||
222 | assert(_G[n] ~= undef) | ||
223 | if n == name then return v end | ||
224 | end | ||
225 | end | ||
226 | |||
227 | local function find1 (name) | ||
228 | for n,v in pairs(_G) do | ||
229 | if n==name then return v end | ||
230 | end | ||
231 | return nil -- not found | ||
232 | end | ||
233 | |||
234 | |||
235 | assert(print==find("print") and print == find1("print")) | ||
236 | assert(_G["print"]==find("print")) | ||
237 | assert(assert==find1("assert")) | ||
238 | assert(nofind==find("return")) | ||
239 | assert(not find1("return")) | ||
240 | _G["ret" .. "urn"] = undef | ||
241 | assert(nofind==find("return")) | ||
242 | _G["xxx"] = 1 | ||
243 | assert(xxx==find("xxx")) | ||
244 | |||
245 | -- invalid key to 'next' | ||
246 | checkerror("invalid key", next, {10,20}, 3) | ||
247 | |||
248 | -- both 'pairs' and 'ipairs' need an argument | ||
249 | checkerror("bad argument", pairs) | ||
250 | checkerror("bad argument", ipairs) | ||
251 | |||
252 | print('+') | ||
253 | |||
254 | a = {} | ||
255 | for i=0,10000 do | ||
256 | if math.fmod(i,10) ~= 0 then | ||
257 | a['x'..i] = i | ||
258 | end | ||
259 | end | ||
260 | |||
261 | n = {n=0} | ||
262 | for i,v in pairs(a) do | ||
263 | n.n = n.n+1 | ||
264 | assert(i and v and a[i] == v) | ||
265 | end | ||
266 | assert(n.n == 9000) | ||
267 | a = nil | ||
268 | |||
269 | do -- clear global table | ||
270 | local a = {} | ||
271 | for n,v in pairs(_G) do a[n]=v end | ||
272 | for n,v in pairs(a) do | ||
273 | if not package.loaded[n] and type(v) ~= "function" and | ||
274 | not string.find(n, "^[%u_]") then | ||
275 | _G[n] = undef | ||
276 | end | ||
277 | collectgarbage() | ||
278 | end | ||
279 | end | ||
280 | |||
281 | |||
282 | -- | ||
283 | |||
284 | local function checknext (a) | ||
285 | local b = {} | ||
286 | do local k,v = next(a); while k do b[k] = v; k,v = next(a,k) end end | ||
287 | for k,v in pairs(b) do assert(a[k] == v) end | ||
288 | for k,v in pairs(a) do assert(b[k] == v) end | ||
289 | end | ||
290 | |||
291 | checknext{1,x=1,y=2,z=3} | ||
292 | checknext{1,2,x=1,y=2,z=3} | ||
293 | checknext{1,2,3,x=1,y=2,z=3} | ||
294 | checknext{1,2,3,4,x=1,y=2,z=3} | ||
295 | checknext{1,2,3,4,5,x=1,y=2,z=3} | ||
296 | |||
297 | assert(#{} == 0) | ||
298 | assert(#{[-1] = 2} == 0) | ||
299 | for i=0,40 do | ||
300 | local a = {} | ||
301 | for j=1,i do a[j]=j end | ||
302 | assert(#a == i) | ||
303 | end | ||
304 | |||
305 | -- 'maxn' is now deprecated, but it is easily defined in Lua | ||
306 | function table.maxn (t) | ||
307 | local max = 0 | ||
308 | for k in pairs(t) do | ||
309 | max = (type(k) == 'number') and math.max(max, k) or max | ||
310 | end | ||
311 | return max | ||
312 | end | ||
313 | |||
314 | assert(table.maxn{} == 0) | ||
315 | assert(table.maxn{["1000"] = true} == 0) | ||
316 | assert(table.maxn{["1000"] = true, [24.5] = 3} == 24.5) | ||
317 | assert(table.maxn{[1000] = true} == 1000) | ||
318 | assert(table.maxn{[10] = true, [100*math.pi] = print} == 100*math.pi) | ||
319 | |||
320 | table.maxn = nil | ||
321 | |||
322 | -- int overflow | ||
323 | a = {} | ||
324 | for i=0,50 do a[2^i] = true end | ||
325 | assert(a[#a]) | ||
326 | |||
327 | print('+') | ||
328 | |||
329 | |||
330 | do -- testing 'next' with all kinds of keys | ||
331 | local a = { | ||
332 | [1] = 1, -- integer | ||
333 | [1.1] = 2, -- float | ||
334 | ['x'] = 3, -- short string | ||
335 | [string.rep('x', 1000)] = 4, -- long string | ||
336 | [print] = 5, -- C function | ||
337 | [checkerror] = 6, -- Lua function | ||
338 | [coroutine.running()] = 7, -- thread | ||
339 | [true] = 8, -- boolean | ||
340 | [io.stdin] = 9, -- userdata | ||
341 | [{}] = 10, -- table | ||
342 | } | ||
343 | local b = {}; for i = 1, 10 do b[i] = true end | ||
344 | for k, v in pairs(a) do | ||
345 | assert(b[v]); b[v] = undef | ||
346 | end | ||
347 | assert(next(b) == nil) -- 'b' now is empty | ||
348 | end | ||
349 | |||
350 | |||
351 | -- erasing values | ||
352 | local t = {[{1}] = 1, [{2}] = 2, [string.rep("x ", 4)] = 3, | ||
353 | [100.3] = 4, [4] = 5} | ||
354 | |||
355 | local n = 0 | ||
356 | for k, v in pairs( t ) do | ||
357 | n = n+1 | ||
358 | assert(t[k] == v) | ||
359 | t[k] = undef | ||
360 | collectgarbage() | ||
361 | assert(t[k] == undef) | ||
362 | end | ||
363 | assert(n == 5) | ||
364 | |||
365 | |||
366 | local function test (a) | ||
367 | assert(not pcall(table.insert, a, 2, 20)); | ||
368 | table.insert(a, 10); table.insert(a, 2, 20); | ||
369 | table.insert(a, 1, -1); table.insert(a, 40); | ||
370 | table.insert(a, #a+1, 50) | ||
371 | table.insert(a, 2, -2) | ||
372 | assert(a[2] ~= undef) | ||
373 | assert(a["2"] == undef) | ||
374 | assert(not pcall(table.insert, a, 0, 20)); | ||
375 | assert(not pcall(table.insert, a, #a + 2, 20)); | ||
376 | assert(table.remove(a,1) == -1) | ||
377 | assert(table.remove(a,1) == -2) | ||
378 | assert(table.remove(a,1) == 10) | ||
379 | assert(table.remove(a,1) == 20) | ||
380 | assert(table.remove(a,1) == 40) | ||
381 | assert(table.remove(a,1) == 50) | ||
382 | assert(table.remove(a,1) == nil) | ||
383 | assert(table.remove(a) == nil) | ||
384 | assert(table.remove(a, #a) == nil) | ||
385 | end | ||
386 | |||
387 | a = {n=0, [-7] = "ban"} | ||
388 | test(a) | ||
389 | assert(a.n == 0 and a[-7] == "ban") | ||
390 | |||
391 | a = {[-7] = "ban"}; | ||
392 | test(a) | ||
393 | assert(a.n == nil and #a == 0 and a[-7] == "ban") | ||
394 | |||
395 | a = {[-1] = "ban"} | ||
396 | test(a) | ||
397 | assert(#a == 0 and table.remove(a) == nil and a[-1] == "ban") | ||
398 | |||
399 | a = {[0] = "ban"} | ||
400 | assert(#a == 0 and table.remove(a) == "ban" and a[0] == undef) | ||
401 | |||
402 | table.insert(a, 1, 10); table.insert(a, 1, 20); table.insert(a, 1, -1) | ||
403 | assert(table.remove(a) == 10) | ||
404 | assert(table.remove(a) == 20) | ||
405 | assert(table.remove(a) == -1) | ||
406 | assert(table.remove(a) == nil) | ||
407 | |||
408 | a = {'c', 'd'} | ||
409 | table.insert(a, 3, 'a') | ||
410 | table.insert(a, 'b') | ||
411 | assert(table.remove(a, 1) == 'c') | ||
412 | assert(table.remove(a, 1) == 'd') | ||
413 | assert(table.remove(a, 1) == 'a') | ||
414 | assert(table.remove(a, 1) == 'b') | ||
415 | assert(table.remove(a, 1) == nil) | ||
416 | assert(#a == 0 and a.n == nil) | ||
417 | |||
418 | a = {10,20,30,40} | ||
419 | assert(table.remove(a, #a + 1) == nil) | ||
420 | assert(not pcall(table.remove, a, 0)) | ||
421 | assert(a[#a] == 40) | ||
422 | assert(table.remove(a, #a) == 40) | ||
423 | assert(a[#a] == 30) | ||
424 | assert(table.remove(a, 2) == 20) | ||
425 | assert(a[#a] == 30 and #a == 2) | ||
426 | |||
427 | do -- testing table library with metamethods | ||
428 | local function test (proxy, t) | ||
429 | for i = 1, 10 do | ||
430 | table.insert(proxy, 1, i) | ||
431 | end | ||
432 | assert(#proxy == 10 and #t == 10 and proxy[1] ~= undef) | ||
433 | for i = 1, 10 do | ||
434 | assert(t[i] == 11 - i) | ||
435 | end | ||
436 | table.sort(proxy) | ||
437 | for i = 1, 10 do | ||
438 | assert(t[i] == i and proxy[i] == i) | ||
439 | end | ||
440 | assert(table.concat(proxy, ",") == "1,2,3,4,5,6,7,8,9,10") | ||
441 | for i = 1, 8 do | ||
442 | assert(table.remove(proxy, 1) == i) | ||
443 | end | ||
444 | assert(#proxy == 2 and #t == 2) | ||
445 | local a, b, c = table.unpack(proxy) | ||
446 | assert(a == 9 and b == 10 and c == nil) | ||
447 | end | ||
448 | |||
449 | -- all virtual | ||
450 | local t = {} | ||
451 | local proxy = setmetatable({}, { | ||
452 | __len = function () return #t end, | ||
453 | __index = t, | ||
454 | __newindex = t, | ||
455 | }) | ||
456 | test(proxy, t) | ||
457 | |||
458 | -- only __newindex | ||
459 | local count = 0 | ||
460 | t = setmetatable({}, { | ||
461 | __newindex = function (t,k,v) count = count + 1; rawset(t,k,v) end}) | ||
462 | test(t, t) | ||
463 | assert(count == 10) -- after first 10, all other sets are not new | ||
464 | |||
465 | -- no __newindex | ||
466 | t = setmetatable({}, { | ||
467 | __index = function (_,k) return k + 1 end, | ||
468 | __len = function (_) return 5 end}) | ||
469 | assert(table.concat(t, ";") == "2;3;4;5;6") | ||
470 | |||
471 | end | ||
472 | |||
473 | |||
474 | if not T then | ||
475 | (Message or print) | ||
476 | ('\n >>> testC not active: skipping tests for table library on non-tables <<<\n') | ||
477 | else --[ | ||
478 | local debug = require'debug' | ||
479 | local tab = {10, 20, 30} | ||
480 | local mt = {} | ||
481 | local u = T.newuserdata(0) | ||
482 | checkerror("table expected", table.insert, u, 40) | ||
483 | checkerror("table expected", table.remove, u) | ||
484 | debug.setmetatable(u, mt) | ||
485 | checkerror("table expected", table.insert, u, 40) | ||
486 | checkerror("table expected", table.remove, u) | ||
487 | mt.__index = tab | ||
488 | checkerror("table expected", table.insert, u, 40) | ||
489 | checkerror("table expected", table.remove, u) | ||
490 | mt.__newindex = tab | ||
491 | checkerror("table expected", table.insert, u, 40) | ||
492 | checkerror("table expected", table.remove, u) | ||
493 | mt.__len = function () return #tab end | ||
494 | table.insert(u, 40) | ||
495 | assert(#u == 4 and #tab == 4 and u[4] == 40 and tab[4] == 40) | ||
496 | assert(table.remove(u) == 40) | ||
497 | table.insert(u, 1, 50) | ||
498 | assert(#u == 4 and #tab == 4 and u[4] == 30 and tab[1] == 50) | ||
499 | |||
500 | mt.__newindex = nil | ||
501 | mt.__len = nil | ||
502 | local tab2 = {} | ||
503 | local u2 = T.newuserdata(0) | ||
504 | debug.setmetatable(u2, {__newindex = function (_, k, v) tab2[k] = v end}) | ||
505 | table.move(u, 1, 4, 1, u2) | ||
506 | assert(#tab2 == 4 and tab2[1] == tab[1] and tab2[4] == tab[4]) | ||
507 | |||
508 | end -- ] | ||
509 | |||
510 | print('+') | ||
511 | |||
512 | a = {} | ||
513 | for i=1,1000 do | ||
514 | a[i] = i; a[i - 1] = undef | ||
515 | end | ||
516 | assert(next(a,nil) == 1000 and next(a,1000) == nil) | ||
517 | |||
518 | assert(next({}) == nil) | ||
519 | assert(next({}, nil) == nil) | ||
520 | |||
521 | for a,b in pairs{} do error"not here" end | ||
522 | for i=1,0 do error'not here' end | ||
523 | for i=0,1,-1 do error'not here' end | ||
524 | a = nil; for i=1,1 do assert(not a); a=1 end; assert(a) | ||
525 | a = nil; for i=1,1,-1 do assert(not a); a=1 end; assert(a) | ||
526 | |||
527 | do | ||
528 | print("testing floats in numeric for") | ||
529 | local a | ||
530 | -- integer count | ||
531 | a = 0; for i=1, 1, 1 do a=a+1 end; assert(a==1) | ||
532 | a = 0; for i=10000, 1e4, -1 do a=a+1 end; assert(a==1) | ||
533 | a = 0; for i=1, 0.99999, 1 do a=a+1 end; assert(a==0) | ||
534 | a = 0; for i=9999, 1e4, -1 do a=a+1 end; assert(a==0) | ||
535 | a = 0; for i=1, 0.99999, -1 do a=a+1 end; assert(a==1) | ||
536 | |||
537 | -- float count | ||
538 | a = 0; for i=0, 0.999999999, 0.1 do a=a+1 end; assert(a==10) | ||
539 | a = 0; for i=1.0, 1, 1 do a=a+1 end; assert(a==1) | ||
540 | a = 0; for i=-1.5, -1.5, 1 do a=a+1 end; assert(a==1) | ||
541 | a = 0; for i=1e6, 1e6, -1 do a=a+1 end; assert(a==1) | ||
542 | a = 0; for i=1.0, 0.99999, 1 do a=a+1 end; assert(a==0) | ||
543 | a = 0; for i=99999, 1e5, -1.0 do a=a+1 end; assert(a==0) | ||
544 | a = 0; for i=1.0, 0.99999, -1 do a=a+1 end; assert(a==1) | ||
545 | end | ||
546 | |||
547 | -- conversion | ||
548 | a = 0; for i="10","1","-2" do a=a+1 end; assert(a==5) | ||
549 | |||
550 | do -- checking types | ||
551 | local c | ||
552 | local function checkfloat (i) | ||
553 | assert(math.type(i) == "float") | ||
554 | c = c + 1 | ||
555 | end | ||
556 | |||
557 | c = 0; for i = 1.0, 10 do checkfloat(i) end | ||
558 | assert(c == 10) | ||
559 | |||
560 | c = 0; for i = -1, -10, -1.0 do checkfloat(i) end | ||
561 | assert(c == 10) | ||
562 | |||
563 | local function checkint (i) | ||
564 | assert(math.type(i) == "integer") | ||
565 | c = c + 1 | ||
566 | end | ||
567 | |||
568 | local m = math.maxinteger | ||
569 | c = 0; for i = m, m - 10, -1 do checkint(i) end | ||
570 | assert(c == 11) | ||
571 | |||
572 | c = 0; for i = 1, 10.9 do checkint(i) end | ||
573 | assert(c == 10) | ||
574 | |||
575 | c = 0; for i = 10, 0.001, -1 do checkint(i) end | ||
576 | assert(c == 10) | ||
577 | |||
578 | c = 0; for i = 1, "10.8" do checkint(i) end | ||
579 | assert(c == 10) | ||
580 | |||
581 | c = 0; for i = 9, "3.4", -1 do checkint(i) end | ||
582 | assert(c == 6) | ||
583 | |||
584 | c = 0; for i = 0, " -3.4 ", -1 do checkint(i) end | ||
585 | assert(c == 4) | ||
586 | |||
587 | c = 0; for i = 100, "96.3", -2 do checkint(i) end | ||
588 | assert(c == 2) | ||
589 | |||
590 | c = 0; for i = 1, math.huge do if i > 10 then break end; checkint(i) end | ||
591 | assert(c == 10) | ||
592 | |||
593 | c = 0; for i = -1, -math.huge, -1 do | ||
594 | if i < -10 then break end; checkint(i) | ||
595 | end | ||
596 | assert(c == 10) | ||
597 | |||
598 | |||
599 | for i = math.mininteger, -10e100 do assert(false) end | ||
600 | for i = math.maxinteger, 10e100, -1 do assert(false) end | ||
601 | |||
602 | end | ||
603 | |||
604 | collectgarbage() | ||
605 | |||
606 | |||
607 | -- testing generic 'for' | ||
608 | |||
609 | local function f (n, p) | ||
610 | local t = {}; for i=1,p do t[i] = i*10 end | ||
611 | return function (_,n) | ||
612 | if n > 0 then | ||
613 | n = n-1 | ||
614 | return n, table.unpack(t) | ||
615 | end | ||
616 | end, nil, n | ||
617 | end | ||
618 | |||
619 | local x = 0 | ||
620 | for n,a,b,c,d in f(5,3) do | ||
621 | x = x+1 | ||
622 | assert(a == 10 and b == 20 and c == 30 and d == nil) | ||
623 | end | ||
624 | assert(x == 5) | ||
625 | |||
626 | |||
627 | |||
628 | -- testing __pairs and __ipairs metamethod | ||
629 | a = {} | ||
630 | do | ||
631 | local x,y,z = pairs(a) | ||
632 | assert(type(x) == 'function' and y == a and z == nil) | ||
633 | end | ||
634 | |||
635 | local function foo (e,i) | ||
636 | assert(e == a) | ||
637 | if i <= 10 then return i+1, i+2 end | ||
638 | end | ||
639 | |||
640 | local function foo1 (e,i) | ||
641 | i = i + 1 | ||
642 | assert(e == a) | ||
643 | if i <= e.n then return i,a[i] end | ||
644 | end | ||
645 | |||
646 | setmetatable(a, {__pairs = function (x) return foo, x, 0 end}) | ||
647 | |||
648 | local i = 0 | ||
649 | for k,v in pairs(a) do | ||
650 | i = i + 1 | ||
651 | assert(k == i and v == k+1) | ||
652 | end | ||
653 | |||
654 | a.n = 5 | ||
655 | a[3] = 30 | ||
656 | |||
657 | -- testing ipairs with metamethods | ||
658 | a = {n=10} | ||
659 | setmetatable(a, { __index = function (t,k) | ||
660 | if k <= t.n then return k * 10 end | ||
661 | end}) | ||
662 | i = 0 | ||
663 | for k,v in ipairs(a) do | ||
664 | i = i + 1 | ||
665 | assert(k == i and v == i * 10) | ||
666 | end | ||
667 | assert(i == a.n) | ||
668 | |||
669 | print"OK" | ||
diff --git a/testes/pm.lua b/testes/pm.lua new file mode 100644 index 00000000..e517c8b6 --- /dev/null +++ b/testes/pm.lua | |||
@@ -0,0 +1,374 @@ | |||
1 | -- $Id: pm.lua,v 1.50 2018/03/12 14:19:36 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing pattern matching') | ||
5 | |||
6 | local function checkerror (msg, f, ...) | ||
7 | local s, err = pcall(f, ...) | ||
8 | assert(not s and string.find(err, msg)) | ||
9 | end | ||
10 | |||
11 | |||
12 | function f(s, p) | ||
13 | local i,e = string.find(s, p) | ||
14 | if i then return string.sub(s, i, e) end | ||
15 | end | ||
16 | |||
17 | a,b = string.find('', '') -- empty patterns are tricky | ||
18 | assert(a == 1 and b == 0); | ||
19 | a,b = string.find('alo', '') | ||
20 | assert(a == 1 and b == 0) | ||
21 | a,b = string.find('a\0o a\0o a\0o', 'a', 1) -- first position | ||
22 | assert(a == 1 and b == 1) | ||
23 | a,b = string.find('a\0o a\0o a\0o', 'a\0o', 2) -- starts in the midle | ||
24 | assert(a == 5 and b == 7) | ||
25 | a,b = string.find('a\0o a\0o a\0o', 'a\0o', 9) -- starts in the midle | ||
26 | assert(a == 9 and b == 11) | ||
27 | a,b = string.find('a\0a\0a\0a\0\0ab', '\0ab', 2); -- finds at the end | ||
28 | assert(a == 9 and b == 11); | ||
29 | a,b = string.find('a\0a\0a\0a\0\0ab', 'b') -- last position | ||
30 | assert(a == 11 and b == 11) | ||
31 | assert(string.find('a\0a\0a\0a\0\0ab', 'b\0') == nil) -- check ending | ||
32 | assert(string.find('', '\0') == nil) | ||
33 | assert(string.find('alo123alo', '12') == 4) | ||
34 | assert(string.find('alo123alo', '^12') == nil) | ||
35 | |||
36 | assert(string.match("aaab", ".*b") == "aaab") | ||
37 | assert(string.match("aaa", ".*a") == "aaa") | ||
38 | assert(string.match("b", ".*b") == "b") | ||
39 | |||
40 | assert(string.match("aaab", ".+b") == "aaab") | ||
41 | assert(string.match("aaa", ".+a") == "aaa") | ||
42 | assert(not string.match("b", ".+b")) | ||
43 | |||
44 | assert(string.match("aaab", ".?b") == "ab") | ||
45 | assert(string.match("aaa", ".?a") == "aa") | ||
46 | assert(string.match("b", ".?b") == "b") | ||
47 | |||
48 | assert(f('aloALO', '%l*') == 'alo') | ||
49 | assert(f('aLo_ALO', '%a*') == 'aLo') | ||
50 | |||
51 | assert(f(" \n\r*&\n\r xuxu \n\n", "%g%g%g+") == "xuxu") | ||
52 | |||
53 | assert(f('aaab', 'a*') == 'aaa'); | ||
54 | assert(f('aaa', '^.*$') == 'aaa'); | ||
55 | assert(f('aaa', 'b*') == ''); | ||
56 | assert(f('aaa', 'ab*a') == 'aa') | ||
57 | assert(f('aba', 'ab*a') == 'aba') | ||
58 | assert(f('aaab', 'a+') == 'aaa') | ||
59 | assert(f('aaa', '^.+$') == 'aaa') | ||
60 | assert(f('aaa', 'b+') == nil) | ||
61 | assert(f('aaa', 'ab+a') == nil) | ||
62 | assert(f('aba', 'ab+a') == 'aba') | ||
63 | assert(f('a$a', '.$') == 'a') | ||
64 | assert(f('a$a', '.%$') == 'a$') | ||
65 | assert(f('a$a', '.$.') == 'a$a') | ||
66 | assert(f('a$a', '$$') == nil) | ||
67 | assert(f('a$b', 'a$') == nil) | ||
68 | assert(f('a$a', '$') == '') | ||
69 | assert(f('', 'b*') == '') | ||
70 | assert(f('aaa', 'bb*') == nil) | ||
71 | assert(f('aaab', 'a-') == '') | ||
72 | assert(f('aaa', '^.-$') == 'aaa') | ||
73 | assert(f('aabaaabaaabaaaba', 'b.*b') == 'baaabaaabaaab') | ||
74 | assert(f('aabaaabaaabaaaba', 'b.-b') == 'baaab') | ||
75 | assert(f('alo xo', '.o$') == 'xo') | ||
76 | assert(f(' \n isto é assim', '%S%S*') == 'isto') | ||
77 | assert(f(' \n isto é assim', '%S*$') == 'assim') | ||
78 | assert(f(' \n isto é assim', '[a-z]*$') == 'assim') | ||
79 | assert(f('um caracter ? extra', '[^%sa-z]') == '?') | ||
80 | assert(f('', 'a?') == '') | ||
81 | assert(f('á', 'á?') == 'á') | ||
82 | assert(f('ábl', 'á?b?l?') == 'ábl') | ||
83 | assert(f(' ábl', 'á?b?l?') == '') | ||
84 | assert(f('aa', '^aa?a?a') == 'aa') | ||
85 | assert(f(']]]áb', '[^]]') == 'á') | ||
86 | assert(f("0alo alo", "%x*") == "0a") | ||
87 | assert(f("alo alo", "%C+") == "alo alo") | ||
88 | print('+') | ||
89 | |||
90 | |||
91 | function f1(s, p) | ||
92 | p = string.gsub(p, "%%([0-9])", function (s) | ||
93 | return "%" .. (tonumber(s)+1) | ||
94 | end) | ||
95 | p = string.gsub(p, "^(^?)", "%1()", 1) | ||
96 | p = string.gsub(p, "($?)$", "()%1", 1) | ||
97 | local t = {string.match(s, p)} | ||
98 | return string.sub(s, t[1], t[#t] - 1) | ||
99 | end | ||
100 | |||
101 | assert(f1('alo alx 123 b\0o b\0o', '(..*) %1') == "b\0o b\0o") | ||
102 | assert(f1('axz123= 4= 4 34', '(.+)=(.*)=%2 %1') == '3= 4= 4 3') | ||
103 | assert(f1('=======', '^(=*)=%1$') == '=======') | ||
104 | assert(string.match('==========', '^([=]*)=%1$') == nil) | ||
105 | |||
106 | local function range (i, j) | ||
107 | if i <= j then | ||
108 | return i, range(i+1, j) | ||
109 | end | ||
110 | end | ||
111 | |||
112 | local abc = string.char(range(0, 127)) .. string.char(range(128, 255)); | ||
113 | |||
114 | assert(string.len(abc) == 256) | ||
115 | |||
116 | function strset (p) | ||
117 | local res = {s=''} | ||
118 | string.gsub(abc, p, function (c) res.s = res.s .. c end) | ||
119 | return res.s | ||
120 | end; | ||
121 | |||
122 | assert(string.len(strset('[\200-\210]')) == 11) | ||
123 | |||
124 | assert(strset('[a-z]') == "abcdefghijklmnopqrstuvwxyz") | ||
125 | assert(strset('[a-z%d]') == strset('[%da-uu-z]')) | ||
126 | assert(strset('[a-]') == "-a") | ||
127 | assert(strset('[^%W]') == strset('[%w]')) | ||
128 | assert(strset('[]%%]') == '%]') | ||
129 | assert(strset('[a%-z]') == '-az') | ||
130 | assert(strset('[%^%[%-a%]%-b]') == '-[]^ab') | ||
131 | assert(strset('%Z') == strset('[\1-\255]')) | ||
132 | assert(strset('.') == strset('[\1-\255%z]')) | ||
133 | print('+'); | ||
134 | |||
135 | assert(string.match("alo xyzK", "(%w+)K") == "xyz") | ||
136 | assert(string.match("254 K", "(%d*)K") == "") | ||
137 | assert(string.match("alo ", "(%w*)$") == "") | ||
138 | assert(string.match("alo ", "(%w+)$") == nil) | ||
139 | assert(string.find("(álo)", "%(á") == 1) | ||
140 | local a, b, c, d, e = string.match("âlo alo", "^(((.).).* (%w*))$") | ||
141 | assert(a == 'âlo alo' and b == 'âl' and c == 'â' and d == 'alo' and e == nil) | ||
142 | a, b, c, d = string.match('0123456789', '(.+(.?)())') | ||
143 | assert(a == '0123456789' and b == '' and c == 11 and d == nil) | ||
144 | print('+') | ||
145 | |||
146 | assert(string.gsub('ülo ülo', 'ü', 'x') == 'xlo xlo') | ||
147 | assert(string.gsub('alo úlo ', ' +$', '') == 'alo úlo') -- trim | ||
148 | assert(string.gsub(' alo alo ', '^%s*(.-)%s*$', '%1') == 'alo alo') -- double trim | ||
149 | assert(string.gsub('alo alo \n 123\n ', '%s+', ' ') == 'alo alo 123 ') | ||
150 | t = "abç d" | ||
151 | a, b = string.gsub(t, '(.)', '%1@') | ||
152 | assert('@'..a == string.gsub(t, '', '@') and b == 5) | ||
153 | a, b = string.gsub('abçd', '(.)', '%0@', 2) | ||
154 | assert(a == 'a@b@çd' and b == 2) | ||
155 | assert(string.gsub('alo alo', '()[al]', '%1') == '12o 56o') | ||
156 | assert(string.gsub("abc=xyz", "(%w*)(%p)(%w+)", "%3%2%1-%0") == | ||
157 | "xyz=abc-abc=xyz") | ||
158 | assert(string.gsub("abc", "%w", "%1%0") == "aabbcc") | ||
159 | assert(string.gsub("abc", "%w+", "%0%1") == "abcabc") | ||
160 | assert(string.gsub('áéí', '$', '\0óú') == 'áéí\0óú') | ||
161 | assert(string.gsub('', '^', 'r') == 'r') | ||
162 | assert(string.gsub('', '$', 'r') == 'r') | ||
163 | print('+') | ||
164 | |||
165 | |||
166 | do -- new (5.3.3) semantics for empty matches | ||
167 | assert(string.gsub("a b cd", " *", "-") == "-a-b-c-d-") | ||
168 | |||
169 | local res = "" | ||
170 | local sub = "a \nbc\t\td" | ||
171 | local i = 1 | ||
172 | for p, e in string.gmatch(sub, "()%s*()") do | ||
173 | res = res .. string.sub(sub, i, p - 1) .. "-" | ||
174 | i = e | ||
175 | end | ||
176 | assert(res == "-a-b-c-d-") | ||
177 | end | ||
178 | |||
179 | |||
180 | assert(string.gsub("um (dois) tres (quatro)", "(%(%w+%))", string.upper) == | ||
181 | "um (DOIS) tres (QUATRO)") | ||
182 | |||
183 | do | ||
184 | local function setglobal (n,v) rawset(_G, n, v) end | ||
185 | string.gsub("a=roberto,roberto=a", "(%w+)=(%w%w*)", setglobal) | ||
186 | assert(_G.a=="roberto" and _G.roberto=="a") | ||
187 | end | ||
188 | |||
189 | function f(a,b) return string.gsub(a,'.',b) end | ||
190 | assert(string.gsub("trocar tudo em |teste|b| é |beleza|al|", "|([^|]*)|([^|]*)|", f) == | ||
191 | "trocar tudo em bbbbb é alalalalalal") | ||
192 | |||
193 | local function dostring (s) return load(s, "")() or "" end | ||
194 | assert(string.gsub("alo $a='x'$ novamente $return a$", | ||
195 | "$([^$]*)%$", | ||
196 | dostring) == "alo novamente x") | ||
197 | |||
198 | x = string.gsub("$x=string.gsub('alo', '.', string.upper)$ assim vai para $return x$", | ||
199 | "$([^$]*)%$", dostring) | ||
200 | assert(x == ' assim vai para ALO') | ||
201 | |||
202 | t = {} | ||
203 | s = 'a alo jose joao' | ||
204 | r = string.gsub(s, '()(%w+)()', function (a,w,b) | ||
205 | assert(string.len(w) == b-a); | ||
206 | t[a] = b-a; | ||
207 | end) | ||
208 | assert(s == r and t[1] == 1 and t[3] == 3 and t[7] == 4 and t[13] == 4) | ||
209 | |||
210 | |||
211 | function isbalanced (s) | ||
212 | return string.find(string.gsub(s, "%b()", ""), "[()]") == nil | ||
213 | end | ||
214 | |||
215 | assert(isbalanced("(9 ((8))(\0) 7) \0\0 a b ()(c)() a")) | ||
216 | assert(not isbalanced("(9 ((8) 7) a b (\0 c) a")) | ||
217 | assert(string.gsub("alo 'oi' alo", "%b''", '"') == 'alo " alo') | ||
218 | |||
219 | |||
220 | local t = {"apple", "orange", "lime"; n=0} | ||
221 | assert(string.gsub("x and x and x", "x", function () t.n=t.n+1; return t[t.n] end) | ||
222 | == "apple and orange and lime") | ||
223 | |||
224 | t = {n=0} | ||
225 | string.gsub("first second word", "%w%w*", function (w) t.n=t.n+1; t[t.n] = w end) | ||
226 | assert(t[1] == "first" and t[2] == "second" and t[3] == "word" and t.n == 3) | ||
227 | |||
228 | t = {n=0} | ||
229 | assert(string.gsub("first second word", "%w+", | ||
230 | function (w) t.n=t.n+1; t[t.n] = w end, 2) == "first second word") | ||
231 | assert(t[1] == "first" and t[2] == "second" and t[3] == undef) | ||
232 | |||
233 | checkerror("invalid replacement value %(a table%)", | ||
234 | string.gsub, "alo", ".", {a = {}}) | ||
235 | checkerror("invalid capture index %%2", string.gsub, "alo", ".", "%2") | ||
236 | checkerror("invalid capture index %%0", string.gsub, "alo", "(%0)", "a") | ||
237 | checkerror("invalid capture index %%1", string.gsub, "alo", "(%1)", "a") | ||
238 | checkerror("invalid use of '%%'", string.gsub, "alo", ".", "%x") | ||
239 | |||
240 | -- bug since 2.5 (C-stack overflow) | ||
241 | do | ||
242 | local function f (size) | ||
243 | local s = string.rep("a", size) | ||
244 | local p = string.rep(".?", size) | ||
245 | return pcall(string.match, s, p) | ||
246 | end | ||
247 | local r, m = f(80) | ||
248 | assert(r and #m == 80) | ||
249 | r, m = f(200000) | ||
250 | assert(not r and string.find(m, "too complex")) | ||
251 | end | ||
252 | |||
253 | if not _soft then | ||
254 | print("big strings") | ||
255 | local a = string.rep('a', 300000) | ||
256 | assert(string.find(a, '^a*.?$')) | ||
257 | assert(not string.find(a, '^a*.?b$')) | ||
258 | assert(string.find(a, '^a-.?$')) | ||
259 | |||
260 | -- bug in 5.1.2 | ||
261 | a = string.rep('a', 10000) .. string.rep('b', 10000) | ||
262 | assert(not pcall(string.gsub, a, 'b')) | ||
263 | end | ||
264 | |||
265 | -- recursive nest of gsubs | ||
266 | function rev (s) | ||
267 | return string.gsub(s, "(.)(.+)", function (c,s1) return rev(s1)..c end) | ||
268 | end | ||
269 | |||
270 | local x = "abcdef" | ||
271 | assert(rev(rev(x)) == x) | ||
272 | |||
273 | |||
274 | -- gsub with tables | ||
275 | assert(string.gsub("alo alo", ".", {}) == "alo alo") | ||
276 | assert(string.gsub("alo alo", "(.)", {a="AA", l=""}) == "AAo AAo") | ||
277 | assert(string.gsub("alo alo", "(.).", {a="AA", l="K"}) == "AAo AAo") | ||
278 | assert(string.gsub("alo alo", "((.)(.?))", {al="AA", o=false}) == "AAo AAo") | ||
279 | |||
280 | assert(string.gsub("alo alo", "().", {'x','yy','zzz'}) == "xyyzzz alo") | ||
281 | |||
282 | t = {}; setmetatable(t, {__index = function (t,s) return string.upper(s) end}) | ||
283 | assert(string.gsub("a alo b hi", "%w%w+", t) == "a ALO b HI") | ||
284 | |||
285 | |||
286 | -- tests for gmatch | ||
287 | local a = 0 | ||
288 | for i in string.gmatch('abcde', '()') do assert(i == a+1); a=i end | ||
289 | assert(a==6) | ||
290 | |||
291 | t = {n=0} | ||
292 | for w in string.gmatch("first second word", "%w+") do | ||
293 | t.n=t.n+1; t[t.n] = w | ||
294 | end | ||
295 | assert(t[1] == "first" and t[2] == "second" and t[3] == "word") | ||
296 | |||
297 | t = {3, 6, 9} | ||
298 | for i in string.gmatch ("xuxx uu ppar r", "()(.)%2") do | ||
299 | assert(i == table.remove(t, 1)) | ||
300 | end | ||
301 | assert(#t == 0) | ||
302 | |||
303 | t = {} | ||
304 | for i,j in string.gmatch("13 14 10 = 11, 15= 16, 22=23", "(%d+)%s*=%s*(%d+)") do | ||
305 | t[tonumber(i)] = tonumber(j) | ||
306 | end | ||
307 | a = 0 | ||
308 | for k,v in pairs(t) do assert(k+1 == v+0); a=a+1 end | ||
309 | assert(a == 3) | ||
310 | |||
311 | |||
312 | -- tests for `%f' (`frontiers') | ||
313 | |||
314 | assert(string.gsub("aaa aa a aaa a", "%f[%w]a", "x") == "xaa xa x xaa x") | ||
315 | assert(string.gsub("[[]] [][] [[[[", "%f[[].", "x") == "x[]] x]x] x[[[") | ||
316 | assert(string.gsub("01abc45de3", "%f[%d]", ".") == ".01abc.45de.3") | ||
317 | assert(string.gsub("01abc45 de3x", "%f[%D]%w", ".") == "01.bc45 de3.") | ||
318 | assert(string.gsub("function", "%f[\1-\255]%w", ".") == ".unction") | ||
319 | assert(string.gsub("function", "%f[^\1-\255]", ".") == "function.") | ||
320 | |||
321 | assert(string.find("a", "%f[a]") == 1) | ||
322 | assert(string.find("a", "%f[^%z]") == 1) | ||
323 | assert(string.find("a", "%f[^%l]") == 2) | ||
324 | assert(string.find("aba", "%f[a%z]") == 3) | ||
325 | assert(string.find("aba", "%f[%z]") == 4) | ||
326 | assert(not string.find("aba", "%f[%l%z]")) | ||
327 | assert(not string.find("aba", "%f[^%l%z]")) | ||
328 | |||
329 | local i, e = string.find(" alo aalo allo", "%f[%S].-%f[%s].-%f[%S]") | ||
330 | assert(i == 2 and e == 5) | ||
331 | local k = string.match(" alo aalo allo", "%f[%S](.-%f[%s].-%f[%S])") | ||
332 | assert(k == 'alo ') | ||
333 | |||
334 | local a = {1, 5, 9, 14, 17,} | ||
335 | for k in string.gmatch("alo alo th02 is 1hat", "()%f[%w%d]") do | ||
336 | assert(table.remove(a, 1) == k) | ||
337 | end | ||
338 | assert(#a == 0) | ||
339 | |||
340 | |||
341 | -- malformed patterns | ||
342 | local function malform (p, m) | ||
343 | m = m or "malformed" | ||
344 | local r, msg = pcall(string.find, "a", p) | ||
345 | assert(not r and string.find(msg, m)) | ||
346 | end | ||
347 | |||
348 | malform("(.", "unfinished capture") | ||
349 | malform(".)", "invalid pattern capture") | ||
350 | malform("[a") | ||
351 | malform("[]") | ||
352 | malform("[^]") | ||
353 | malform("[a%]") | ||
354 | malform("[a%") | ||
355 | malform("%b") | ||
356 | malform("%ba") | ||
357 | malform("%") | ||
358 | malform("%f", "missing") | ||
359 | |||
360 | -- \0 in patterns | ||
361 | assert(string.match("ab\0\1\2c", "[\0-\2]+") == "\0\1\2") | ||
362 | assert(string.match("ab\0\1\2c", "[\0-\0]+") == "\0") | ||
363 | assert(string.find("b$a", "$\0?") == 2) | ||
364 | assert(string.find("abc\0efg", "%\0") == 4) | ||
365 | assert(string.match("abc\0efg\0\1e\1g", "%b\0\1") == "\0efg\0\1e\1") | ||
366 | assert(string.match("abc\0\0\0", "%\0+") == "\0\0\0") | ||
367 | assert(string.match("abc\0\0\0", "%\0%\0?") == "\0\0") | ||
368 | |||
369 | -- magic char after \0 | ||
370 | assert(string.find("abc\0\0","\0.") == 4) | ||
371 | assert(string.find("abcx\0\0abc\0abc","x\0\0abc\0a.") == 4) | ||
372 | |||
373 | print('OK') | ||
374 | |||
diff --git a/testes/sort.lua b/testes/sort.lua new file mode 100644 index 00000000..6eb9b706 --- /dev/null +++ b/testes/sort.lua | |||
@@ -0,0 +1,310 @@ | |||
1 | -- $Id: sort.lua,v 1.39 2018/03/12 13:51:02 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print "testing (parts of) table library" | ||
5 | |||
6 | print "testing unpack" | ||
7 | |||
8 | local unpack = table.unpack | ||
9 | |||
10 | local maxI = math.maxinteger | ||
11 | local minI = math.mininteger | ||
12 | |||
13 | |||
14 | local function checkerror (msg, f, ...) | ||
15 | local s, err = pcall(f, ...) | ||
16 | assert(not s and string.find(err, msg)) | ||
17 | end | ||
18 | |||
19 | |||
20 | checkerror("wrong number of arguments", table.insert, {}, 2, 3, 4) | ||
21 | |||
22 | local x,y,z,a,n | ||
23 | a = {}; lim = _soft and 200 or 2000 | ||
24 | for i=1, lim do a[i]=i end | ||
25 | assert(select(lim, unpack(a)) == lim and select('#', unpack(a)) == lim) | ||
26 | x = unpack(a) | ||
27 | assert(x == 1) | ||
28 | x = {unpack(a)} | ||
29 | assert(#x == lim and x[1] == 1 and x[lim] == lim) | ||
30 | x = {unpack(a, lim-2)} | ||
31 | assert(#x == 3 and x[1] == lim-2 and x[3] == lim) | ||
32 | x = {unpack(a, 10, 6)} | ||
33 | assert(next(x) == nil) -- no elements | ||
34 | x = {unpack(a, 11, 10)} | ||
35 | assert(next(x) == nil) -- no elements | ||
36 | x,y = unpack(a, 10, 10) | ||
37 | assert(x == 10 and y == nil) | ||
38 | x,y,z = unpack(a, 10, 11) | ||
39 | assert(x == 10 and y == 11 and z == nil) | ||
40 | a,x = unpack{1} | ||
41 | assert(a==1 and x==nil) | ||
42 | a,x = unpack({1,2}, 1, 1) | ||
43 | assert(a==1 and x==nil) | ||
44 | |||
45 | do | ||
46 | local maxi = (1 << 31) - 1 -- maximum value for an int (usually) | ||
47 | local mini = -(1 << 31) -- minimum value for an int (usually) | ||
48 | checkerror("too many results", unpack, {}, 0, maxi) | ||
49 | checkerror("too many results", unpack, {}, 1, maxi) | ||
50 | checkerror("too many results", unpack, {}, 0, maxI) | ||
51 | checkerror("too many results", unpack, {}, 1, maxI) | ||
52 | checkerror("too many results", unpack, {}, mini, maxi) | ||
53 | checkerror("too many results", unpack, {}, -maxi, maxi) | ||
54 | checkerror("too many results", unpack, {}, minI, maxI) | ||
55 | unpack({}, maxi, 0) | ||
56 | unpack({}, maxi, 1) | ||
57 | unpack({}, maxI, minI) | ||
58 | pcall(unpack, {}, 1, maxi + 1) | ||
59 | local a, b = unpack({[maxi] = 20}, maxi, maxi) | ||
60 | assert(a == 20 and b == nil) | ||
61 | a, b = unpack({[maxi] = 20}, maxi - 1, maxi) | ||
62 | assert(a == nil and b == 20) | ||
63 | local t = {[maxI - 1] = 12, [maxI] = 23} | ||
64 | a, b = unpack(t, maxI - 1, maxI); assert(a == 12 and b == 23) | ||
65 | a, b = unpack(t, maxI, maxI); assert(a == 23 and b == nil) | ||
66 | a, b = unpack(t, maxI, maxI - 1); assert(a == nil and b == nil) | ||
67 | t = {[minI] = 12.3, [minI + 1] = 23.5} | ||
68 | a, b = unpack(t, minI, minI + 1); assert(a == 12.3 and b == 23.5) | ||
69 | a, b = unpack(t, minI, minI); assert(a == 12.3 and b == nil) | ||
70 | a, b = unpack(t, minI + 1, minI); assert(a == nil and b == nil) | ||
71 | end | ||
72 | |||
73 | do -- length is not an integer | ||
74 | local t = setmetatable({}, {__len = function () return 'abc' end}) | ||
75 | assert(#t == 'abc') | ||
76 | checkerror("object length is not an integer", table.insert, t, 1) | ||
77 | end | ||
78 | |||
79 | print "testing pack" | ||
80 | |||
81 | a = table.pack() | ||
82 | assert(a[1] == undef and a.n == 0) | ||
83 | |||
84 | a = table.pack(table) | ||
85 | assert(a[1] == table and a.n == 1) | ||
86 | |||
87 | a = table.pack(nil, nil, nil, nil) | ||
88 | assert(a[1] == nil and a.n == 4) | ||
89 | |||
90 | |||
91 | -- testing move | ||
92 | do | ||
93 | |||
94 | checkerror("table expected", table.move, 1, 2, 3, 4) | ||
95 | |||
96 | local function eqT (a, b) | ||
97 | for k, v in pairs(a) do assert(b[k] == v) end | ||
98 | for k, v in pairs(b) do assert(a[k] == v) end | ||
99 | end | ||
100 | |||
101 | local a = table.move({10,20,30}, 1, 3, 2) -- move forward | ||
102 | eqT(a, {10,10,20,30}) | ||
103 | |||
104 | -- move forward with overlap of 1 | ||
105 | a = table.move({10, 20, 30}, 1, 3, 3) | ||
106 | eqT(a, {10, 20, 10, 20, 30}) | ||
107 | |||
108 | -- moving to the same table (not being explicit about it) | ||
109 | a = {10, 20, 30, 40} | ||
110 | table.move(a, 1, 4, 2, a) | ||
111 | eqT(a, {10, 10, 20, 30, 40}) | ||
112 | |||
113 | a = table.move({10,20,30}, 2, 3, 1) -- move backward | ||
114 | eqT(a, {20,30,30}) | ||
115 | |||
116 | a = {} -- move to new table | ||
117 | assert(table.move({10,20,30}, 1, 3, 1, a) == a) | ||
118 | eqT(a, {10,20,30}) | ||
119 | |||
120 | a = {} | ||
121 | assert(table.move({10,20,30}, 1, 0, 3, a) == a) -- empty move (no move) | ||
122 | eqT(a, {}) | ||
123 | |||
124 | a = table.move({10,20,30}, 1, 10, 1) -- move to the same place | ||
125 | eqT(a, {10,20,30}) | ||
126 | |||
127 | -- moving on the fringes | ||
128 | a = table.move({[maxI - 2] = 1, [maxI - 1] = 2, [maxI] = 3}, | ||
129 | maxI - 2, maxI, -10, {}) | ||
130 | eqT(a, {[-10] = 1, [-9] = 2, [-8] = 3}) | ||
131 | |||
132 | a = table.move({[minI] = 1, [minI + 1] = 2, [minI + 2] = 3}, | ||
133 | minI, minI + 2, -10, {}) | ||
134 | eqT(a, {[-10] = 1, [-9] = 2, [-8] = 3}) | ||
135 | |||
136 | a = table.move({45}, 1, 1, maxI) | ||
137 | eqT(a, {45, [maxI] = 45}) | ||
138 | |||
139 | a = table.move({[maxI] = 100}, maxI, maxI, minI) | ||
140 | eqT(a, {[minI] = 100, [maxI] = 100}) | ||
141 | |||
142 | a = table.move({[minI] = 100}, minI, minI, maxI) | ||
143 | eqT(a, {[minI] = 100, [maxI] = 100}) | ||
144 | |||
145 | a = setmetatable({}, { | ||
146 | __index = function (_,k) return k * 10 end, | ||
147 | __newindex = error}) | ||
148 | local b = table.move(a, 1, 10, 3, {}) | ||
149 | eqT(a, {}) | ||
150 | eqT(b, {nil,nil,10,20,30,40,50,60,70,80,90,100}) | ||
151 | |||
152 | b = setmetatable({""}, { | ||
153 | __index = error, | ||
154 | __newindex = function (t,k,v) | ||
155 | t[1] = string.format("%s(%d,%d)", t[1], k, v) | ||
156 | end}) | ||
157 | table.move(a, 10, 13, 3, b) | ||
158 | assert(b[1] == "(3,100)(4,110)(5,120)(6,130)") | ||
159 | local stat, msg = pcall(table.move, b, 10, 13, 3, b) | ||
160 | assert(not stat and msg == b) | ||
161 | end | ||
162 | |||
163 | do | ||
164 | -- for very long moves, just check initial accesses and interrupt | ||
165 | -- move with an error | ||
166 | local function checkmove (f, e, t, x, y) | ||
167 | local pos1, pos2 | ||
168 | local a = setmetatable({}, { | ||
169 | __index = function (_,k) pos1 = k end, | ||
170 | __newindex = function (_,k) pos2 = k; error() end, }) | ||
171 | local st, msg = pcall(table.move, a, f, e, t) | ||
172 | assert(not st and not msg and pos1 == x and pos2 == y) | ||
173 | end | ||
174 | checkmove(1, maxI, 0, 1, 0) | ||
175 | checkmove(0, maxI - 1, 1, maxI - 1, maxI) | ||
176 | checkmove(minI, -2, -5, -2, maxI - 6) | ||
177 | checkmove(minI + 1, -1, -2, -1, maxI - 3) | ||
178 | checkmove(minI, -2, 0, minI, 0) -- non overlapping | ||
179 | checkmove(minI + 1, -1, 1, minI + 1, 1) -- non overlapping | ||
180 | end | ||
181 | |||
182 | checkerror("too many", table.move, {}, 0, maxI, 1) | ||
183 | checkerror("too many", table.move, {}, -1, maxI - 1, 1) | ||
184 | checkerror("too many", table.move, {}, minI, -1, 1) | ||
185 | checkerror("too many", table.move, {}, minI, maxI, 1) | ||
186 | checkerror("wrap around", table.move, {}, 1, maxI, 2) | ||
187 | checkerror("wrap around", table.move, {}, 1, 2, maxI) | ||
188 | checkerror("wrap around", table.move, {}, minI, -2, 2) | ||
189 | |||
190 | |||
191 | print"testing sort" | ||
192 | |||
193 | |||
194 | -- strange lengths | ||
195 | local a = setmetatable({}, {__len = function () return -1 end}) | ||
196 | assert(#a == -1) | ||
197 | table.sort(a, error) -- should not compare anything | ||
198 | a = setmetatable({}, {__len = function () return maxI end}) | ||
199 | checkerror("too big", table.sort, a) | ||
200 | |||
201 | -- test checks for invalid order functions | ||
202 | local function check (t) | ||
203 | local function f(a, b) assert(a and b); return true end | ||
204 | checkerror("invalid order function", table.sort, t, f) | ||
205 | end | ||
206 | |||
207 | check{1,2,3,4} | ||
208 | check{1,2,3,4,5} | ||
209 | check{1,2,3,4,5,6} | ||
210 | |||
211 | |||
212 | function check (a, f) | ||
213 | f = f or function (x,y) return x<y end; | ||
214 | for n = #a, 2, -1 do | ||
215 | assert(not f(a[n], a[n-1])) | ||
216 | end | ||
217 | end | ||
218 | |||
219 | a = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", | ||
220 | "Oct", "Nov", "Dec"} | ||
221 | |||
222 | table.sort(a) | ||
223 | check(a) | ||
224 | |||
225 | function perm (s, n) | ||
226 | n = n or #s | ||
227 | if n == 1 then | ||
228 | local t = {unpack(s)} | ||
229 | table.sort(t) | ||
230 | check(t) | ||
231 | else | ||
232 | for i = 1, n do | ||
233 | s[i], s[n] = s[n], s[i] | ||
234 | perm(s, n - 1) | ||
235 | s[i], s[n] = s[n], s[i] | ||
236 | end | ||
237 | end | ||
238 | end | ||
239 | |||
240 | perm{} | ||
241 | perm{1} | ||
242 | perm{1,2} | ||
243 | perm{1,2,3} | ||
244 | perm{1,2,3,4} | ||
245 | perm{2,2,3,4} | ||
246 | perm{1,2,3,4,5} | ||
247 | perm{1,2,3,3,5} | ||
248 | perm{1,2,3,4,5,6} | ||
249 | perm{2,2,3,3,5,6} | ||
250 | |||
251 | function timesort (a, n, func, msg, pre) | ||
252 | local x = os.clock() | ||
253 | table.sort(a, func) | ||
254 | x = (os.clock() - x) * 1000 | ||
255 | pre = pre or "" | ||
256 | print(string.format("%ssorting %d %s elements in %.2f msec.", pre, n, msg, x)) | ||
257 | check(a, func) | ||
258 | end | ||
259 | |||
260 | limit = 50000 | ||
261 | if _soft then limit = 5000 end | ||
262 | |||
263 | a = {} | ||
264 | for i=1,limit do | ||
265 | a[i] = math.random() | ||
266 | end | ||
267 | |||
268 | timesort(a, limit, nil, "random") | ||
269 | |||
270 | timesort(a, limit, nil, "sorted", "re-") | ||
271 | |||
272 | a = {} | ||
273 | for i=1,limit do | ||
274 | a[i] = math.random() | ||
275 | end | ||
276 | |||
277 | x = os.clock(); i=0 | ||
278 | table.sort(a, function(x,y) i=i+1; return y<x end) | ||
279 | x = (os.clock() - x) * 1000 | ||
280 | print(string.format("Invert-sorting other %d elements in %.2f msec., with %i comparisons", | ||
281 | limit, x, i)) | ||
282 | check(a, function(x,y) return y<x end) | ||
283 | |||
284 | |||
285 | table.sort{} -- empty array | ||
286 | |||
287 | for i=1,limit do a[i] = false end | ||
288 | timesort(a, limit, function(x,y) return nil end, "equal") | ||
289 | |||
290 | for i,v in pairs(a) do assert(v == false) end | ||
291 | |||
292 | A = {"álo", "\0first :-)", "alo", "then this one", "45", "and a new"} | ||
293 | table.sort(A) | ||
294 | check(A) | ||
295 | |||
296 | table.sort(A, function (x, y) | ||
297 | load(string.format("A[%q] = ''", x), "")() | ||
298 | collectgarbage() | ||
299 | return x<y | ||
300 | end) | ||
301 | |||
302 | |||
303 | tt = {__lt = function (a,b) return a.val < b.val end} | ||
304 | a = {} | ||
305 | for i=1,10 do a[i] = {val=math.random(100)}; setmetatable(a[i], tt); end | ||
306 | table.sort(a) | ||
307 | check(a, tt.__lt) | ||
308 | check(a) | ||
309 | |||
310 | print"OK" | ||
diff --git a/testes/strings.lua b/testes/strings.lua new file mode 100644 index 00000000..dd720b65 --- /dev/null +++ b/testes/strings.lua | |||
@@ -0,0 +1,382 @@ | |||
1 | -- $Id: strings.lua,v 1.89 2018/06/19 12:25:15 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing strings and string library') | ||
5 | |||
6 | local maxi, mini = math.maxinteger, math.mininteger | ||
7 | |||
8 | |||
9 | local function checkerror (msg, f, ...) | ||
10 | local s, err = pcall(f, ...) | ||
11 | assert(not s and string.find(err, msg)) | ||
12 | end | ||
13 | |||
14 | |||
15 | -- testing string comparisons | ||
16 | assert('alo' < 'alo1') | ||
17 | assert('' < 'a') | ||
18 | assert('alo\0alo' < 'alo\0b') | ||
19 | assert('alo\0alo\0\0' > 'alo\0alo\0') | ||
20 | assert('alo' < 'alo\0') | ||
21 | assert('alo\0' > 'alo') | ||
22 | assert('\0' < '\1') | ||
23 | assert('\0\0' < '\0\1') | ||
24 | assert('\1\0a\0a' <= '\1\0a\0a') | ||
25 | assert(not ('\1\0a\0b' <= '\1\0a\0a')) | ||
26 | assert('\0\0\0' < '\0\0\0\0') | ||
27 | assert(not('\0\0\0\0' < '\0\0\0')) | ||
28 | assert('\0\0\0' <= '\0\0\0\0') | ||
29 | assert(not('\0\0\0\0' <= '\0\0\0')) | ||
30 | assert('\0\0\0' <= '\0\0\0') | ||
31 | assert('\0\0\0' >= '\0\0\0') | ||
32 | assert(not ('\0\0b' < '\0\0a\0')) | ||
33 | |||
34 | -- testing string.sub | ||
35 | assert(string.sub("123456789",2,4) == "234") | ||
36 | assert(string.sub("123456789",7) == "789") | ||
37 | assert(string.sub("123456789",7,6) == "") | ||
38 | assert(string.sub("123456789",7,7) == "7") | ||
39 | assert(string.sub("123456789",0,0) == "") | ||
40 | assert(string.sub("123456789",-10,10) == "123456789") | ||
41 | assert(string.sub("123456789",1,9) == "123456789") | ||
42 | assert(string.sub("123456789",-10,-20) == "") | ||
43 | assert(string.sub("123456789",-1) == "9") | ||
44 | assert(string.sub("123456789",-4) == "6789") | ||
45 | assert(string.sub("123456789",-6, -4) == "456") | ||
46 | assert(string.sub("123456789", mini, -4) == "123456") | ||
47 | assert(string.sub("123456789", mini, maxi) == "123456789") | ||
48 | assert(string.sub("123456789", mini, mini) == "") | ||
49 | assert(string.sub("\000123456789",3,5) == "234") | ||
50 | assert(("\000123456789"):sub(8) == "789") | ||
51 | |||
52 | -- testing string.find | ||
53 | assert(string.find("123456789", "345") == 3) | ||
54 | a,b = string.find("123456789", "345") | ||
55 | assert(string.sub("123456789", a, b) == "345") | ||
56 | assert(string.find("1234567890123456789", "345", 3) == 3) | ||
57 | assert(string.find("1234567890123456789", "345", 4) == 13) | ||
58 | assert(string.find("1234567890123456789", "346", 4) == nil) | ||
59 | assert(string.find("1234567890123456789", ".45", -9) == 13) | ||
60 | assert(string.find("abcdefg", "\0", 5, 1) == nil) | ||
61 | assert(string.find("", "") == 1) | ||
62 | assert(string.find("", "", 1) == 1) | ||
63 | assert(not string.find("", "", 2)) | ||
64 | assert(string.find('', 'aaa', 1) == nil) | ||
65 | assert(('alo(.)alo'):find('(.)', 1, 1) == 4) | ||
66 | |||
67 | assert(string.len("") == 0) | ||
68 | assert(string.len("\0\0\0") == 3) | ||
69 | assert(string.len("1234567890") == 10) | ||
70 | |||
71 | assert(#"" == 0) | ||
72 | assert(#"\0\0\0" == 3) | ||
73 | assert(#"1234567890" == 10) | ||
74 | |||
75 | -- testing string.byte/string.char | ||
76 | assert(string.byte("a") == 97) | ||
77 | assert(string.byte("\xe4") > 127) | ||
78 | assert(string.byte(string.char(255)) == 255) | ||
79 | assert(string.byte(string.char(0)) == 0) | ||
80 | assert(string.byte("\0") == 0) | ||
81 | assert(string.byte("\0\0alo\0x", -1) == string.byte('x')) | ||
82 | assert(string.byte("ba", 2) == 97) | ||
83 | assert(string.byte("\n\n", 2, -1) == 10) | ||
84 | assert(string.byte("\n\n", 2, 2) == 10) | ||
85 | assert(string.byte("") == nil) | ||
86 | assert(string.byte("hi", -3) == nil) | ||
87 | assert(string.byte("hi", 3) == nil) | ||
88 | assert(string.byte("hi", 9, 10) == nil) | ||
89 | assert(string.byte("hi", 2, 1) == nil) | ||
90 | assert(string.char() == "") | ||
91 | assert(string.char(0, 255, 0) == "\0\255\0") | ||
92 | assert(string.char(0, string.byte("\xe4"), 0) == "\0\xe4\0") | ||
93 | assert(string.char(string.byte("\xe4l\0óu", 1, -1)) == "\xe4l\0óu") | ||
94 | assert(string.char(string.byte("\xe4l\0óu", 1, 0)) == "") | ||
95 | assert(string.char(string.byte("\xe4l\0óu", -10, 100)) == "\xe4l\0óu") | ||
96 | |||
97 | assert(string.upper("ab\0c") == "AB\0C") | ||
98 | assert(string.lower("\0ABCc%$") == "\0abcc%$") | ||
99 | assert(string.rep('teste', 0) == '') | ||
100 | assert(string.rep('tés\00tê', 2) == 'tés\0têtés\000tê') | ||
101 | assert(string.rep('', 10) == '') | ||
102 | |||
103 | if string.packsize("i") == 4 then | ||
104 | -- result length would be 2^31 (int overflow) | ||
105 | checkerror("too large", string.rep, 'aa', (1 << 30)) | ||
106 | checkerror("too large", string.rep, 'a', (1 << 30), ',') | ||
107 | end | ||
108 | |||
109 | -- repetitions with separator | ||
110 | assert(string.rep('teste', 0, 'xuxu') == '') | ||
111 | assert(string.rep('teste', 1, 'xuxu') == 'teste') | ||
112 | assert(string.rep('\1\0\1', 2, '\0\0') == '\1\0\1\0\0\1\0\1') | ||
113 | assert(string.rep('', 10, '.') == string.rep('.', 9)) | ||
114 | assert(not pcall(string.rep, "aa", maxi // 2 + 10)) | ||
115 | assert(not pcall(string.rep, "", maxi // 2 + 10, "aa")) | ||
116 | |||
117 | assert(string.reverse"" == "") | ||
118 | assert(string.reverse"\0\1\2\3" == "\3\2\1\0") | ||
119 | assert(string.reverse"\0001234" == "4321\0") | ||
120 | |||
121 | for i=0,30 do assert(string.len(string.rep('a', i)) == i) end | ||
122 | |||
123 | assert(type(tostring(nil)) == 'string') | ||
124 | assert(type(tostring(12)) == 'string') | ||
125 | assert(string.find(tostring{}, 'table:')) | ||
126 | assert(string.find(tostring(print), 'function:')) | ||
127 | assert(#tostring('\0') == 1) | ||
128 | assert(tostring(true) == "true") | ||
129 | assert(tostring(false) == "false") | ||
130 | assert(tostring(-1203) == "-1203") | ||
131 | assert(tostring(1203.125) == "1203.125") | ||
132 | assert(tostring(-0.5) == "-0.5") | ||
133 | assert(tostring(-32767) == "-32767") | ||
134 | if math.tointeger(2147483647) then -- no overflow? (32 bits) | ||
135 | assert(tostring(-2147483647) == "-2147483647") | ||
136 | end | ||
137 | if math.tointeger(4611686018427387904) then -- no overflow? (64 bits) | ||
138 | assert(tostring(4611686018427387904) == "4611686018427387904") | ||
139 | assert(tostring(-4611686018427387904) == "-4611686018427387904") | ||
140 | end | ||
141 | |||
142 | if tostring(0.0) == "0.0" then -- "standard" coercion float->string | ||
143 | assert('' .. 12 == '12' and 12.0 .. '' == '12.0') | ||
144 | assert(tostring(-1203 + 0.0) == "-1203.0") | ||
145 | else -- compatible coercion | ||
146 | assert(tostring(0.0) == "0") | ||
147 | assert('' .. 12 == '12' and 12.0 .. '' == '12') | ||
148 | assert(tostring(-1203 + 0.0) == "-1203") | ||
149 | end | ||
150 | |||
151 | |||
152 | x = '"ílo"\n\\' | ||
153 | assert(string.format('%q%s', x, x) == '"\\"ílo\\"\\\n\\\\""ílo"\n\\') | ||
154 | assert(string.format('%q', "\0") == [["\0"]]) | ||
155 | assert(load(string.format('return %q', x))() == x) | ||
156 | x = "\0\1\0023\5\0009" | ||
157 | assert(load(string.format('return %q', x))() == x) | ||
158 | assert(string.format("\0%c\0%c%x\0", string.byte("\xe4"), string.byte("b"), 140) == | ||
159 | "\0\xe4\0b8c\0") | ||
160 | assert(string.format('') == "") | ||
161 | assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) == | ||
162 | string.format("%c%c%c%c", 34, 48, 90, 100)) | ||
163 | assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be') | ||
164 | assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023") | ||
165 | assert(tonumber(string.format("%f", 10.3)) == 10.3) | ||
166 | x = string.format('"%-50s"', 'a') | ||
167 | assert(#x == 52) | ||
168 | assert(string.sub(x, 1, 4) == '"a ') | ||
169 | |||
170 | assert(string.format("-%.20s.20s", string.rep("%", 2000)) == | ||
171 | "-"..string.rep("%", 20)..".20s") | ||
172 | assert(string.format('"-%20s.20s"', string.rep("%", 2000)) == | ||
173 | string.format("%q", "-"..string.rep("%", 2000)..".20s")) | ||
174 | |||
175 | do | ||
176 | local function checkQ (v) | ||
177 | local s = string.format("%q", v) | ||
178 | local nv = load("return " .. s)() | ||
179 | assert(v == nv and math.type(v) == math.type(nv)) | ||
180 | end | ||
181 | checkQ("\0\0\1\255\u{234}") | ||
182 | checkQ(math.maxinteger) | ||
183 | checkQ(math.mininteger) | ||
184 | checkQ(math.pi) | ||
185 | checkQ(0.1) | ||
186 | checkQ(true) | ||
187 | checkQ(nil) | ||
188 | checkQ(false) | ||
189 | checkQ(math.huge) | ||
190 | checkQ(-math.huge) | ||
191 | assert(string.format("%q", 0/0) == "(0/0)") -- NaN | ||
192 | checkerror("no literal", string.format, "%q", {}) | ||
193 | end | ||
194 | |||
195 | assert(string.format("\0%s\0", "\0\0\1") == "\0\0\0\1\0") | ||
196 | checkerror("contains zeros", string.format, "%10s", "\0") | ||
197 | |||
198 | -- format x tostring | ||
199 | assert(string.format("%s %s", nil, true) == "nil true") | ||
200 | assert(string.format("%s %.4s", false, true) == "false true") | ||
201 | assert(string.format("%.3s %.3s", false, true) == "fal tru") | ||
202 | local m = setmetatable({}, {__tostring = function () return "hello" end, | ||
203 | __name = "hi"}) | ||
204 | assert(string.format("%s %.10s", m, m) == "hello hello") | ||
205 | getmetatable(m).__tostring = nil -- will use '__name' from now on | ||
206 | assert(string.format("%.4s", m) == "hi: ") | ||
207 | |||
208 | getmetatable(m).__tostring = function () return {} end | ||
209 | checkerror("'__tostring' must return a string", tostring, m) | ||
210 | |||
211 | |||
212 | assert(string.format("%x", 0.0) == "0") | ||
213 | assert(string.format("%02x", 0.0) == "00") | ||
214 | assert(string.format("%08X", 0xFFFFFFFF) == "FFFFFFFF") | ||
215 | assert(string.format("%+08d", 31501) == "+0031501") | ||
216 | assert(string.format("%+08d", -30927) == "-0030927") | ||
217 | |||
218 | |||
219 | do -- longest number that can be formatted | ||
220 | local i = 1 | ||
221 | local j = 10000 | ||
222 | while i + 1 < j do -- binary search for maximum finite float | ||
223 | local m = (i + j) // 2 | ||
224 | if 10^m < math.huge then i = m else j = m end | ||
225 | end | ||
226 | assert(10^i < math.huge and 10^j == math.huge) | ||
227 | local s = string.format('%.99f', -(10^i)) | ||
228 | assert(string.len(s) >= i + 101) | ||
229 | assert(tonumber(s) == -(10^i)) | ||
230 | end | ||
231 | |||
232 | |||
233 | -- testing large numbers for format | ||
234 | do -- assume at least 32 bits | ||
235 | local max, min = 0x7fffffff, -0x80000000 -- "large" for 32 bits | ||
236 | assert(string.sub(string.format("%8x", -1), -8) == "ffffffff") | ||
237 | assert(string.format("%x", max) == "7fffffff") | ||
238 | assert(string.sub(string.format("%x", min), -8) == "80000000") | ||
239 | assert(string.format("%d", max) == "2147483647") | ||
240 | assert(string.format("%d", min) == "-2147483648") | ||
241 | assert(string.format("%u", 0xffffffff) == "4294967295") | ||
242 | assert(string.format("%o", 0xABCD) == "125715") | ||
243 | |||
244 | max, min = 0x7fffffffffffffff, -0x8000000000000000 | ||
245 | if max > 2.0^53 then -- only for 64 bits | ||
246 | assert(string.format("%x", (2^52 | 0) - 1) == "fffffffffffff") | ||
247 | assert(string.format("0x%8X", 0x8f000003) == "0x8F000003") | ||
248 | assert(string.format("%d", 2^53) == "9007199254740992") | ||
249 | assert(string.format("%i", -2^53) == "-9007199254740992") | ||
250 | assert(string.format("%x", max) == "7fffffffffffffff") | ||
251 | assert(string.format("%x", min) == "8000000000000000") | ||
252 | assert(string.format("%d", max) == "9223372036854775807") | ||
253 | assert(string.format("%d", min) == "-9223372036854775808") | ||
254 | assert(string.format("%u", ~(-1 << 64)) == "18446744073709551615") | ||
255 | assert(tostring(1234567890123) == '1234567890123') | ||
256 | end | ||
257 | end | ||
258 | |||
259 | |||
260 | do print("testing 'format %a %A'") | ||
261 | local function matchhexa (n) | ||
262 | local s = string.format("%a", n) | ||
263 | -- result matches ISO C requirements | ||
264 | assert(string.find(s, "^%-?0x[1-9a-f]%.?[0-9a-f]*p[-+]?%d+$")) | ||
265 | assert(tonumber(s) == n) -- and has full precision | ||
266 | s = string.format("%A", n) | ||
267 | assert(string.find(s, "^%-?0X[1-9A-F]%.?[0-9A-F]*P[-+]?%d+$")) | ||
268 | assert(tonumber(s) == n) | ||
269 | end | ||
270 | for _, n in ipairs{0.1, -0.1, 1/3, -1/3, 1e30, -1e30, | ||
271 | -45/247, 1, -1, 2, -2, 3e-20, -3e-20} do | ||
272 | matchhexa(n) | ||
273 | end | ||
274 | |||
275 | assert(string.find(string.format("%A", 0.0), "^0X0%.?0?P%+?0$")) | ||
276 | assert(string.find(string.format("%a", -0.0), "^%-0x0%.?0?p%+?0$")) | ||
277 | |||
278 | if not _port then -- test inf, -inf, NaN, and -0.0 | ||
279 | assert(string.find(string.format("%a", 1/0), "^inf")) | ||
280 | assert(string.find(string.format("%A", -1/0), "^%-INF")) | ||
281 | assert(string.find(string.format("%a", 0/0), "^%-?nan")) | ||
282 | assert(string.find(string.format("%a", -0.0), "^%-0x0")) | ||
283 | end | ||
284 | |||
285 | if not pcall(string.format, "%.3a", 0) then | ||
286 | (Message or print)("\n >>> modifiers for format '%a' not available <<<\n") | ||
287 | else | ||
288 | assert(string.find(string.format("%+.2A", 12), "^%+0X%x%.%x0P%+?%d$")) | ||
289 | assert(string.find(string.format("%.4A", -12), "^%-0X%x%.%x000P%+?%d$")) | ||
290 | end | ||
291 | end | ||
292 | |||
293 | |||
294 | -- errors in format | ||
295 | |||
296 | local function check (fmt, msg) | ||
297 | checkerror(msg, string.format, fmt, 10) | ||
298 | end | ||
299 | |||
300 | local aux = string.rep('0', 600) | ||
301 | check("%100.3d", "too long") | ||
302 | check("%1"..aux..".3d", "too long") | ||
303 | check("%1.100d", "too long") | ||
304 | check("%10.1"..aux.."004d", "too long") | ||
305 | check("%t", "invalid option") | ||
306 | check("%"..aux.."d", "repeated flags") | ||
307 | check("%d %d", "no value") | ||
308 | |||
309 | |||
310 | assert(load("return 1\n--comment without ending EOL")() == 1) | ||
311 | |||
312 | |||
313 | checkerror("table expected", table.concat, 3) | ||
314 | assert(table.concat{} == "") | ||
315 | assert(table.concat({}, 'x') == "") | ||
316 | assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2") | ||
317 | local a = {}; for i=1,300 do a[i] = "xuxu" end | ||
318 | assert(table.concat(a, "123").."123" == string.rep("xuxu123", 300)) | ||
319 | assert(table.concat(a, "b", 20, 20) == "xuxu") | ||
320 | assert(table.concat(a, "", 20, 21) == "xuxuxuxu") | ||
321 | assert(table.concat(a, "x", 22, 21) == "") | ||
322 | assert(table.concat(a, "3", 299) == "xuxu3xuxu") | ||
323 | assert(table.concat({}, "x", maxi, maxi - 1) == "") | ||
324 | assert(table.concat({}, "x", mini + 1, mini) == "") | ||
325 | assert(table.concat({}, "x", maxi, mini) == "") | ||
326 | assert(table.concat({[maxi] = "alo"}, "x", maxi, maxi) == "alo") | ||
327 | assert(table.concat({[maxi] = "alo", [maxi - 1] = "y"}, "-", maxi - 1, maxi) | ||
328 | == "y-alo") | ||
329 | |||
330 | assert(not pcall(table.concat, {"a", "b", {}})) | ||
331 | |||
332 | a = {"a","b","c"} | ||
333 | assert(table.concat(a, ",", 1, 0) == "") | ||
334 | assert(table.concat(a, ",", 1, 1) == "a") | ||
335 | assert(table.concat(a, ",", 1, 2) == "a,b") | ||
336 | assert(table.concat(a, ",", 2) == "b,c") | ||
337 | assert(table.concat(a, ",", 3) == "c") | ||
338 | assert(table.concat(a, ",", 4) == "") | ||
339 | |||
340 | if not _port then | ||
341 | |||
342 | local locales = { "ptb", "pt_BR.iso88591", "ISO-8859-1" } | ||
343 | local function trylocale (w) | ||
344 | for i = 1, #locales do | ||
345 | if os.setlocale(locales[i], w) then | ||
346 | print(string.format("'%s' locale set to '%s'", w, locales[i])) | ||
347 | return locales[i] | ||
348 | end | ||
349 | end | ||
350 | print(string.format("'%s' locale not found", w)) | ||
351 | return false | ||
352 | end | ||
353 | |||
354 | if trylocale("collate") then | ||
355 | assert("alo" < "álo" and "álo" < "amo") | ||
356 | end | ||
357 | |||
358 | if trylocale("ctype") then | ||
359 | assert(string.gsub("áéíóú", "%a", "x") == "xxxxx") | ||
360 | assert(string.gsub("áÁéÉ", "%l", "x") == "xÁxÉ") | ||
361 | assert(string.gsub("áÁéÉ", "%u", "x") == "áxéx") | ||
362 | assert(string.upper"áÁé{xuxu}ção" == "ÁÁÉ{XUXU}ÇÃO") | ||
363 | end | ||
364 | |||
365 | os.setlocale("C") | ||
366 | assert(os.setlocale() == 'C') | ||
367 | assert(os.setlocale(nil, "numeric") == 'C') | ||
368 | |||
369 | end | ||
370 | |||
371 | |||
372 | -- bug in Lua 5.3.2 | ||
373 | -- 'gmatch' iterator does not work across coroutines | ||
374 | do | ||
375 | local f = string.gmatch("1 2 3 4 5", "%d+") | ||
376 | assert(f() == "1") | ||
377 | co = coroutine.wrap(f) | ||
378 | assert(co() == "2") | ||
379 | end | ||
380 | |||
381 | print('OK') | ||
382 | |||
diff --git a/testes/tpack.lua b/testes/tpack.lua new file mode 100644 index 00000000..0e639cc5 --- /dev/null +++ b/testes/tpack.lua | |||
@@ -0,0 +1,324 @@ | |||
1 | -- $Id: tpack.lua,v 1.14 2018/06/04 14:26:32 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | local pack = string.pack | ||
5 | local packsize = string.packsize | ||
6 | local unpack = string.unpack | ||
7 | |||
8 | print "testing pack/unpack" | ||
9 | |||
10 | -- maximum size for integers | ||
11 | local NB = 16 | ||
12 | |||
13 | local sizeshort = packsize("h") | ||
14 | local sizeint = packsize("i") | ||
15 | local sizelong = packsize("l") | ||
16 | local sizesize_t = packsize("T") | ||
17 | local sizeLI = packsize("j") | ||
18 | local sizefloat = packsize("f") | ||
19 | local sizedouble = packsize("d") | ||
20 | local sizenumber = packsize("n") | ||
21 | local little = (pack("i2", 1) == "\1\0") | ||
22 | local align = packsize("!xXi16") | ||
23 | |||
24 | assert(1 <= sizeshort and sizeshort <= sizeint and sizeint <= sizelong and | ||
25 | sizefloat <= sizedouble) | ||
26 | |||
27 | print("platform:") | ||
28 | print(string.format( | ||
29 | "\tshort %d, int %d, long %d, size_t %d, float %d, double %d,\n\z | ||
30 | \tlua Integer %d, lua Number %d", | ||
31 | sizeshort, sizeint, sizelong, sizesize_t, sizefloat, sizedouble, | ||
32 | sizeLI, sizenumber)) | ||
33 | print("\t" .. (little and "little" or "big") .. " endian") | ||
34 | print("\talignment: " .. align) | ||
35 | |||
36 | |||
37 | -- check errors in arguments | ||
38 | function checkerror (msg, f, ...) | ||
39 | local status, err = pcall(f, ...) | ||
40 | -- print(status, err, msg) | ||
41 | assert(not status and string.find(err, msg)) | ||
42 | end | ||
43 | |||
44 | -- minimum behavior for integer formats | ||
45 | assert(unpack("B", pack("B", 0xff)) == 0xff) | ||
46 | assert(unpack("b", pack("b", 0x7f)) == 0x7f) | ||
47 | assert(unpack("b", pack("b", -0x80)) == -0x80) | ||
48 | |||
49 | assert(unpack("H", pack("H", 0xffff)) == 0xffff) | ||
50 | assert(unpack("h", pack("h", 0x7fff)) == 0x7fff) | ||
51 | assert(unpack("h", pack("h", -0x8000)) == -0x8000) | ||
52 | |||
53 | assert(unpack("L", pack("L", 0xffffffff)) == 0xffffffff) | ||
54 | assert(unpack("l", pack("l", 0x7fffffff)) == 0x7fffffff) | ||
55 | assert(unpack("l", pack("l", -0x80000000)) == -0x80000000) | ||
56 | |||
57 | |||
58 | for i = 1, NB do | ||
59 | -- small numbers with signal extension ("\xFF...") | ||
60 | local s = string.rep("\xff", i) | ||
61 | assert(pack("i" .. i, -1) == s) | ||
62 | assert(packsize("i" .. i) == #s) | ||
63 | assert(unpack("i" .. i, s) == -1) | ||
64 | |||
65 | -- small unsigned number ("\0...\xAA") | ||
66 | s = "\xAA" .. string.rep("\0", i - 1) | ||
67 | assert(pack("<I" .. i, 0xAA) == s) | ||
68 | assert(unpack("<I" .. i, s) == 0xAA) | ||
69 | assert(pack(">I" .. i, 0xAA) == s:reverse()) | ||
70 | assert(unpack(">I" .. i, s:reverse()) == 0xAA) | ||
71 | end | ||
72 | |||
73 | do | ||
74 | local lnum = 0x13121110090807060504030201 | ||
75 | local s = pack("<j", lnum) | ||
76 | assert(unpack("<j", s) == lnum) | ||
77 | assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum) | ||
78 | assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum) | ||
79 | |||
80 | for i = sizeLI + 1, NB do | ||
81 | local s = pack("<j", -lnum) | ||
82 | assert(unpack("<j", s) == -lnum) | ||
83 | -- strings with (correct) extra bytes | ||
84 | assert(unpack("<i" .. i, s .. ("\xFF"):rep(i - sizeLI)) == -lnum) | ||
85 | assert(unpack(">i" .. i, ("\xFF"):rep(i - sizeLI) .. s:reverse()) == -lnum) | ||
86 | assert(unpack("<I" .. i, s .. ("\0"):rep(i - sizeLI)) == -lnum) | ||
87 | |||
88 | -- overflows | ||
89 | checkerror("does not fit", unpack, "<I" .. i, ("\x00"):rep(i - 1) .. "\1") | ||
90 | checkerror("does not fit", unpack, ">i" .. i, "\1" .. ("\x00"):rep(i - 1)) | ||
91 | end | ||
92 | end | ||
93 | |||
94 | for i = 1, sizeLI do | ||
95 | local lstr = "\1\2\3\4\5\6\7\8\9\10\11\12\13" | ||
96 | local lnum = 0x13121110090807060504030201 | ||
97 | local n = lnum & (~(-1 << (i * 8))) | ||
98 | local s = string.sub(lstr, 1, i) | ||
99 | assert(pack("<i" .. i, n) == s) | ||
100 | assert(pack(">i" .. i, n) == s:reverse()) | ||
101 | assert(unpack(">i" .. i, s:reverse()) == n) | ||
102 | end | ||
103 | |||
104 | -- sign extension | ||
105 | do | ||
106 | local u = 0xf0 | ||
107 | for i = 1, sizeLI - 1 do | ||
108 | assert(unpack("<i"..i, "\xf0"..("\xff"):rep(i - 1)) == -16) | ||
109 | assert(unpack(">I"..i, "\xf0"..("\xff"):rep(i - 1)) == u) | ||
110 | u = u * 256 + 0xff | ||
111 | end | ||
112 | end | ||
113 | |||
114 | -- mixed endianness | ||
115 | do | ||
116 | assert(pack(">i2 <i2", 10, 20) == "\0\10\20\0") | ||
117 | local a, b = unpack("<i2 >i2", "\10\0\0\20") | ||
118 | assert(a == 10 and b == 20) | ||
119 | assert(pack("=i4", 2001) == pack("i4", 2001)) | ||
120 | end | ||
121 | |||
122 | print("testing invalid formats") | ||
123 | |||
124 | checkerror("out of limits", pack, "i0", 0) | ||
125 | checkerror("out of limits", pack, "i" .. NB + 1, 0) | ||
126 | checkerror("out of limits", pack, "!" .. NB + 1, 0) | ||
127 | checkerror("%(17%) out of limits %[1,16%]", pack, "Xi" .. NB + 1) | ||
128 | checkerror("invalid format option 'r'", pack, "i3r", 0) | ||
129 | checkerror("16%-byte integer", unpack, "i16", string.rep('\3', 16)) | ||
130 | checkerror("not power of 2", pack, "!4i3", 0); | ||
131 | checkerror("missing size", pack, "c", "") | ||
132 | checkerror("variable%-length format", packsize, "s") | ||
133 | checkerror("variable%-length format", packsize, "z") | ||
134 | |||
135 | -- overflow in option size (error will be in digit after limit) | ||
136 | checkerror("invalid format", packsize, "c1" .. string.rep("0", 40)) | ||
137 | |||
138 | if packsize("i") == 4 then | ||
139 | -- result would be 2^31 (2^3 repetitions of 2^28 strings) | ||
140 | local s = string.rep("c268435456", 2^3) | ||
141 | checkerror("too large", packsize, s) | ||
142 | -- one less is OK | ||
143 | s = string.rep("c268435456", 2^3 - 1) .. "c268435455" | ||
144 | assert(packsize(s) == 0x7fffffff) | ||
145 | end | ||
146 | |||
147 | -- overflow in packing | ||
148 | for i = 1, sizeLI - 1 do | ||
149 | local umax = (1 << (i * 8)) - 1 | ||
150 | local max = umax >> 1 | ||
151 | local min = ~max | ||
152 | checkerror("overflow", pack, "<I" .. i, -1) | ||
153 | checkerror("overflow", pack, "<I" .. i, min) | ||
154 | checkerror("overflow", pack, ">I" .. i, umax + 1) | ||
155 | |||
156 | checkerror("overflow", pack, ">i" .. i, umax) | ||
157 | checkerror("overflow", pack, ">i" .. i, max + 1) | ||
158 | checkerror("overflow", pack, "<i" .. i, min - 1) | ||
159 | |||
160 | assert(unpack(">i" .. i, pack(">i" .. i, max)) == max) | ||
161 | assert(unpack("<i" .. i, pack("<i" .. i, min)) == min) | ||
162 | assert(unpack(">I" .. i, pack(">I" .. i, umax)) == umax) | ||
163 | end | ||
164 | |||
165 | -- Lua integer size | ||
166 | assert(unpack(">j", pack(">j", math.maxinteger)) == math.maxinteger) | ||
167 | assert(unpack("<j", pack("<j", math.mininteger)) == math.mininteger) | ||
168 | assert(unpack("<J", pack("<j", -1)) == -1) -- maximum unsigned integer | ||
169 | |||
170 | if little then | ||
171 | assert(pack("f", 24) == pack("<f", 24)) | ||
172 | else | ||
173 | assert(pack("f", 24) == pack(">f", 24)) | ||
174 | end | ||
175 | |||
176 | print "testing pack/unpack of floating-point numbers" | ||
177 | |||
178 | for _, n in ipairs{0, -1.1, 1.9, 1/0, -1/0, 1e20, -1e20, 0.1, 2000.7} do | ||
179 | assert(unpack("n", pack("n", n)) == n) | ||
180 | assert(unpack("<n", pack("<n", n)) == n) | ||
181 | assert(unpack(">n", pack(">n", n)) == n) | ||
182 | assert(pack("<f", n) == pack(">f", n):reverse()) | ||
183 | assert(pack(">d", n) == pack("<d", n):reverse()) | ||
184 | end | ||
185 | |||
186 | -- for non-native precisions, test only with "round" numbers | ||
187 | for _, n in ipairs{0, -1.5, 1/0, -1/0, 1e10, -1e9, 0.5, 2000.25} do | ||
188 | assert(unpack("<f", pack("<f", n)) == n) | ||
189 | assert(unpack(">f", pack(">f", n)) == n) | ||
190 | assert(unpack("<d", pack("<d", n)) == n) | ||
191 | assert(unpack(">d", pack(">d", n)) == n) | ||
192 | end | ||
193 | |||
194 | print "testing pack/unpack of strings" | ||
195 | do | ||
196 | local s = string.rep("abc", 1000) | ||
197 | assert(pack("zB", s, 247) == s .. "\0\xF7") | ||
198 | local s1, b = unpack("zB", s .. "\0\xF9") | ||
199 | assert(b == 249 and s1 == s) | ||
200 | s1 = pack("s", s) | ||
201 | assert(unpack("s", s1) == s) | ||
202 | |||
203 | checkerror("does not fit", pack, "s1", s) | ||
204 | |||
205 | checkerror("contains zeros", pack, "z", "alo\0"); | ||
206 | |||
207 | checkerror("unfinished string", unpack, "zc10000000", "alo") | ||
208 | |||
209 | for i = 2, NB do | ||
210 | local s1 = pack("s" .. i, s) | ||
211 | assert(unpack("s" .. i, s1) == s and #s1 == #s + i) | ||
212 | end | ||
213 | end | ||
214 | |||
215 | do | ||
216 | local x = pack("s", "alo") | ||
217 | checkerror("too short", unpack, "s", x:sub(1, -2)) | ||
218 | checkerror("too short", unpack, "c5", "abcd") | ||
219 | checkerror("out of limits", pack, "s100", "alo") | ||
220 | end | ||
221 | |||
222 | do | ||
223 | assert(pack("c0", "") == "") | ||
224 | assert(packsize("c0") == 0) | ||
225 | assert(unpack("c0", "") == "") | ||
226 | assert(pack("<! c3", "abc") == "abc") | ||
227 | assert(packsize("<! c3") == 3) | ||
228 | assert(pack(">!4 c6", "abcdef") == "abcdef") | ||
229 | assert(pack("c3", "123") == "123") | ||
230 | assert(pack("c0", "") == "") | ||
231 | assert(pack("c8", "123456") == "123456\0\0") | ||
232 | assert(pack("c88", "") == string.rep("\0", 88)) | ||
233 | assert(pack("c188", "ab") == "ab" .. string.rep("\0", 188 - 2)) | ||
234 | local a, b, c = unpack("!4 z c3", "abcdefghi\0xyz") | ||
235 | assert(a == "abcdefghi" and b == "xyz" and c == 14) | ||
236 | checkerror("longer than", pack, "c3", "1234") | ||
237 | end | ||
238 | |||
239 | |||
240 | -- testing multiple types and sequence | ||
241 | do | ||
242 | local x = pack("<b h b f d f n i", 1, 2, 3, 4, 5, 6, 7, 8) | ||
243 | assert(#x == packsize("<b h b f d f n i")) | ||
244 | local a, b, c, d, e, f, g, h = unpack("<b h b f d f n i", x) | ||
245 | assert(a == 1 and b == 2 and c == 3 and d == 4 and e == 5 and f == 6 and | ||
246 | g == 7 and h == 8) | ||
247 | end | ||
248 | |||
249 | print "testing alignment" | ||
250 | do | ||
251 | assert(pack(" < i1 i2 ", 2, 3) == "\2\3\0") -- no alignment by default | ||
252 | local x = pack(">!8 b Xh i4 i8 c1 Xi8", -12, 100, 200, "\xEC") | ||
253 | assert(#x == packsize(">!8 b Xh i4 i8 c1 Xi8")) | ||
254 | assert(x == "\xf4" .. "\0\0\0" .. | ||
255 | "\0\0\0\100" .. | ||
256 | "\0\0\0\0\0\0\0\xC8" .. | ||
257 | "\xEC" .. "\0\0\0\0\0\0\0") | ||
258 | local a, b, c, d, pos = unpack(">!8 c1 Xh i4 i8 b Xi8 XI XH", x) | ||
259 | assert(a == "\xF4" and b == 100 and c == 200 and d == -20 and (pos - 1) == #x) | ||
260 | |||
261 | x = pack(">!4 c3 c4 c2 z i4 c5 c2 Xi4", | ||
262 | "abc", "abcd", "xz", "hello", 5, "world", "xy") | ||
263 | assert(x == "abcabcdxzhello\0\0\0\0\0\5worldxy\0") | ||
264 | local a, b, c, d, e, f, g, pos = unpack(">!4 c3 c4 c2 z i4 c5 c2 Xh Xi4", x) | ||
265 | assert(a == "abc" and b == "abcd" and c == "xz" and d == "hello" and | ||
266 | e == 5 and f == "world" and g == "xy" and (pos - 1) % 4 == 0) | ||
267 | |||
268 | x = pack(" b b Xd b Xb x", 1, 2, 3) | ||
269 | assert(packsize(" b b Xd b Xb x") == 4) | ||
270 | assert(x == "\1\2\3\0") | ||
271 | a, b, c, pos = unpack("bbXdb", x) | ||
272 | assert(a == 1 and b == 2 and c == 3 and pos == #x) | ||
273 | |||
274 | -- only alignment | ||
275 | assert(packsize("!8 xXi8") == 8) | ||
276 | local pos = unpack("!8 xXi8", "0123456701234567"); assert(pos == 9) | ||
277 | assert(packsize("!8 xXi2") == 2) | ||
278 | local pos = unpack("!8 xXi2", "0123456701234567"); assert(pos == 3) | ||
279 | assert(packsize("!2 xXi2") == 2) | ||
280 | local pos = unpack("!2 xXi2", "0123456701234567"); assert(pos == 3) | ||
281 | assert(packsize("!2 xXi8") == 2) | ||
282 | local pos = unpack("!2 xXi8", "0123456701234567"); assert(pos == 3) | ||
283 | assert(packsize("!16 xXi16") == 16) | ||
284 | local pos = unpack("!16 xXi16", "0123456701234567"); assert(pos == 17) | ||
285 | |||
286 | checkerror("invalid next option", pack, "X") | ||
287 | checkerror("invalid next option", unpack, "XXi", "") | ||
288 | checkerror("invalid next option", unpack, "X i", "") | ||
289 | checkerror("invalid next option", pack, "Xc1") | ||
290 | end | ||
291 | |||
292 | do -- testing initial position | ||
293 | local x = pack("i4i4i4i4", 1, 2, 3, 4) | ||
294 | for pos = 1, 16, 4 do | ||
295 | local i, p = unpack("i4", x, pos) | ||
296 | assert(i == pos//4 + 1 and p == pos + 4) | ||
297 | end | ||
298 | |||
299 | -- with alignment | ||
300 | for pos = 0, 12 do -- will always round position to power of 2 | ||
301 | local i, p = unpack("!4 i4", x, pos + 1) | ||
302 | assert(i == (pos + 3)//4 + 1 and p == i*4 + 1) | ||
303 | end | ||
304 | |||
305 | -- negative indices | ||
306 | local i, p = unpack("!4 i4", x, -4) | ||
307 | assert(i == 4 and p == 17) | ||
308 | local i, p = unpack("!4 i4", x, -7) | ||
309 | assert(i == 4 and p == 17) | ||
310 | local i, p = unpack("!4 i4", x, -#x) | ||
311 | assert(i == 1 and p == 5) | ||
312 | |||
313 | -- limits | ||
314 | for i = 1, #x + 1 do | ||
315 | assert(unpack("c0", x, i) == "") | ||
316 | end | ||
317 | checkerror("out of string", unpack, "c0", x, 0) | ||
318 | checkerror("out of string", unpack, "c0", x, #x + 2) | ||
319 | checkerror("out of string", unpack, "c0", x, -(#x + 1)) | ||
320 | |||
321 | end | ||
322 | |||
323 | print "OK" | ||
324 | |||
diff --git a/testes/utf8.lua b/testes/utf8.lua new file mode 100644 index 00000000..ebc190b7 --- /dev/null +++ b/testes/utf8.lua | |||
@@ -0,0 +1,210 @@ | |||
1 | -- $Id: utf8.lua,v 1.12 2016/11/07 13:11:28 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print "testing UTF-8 library" | ||
5 | |||
6 | local utf8 = require'utf8' | ||
7 | |||
8 | |||
9 | local function checkerror (msg, f, ...) | ||
10 | local s, err = pcall(f, ...) | ||
11 | assert(not s and string.find(err, msg)) | ||
12 | end | ||
13 | |||
14 | |||
15 | local function len (s) | ||
16 | return #string.gsub(s, "[\x80-\xBF]", "") | ||
17 | end | ||
18 | |||
19 | |||
20 | local justone = "^" .. utf8.charpattern .. "$" | ||
21 | |||
22 | -- 't' is the list of codepoints of 's' | ||
23 | local function checksyntax (s, t) | ||
24 | local ts = {"return '"} | ||
25 | for i = 1, #t do ts[i + 1] = string.format("\\u{%x}", t[i]) end | ||
26 | ts[#t + 2] = "'" | ||
27 | ts = table.concat(ts) | ||
28 | assert(assert(load(ts))() == s) | ||
29 | end | ||
30 | |||
31 | assert(utf8.offset("alo", 5) == nil) | ||
32 | assert(utf8.offset("alo", -4) == nil) | ||
33 | |||
34 | -- 't' is the list of codepoints of 's' | ||
35 | local function check (s, t) | ||
36 | local l = utf8.len(s) | ||
37 | assert(#t == l and len(s) == l) | ||
38 | assert(utf8.char(table.unpack(t)) == s) | ||
39 | |||
40 | assert(utf8.offset(s, 0) == 1) | ||
41 | |||
42 | checksyntax(s, t) | ||
43 | |||
44 | local t1 = {utf8.codepoint(s, 1, -1)} | ||
45 | assert(#t == #t1) | ||
46 | for i = 1, #t do assert(t[i] == t1[i]) end | ||
47 | |||
48 | for i = 1, l do | ||
49 | local pi = utf8.offset(s, i) -- position of i-th char | ||
50 | local pi1 = utf8.offset(s, 2, pi) -- position of next char | ||
51 | assert(string.find(string.sub(s, pi, pi1 - 1), justone)) | ||
52 | assert(utf8.offset(s, -1, pi1) == pi) | ||
53 | assert(utf8.offset(s, i - l - 1) == pi) | ||
54 | assert(pi1 - pi == #utf8.char(utf8.codepoint(s, pi))) | ||
55 | for j = pi, pi1 - 1 do | ||
56 | assert(utf8.offset(s, 0, j) == pi) | ||
57 | end | ||
58 | for j = pi + 1, pi1 - 1 do | ||
59 | assert(not utf8.len(s, j)) | ||
60 | end | ||
61 | assert(utf8.len(s, pi, pi) == 1) | ||
62 | assert(utf8.len(s, pi, pi1 - 1) == 1) | ||
63 | assert(utf8.len(s, pi) == l - i + 1) | ||
64 | assert(utf8.len(s, pi1) == l - i) | ||
65 | assert(utf8.len(s, 1, pi) == i) | ||
66 | end | ||
67 | |||
68 | local i = 0 | ||
69 | for p, c in utf8.codes(s) do | ||
70 | i = i + 1 | ||
71 | assert(c == t[i] and p == utf8.offset(s, i)) | ||
72 | assert(utf8.codepoint(s, p) == c) | ||
73 | end | ||
74 | assert(i == #t) | ||
75 | |||
76 | i = 0 | ||
77 | for p, c in utf8.codes(s) do | ||
78 | i = i + 1 | ||
79 | assert(c == t[i] and p == utf8.offset(s, i)) | ||
80 | end | ||
81 | assert(i == #t) | ||
82 | |||
83 | i = 0 | ||
84 | for c in string.gmatch(s, utf8.charpattern) do | ||
85 | i = i + 1 | ||
86 | assert(c == utf8.char(t[i])) | ||
87 | end | ||
88 | assert(i == #t) | ||
89 | |||
90 | for i = 1, l do | ||
91 | assert(utf8.offset(s, i) == utf8.offset(s, i - l - 1, #s + 1)) | ||
92 | end | ||
93 | |||
94 | end | ||
95 | |||
96 | |||
97 | do -- error indication in utf8.len | ||
98 | local function check (s, p) | ||
99 | local a, b = utf8.len(s) | ||
100 | assert(not a and b == p) | ||
101 | end | ||
102 | check("abc\xE3def", 4) | ||
103 | check("汉å—\x80", #("汉å—") + 1) | ||
104 | check("\xF4\x9F\xBF", 1) | ||
105 | check("\xF4\x9F\xBF\xBF", 1) | ||
106 | end | ||
107 | |||
108 | -- error in utf8.codes | ||
109 | checkerror("invalid UTF%-8 code", | ||
110 | function () | ||
111 | local s = "ab\xff" | ||
112 | for c in utf8.codes(s) do assert(c) end | ||
113 | end) | ||
114 | |||
115 | |||
116 | -- error in initial position for offset | ||
117 | checkerror("position out of range", utf8.offset, "abc", 1, 5) | ||
118 | checkerror("position out of range", utf8.offset, "abc", 1, -4) | ||
119 | checkerror("position out of range", utf8.offset, "", 1, 2) | ||
120 | checkerror("position out of range", utf8.offset, "", 1, -1) | ||
121 | checkerror("continuation byte", utf8.offset, "𦧺", 1, 2) | ||
122 | checkerror("continuation byte", utf8.offset, "𦧺", 1, 2) | ||
123 | checkerror("continuation byte", utf8.offset, "\x80", 1) | ||
124 | |||
125 | |||
126 | |||
127 | local s = "hello World" | ||
128 | local t = {string.byte(s, 1, -1)} | ||
129 | for i = 1, utf8.len(s) do assert(t[i] == string.byte(s, i)) end | ||
130 | check(s, t) | ||
131 | |||
132 | check("汉å—/æ¼¢å—", {27721, 23383, 47, 28450, 23383,}) | ||
133 | |||
134 | do | ||
135 | local s = "áéÃ\128" | ||
136 | local t = {utf8.codepoint(s,1,#s - 1)} | ||
137 | assert(#t == 3 and t[1] == 225 and t[2] == 233 and t[3] == 237) | ||
138 | checkerror("invalid UTF%-8 code", utf8.codepoint, s, 1, #s) | ||
139 | checkerror("out of range", utf8.codepoint, s, #s + 1) | ||
140 | t = {utf8.codepoint(s, 4, 3)} | ||
141 | assert(#t == 0) | ||
142 | checkerror("out of range", utf8.codepoint, s, -(#s + 1), 1) | ||
143 | checkerror("out of range", utf8.codepoint, s, 1, #s + 1) | ||
144 | end | ||
145 | |||
146 | assert(utf8.char() == "") | ||
147 | assert(utf8.char(97, 98, 99) == "abc") | ||
148 | |||
149 | assert(utf8.codepoint(utf8.char(0x10FFFF)) == 0x10FFFF) | ||
150 | |||
151 | checkerror("value out of range", utf8.char, 0x10FFFF + 1) | ||
152 | |||
153 | local function invalid (s) | ||
154 | checkerror("invalid UTF%-8 code", utf8.codepoint, s) | ||
155 | assert(not utf8.len(s)) | ||
156 | end | ||
157 | |||
158 | -- UTF-8 representation for 0x11ffff (value out of valid range) | ||
159 | invalid("\xF4\x9F\xBF\xBF") | ||
160 | |||
161 | -- overlong sequences | ||
162 | invalid("\xC0\x80") -- zero | ||
163 | invalid("\xC1\xBF") -- 0x7F (should be coded in 1 byte) | ||
164 | invalid("\xE0\x9F\xBF") -- 0x7FF (should be coded in 2 bytes) | ||
165 | invalid("\xF0\x8F\xBF\xBF") -- 0xFFFF (should be coded in 3 bytes) | ||
166 | |||
167 | |||
168 | -- invalid bytes | ||
169 | invalid("\x80") -- continuation byte | ||
170 | invalid("\xBF") -- continuation byte | ||
171 | invalid("\xFE") -- invalid byte | ||
172 | invalid("\xFF") -- invalid byte | ||
173 | |||
174 | |||
175 | -- empty string | ||
176 | check("", {}) | ||
177 | |||
178 | -- minimum and maximum values for each sequence size | ||
179 | s = "\0 \x7F\z | ||
180 | \xC2\x80 \xDF\xBF\z | ||
181 | \xE0\xA0\x80 \xEF\xBF\xBF\z | ||
182 | \xF0\x90\x80\x80 \xF4\x8F\xBF\xBF" | ||
183 | s = string.gsub(s, " ", "") | ||
184 | check(s, {0,0x7F, 0x80,0x7FF, 0x800,0xFFFF, 0x10000,0x10FFFF}) | ||
185 | |||
186 | x = "日本語a-4\0éó" | ||
187 | check(x, {26085, 26412, 35486, 97, 45, 52, 0, 233, 243}) | ||
188 | |||
189 | |||
190 | -- Supplementary Characters | ||
191 | check("𣲷𠜎𠱓ð¡»ð µ¼ab𠺢", | ||
192 | {0x23CB7, 0x2070E, 0x20C53, 0x2107B, 0x20D7C, 0x61, 0x62, 0x20EA2,}) | ||
193 | |||
194 | check("𨳊𩶘𦧺𨳒𥄫𤓓\xF4\x8F\xBF\xBF", | ||
195 | {0x28CCA, 0x29D98, 0x269FA, 0x28CD2, 0x2512B, 0x244D3, 0x10ffff}) | ||
196 | |||
197 | |||
198 | local i = 0 | ||
199 | for p, c in string.gmatch(x, "()(" .. utf8.charpattern .. ")") do | ||
200 | i = i + 1 | ||
201 | assert(utf8.offset(x, i) == p) | ||
202 | assert(utf8.len(x, p) == utf8.len(x) - i + 1) | ||
203 | assert(utf8.len(c) == 1) | ||
204 | for j = 1, #c - 1 do | ||
205 | assert(utf8.offset(x, 0, p + j - 1) == p) | ||
206 | end | ||
207 | end | ||
208 | |||
209 | print'ok' | ||
210 | |||
diff --git a/testes/vararg.lua b/testes/vararg.lua new file mode 100644 index 00000000..4d5ce4ab --- /dev/null +++ b/testes/vararg.lua | |||
@@ -0,0 +1,151 @@ | |||
1 | -- $Id: vararg.lua,v 1.29 2018/03/12 14:19:36 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print('testing vararg') | ||
5 | |||
6 | function f(a, ...) | ||
7 | local x = {n = select('#', ...), ...} | ||
8 | for i = 1, x.n do assert(a[i] == x[i]) end | ||
9 | return x.n | ||
10 | end | ||
11 | |||
12 | function c12 (...) | ||
13 | assert(arg == _G.arg) -- no local 'arg' | ||
14 | local x = {...}; x.n = #x | ||
15 | local res = (x.n==2 and x[1] == 1 and x[2] == 2) | ||
16 | if res then res = 55 end | ||
17 | return res, 2 | ||
18 | end | ||
19 | |||
20 | function vararg (...) return {n = select('#', ...), ...} end | ||
21 | |||
22 | local call = function (f, args) return f(table.unpack(args, 1, args.n)) end | ||
23 | |||
24 | assert(f() == 0) | ||
25 | assert(f({1,2,3}, 1, 2, 3) == 3) | ||
26 | assert(f({"alo", nil, 45, f, nil}, "alo", nil, 45, f, nil) == 5) | ||
27 | |||
28 | assert(vararg().n == 0) | ||
29 | assert(vararg(nil, nil).n == 2) | ||
30 | |||
31 | assert(c12(1,2)==55) | ||
32 | a,b = assert(call(c12, {1,2})) | ||
33 | assert(a == 55 and b == 2) | ||
34 | a = call(c12, {1,2;n=2}) | ||
35 | assert(a == 55 and b == 2) | ||
36 | a = call(c12, {1,2;n=1}) | ||
37 | assert(not a) | ||
38 | assert(c12(1,2,3) == false) | ||
39 | local a = vararg(call(next, {_G,nil;n=2})) | ||
40 | local b,c = next(_G) | ||
41 | assert(a[1] == b and a[2] == c and a.n == 2) | ||
42 | a = vararg(call(call, {c12, {1,2}})) | ||
43 | assert(a.n == 2 and a[1] == 55 and a[2] == 2) | ||
44 | a = call(print, {'+'}) | ||
45 | assert(a == nil) | ||
46 | |||
47 | local t = {1, 10} | ||
48 | function t:f (...) local arg = {...}; return self[...]+#arg end | ||
49 | assert(t:f(1,4) == 3 and t:f(2) == 11) | ||
50 | print('+') | ||
51 | |||
52 | lim = 20 | ||
53 | local i, a = 1, {} | ||
54 | while i <= lim do a[i] = i+0.3; i=i+1 end | ||
55 | |||
56 | function f(a, b, c, d, ...) | ||
57 | local more = {...} | ||
58 | assert(a == 1.3 and more[1] == 5.3 and | ||
59 | more[lim-4] == lim+0.3 and not more[lim-3]) | ||
60 | end | ||
61 | |||
62 | function g(a,b,c) | ||
63 | assert(a == 1.3 and b == 2.3 and c == 3.3) | ||
64 | end | ||
65 | |||
66 | call(f, a) | ||
67 | call(g, a) | ||
68 | |||
69 | a = {} | ||
70 | i = 1 | ||
71 | while i <= lim do a[i] = i; i=i+1 end | ||
72 | assert(call(math.max, a) == lim) | ||
73 | |||
74 | print("+") | ||
75 | |||
76 | |||
77 | -- new-style varargs | ||
78 | |||
79 | function oneless (a, ...) return ... end | ||
80 | |||
81 | function f (n, a, ...) | ||
82 | local b | ||
83 | assert(arg == _G.arg) -- no local 'arg' | ||
84 | if n == 0 then | ||
85 | local b, c, d = ... | ||
86 | return a, b, c, d, oneless(oneless(oneless(...))) | ||
87 | else | ||
88 | n, b, a = n-1, ..., a | ||
89 | assert(b == ...) | ||
90 | return f(n, a, ...) | ||
91 | end | ||
92 | end | ||
93 | |||
94 | a,b,c,d,e = assert(f(10,5,4,3,2,1)) | ||
95 | assert(a==5 and b==4 and c==3 and d==2 and e==1) | ||
96 | |||
97 | a,b,c,d,e = f(4) | ||
98 | assert(a==nil and b==nil and c==nil and d==nil and e==nil) | ||
99 | |||
100 | |||
101 | -- varargs for main chunks | ||
102 | f = load[[ return {...} ]] | ||
103 | x = f(2,3) | ||
104 | assert(x[1] == 2 and x[2] == 3 and x[3] == undef) | ||
105 | |||
106 | |||
107 | f = load[[ | ||
108 | local x = {...} | ||
109 | for i=1,select('#', ...) do assert(x[i] == select(i, ...)) end | ||
110 | assert(x[select('#', ...)+1] == undef) | ||
111 | return true | ||
112 | ]] | ||
113 | |||
114 | assert(f("a", "b", nil, {}, assert)) | ||
115 | assert(f()) | ||
116 | |||
117 | a = {select(3, table.unpack{10,20,30,40})} | ||
118 | assert(#a == 2 and a[1] == 30 and a[2] == 40) | ||
119 | a = {select(1)} | ||
120 | assert(next(a) == nil) | ||
121 | a = {select(-1, 3, 5, 7)} | ||
122 | assert(a[1] == 7 and a[2] == undef) | ||
123 | a = {select(-2, 3, 5, 7)} | ||
124 | assert(a[1] == 5 and a[2] == 7 and a[3] == undef) | ||
125 | pcall(select, 10000) | ||
126 | pcall(select, -10000) | ||
127 | |||
128 | |||
129 | -- bug in 5.2.2 | ||
130 | |||
131 | function f(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, | ||
132 | p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, | ||
133 | p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, | ||
134 | p31, p32, p33, p34, p35, p36, p37, p38, p39, p40, | ||
135 | p41, p42, p43, p44, p45, p46, p48, p49, p50, ...) | ||
136 | local a1,a2,a3,a4,a5,a6,a7 | ||
137 | local a8,a9,a10,a11,a12,a13,a14 | ||
138 | end | ||
139 | |||
140 | -- assertion fail here | ||
141 | f() | ||
142 | |||
143 | -- missing arguments in tail call | ||
144 | do | ||
145 | local function f(a,b,c) return c, b end | ||
146 | local function g() return f(1,2) end | ||
147 | local a, b = g() | ||
148 | assert(a == nil and b == 2) | ||
149 | end | ||
150 | print('OK') | ||
151 | |||
diff --git a/testes/verybig.lua b/testes/verybig.lua new file mode 100644 index 00000000..5b29dea7 --- /dev/null +++ b/testes/verybig.lua | |||
@@ -0,0 +1,152 @@ | |||
1 | -- $Id: verybig.lua,v 1.27 2018/03/09 14:23:48 roberto Exp $ | ||
2 | -- See Copyright Notice in file all.lua | ||
3 | |||
4 | print "testing RK" | ||
5 | |||
6 | -- testing opcodes with RK arguments larger than K limit | ||
7 | local function foo () | ||
8 | local dummy = { | ||
9 | -- fill first 256 entries in table of constants | ||
10 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, | ||
11 | 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, | ||
12 | 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, | ||
13 | 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, | ||
14 | 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, | ||
15 | 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, | ||
16 | 97, 98, 99, 100, 101, 102, 103, 104, | ||
17 | 105, 106, 107, 108, 109, 110, 111, 112, | ||
18 | 113, 114, 115, 116, 117, 118, 119, 120, | ||
19 | 121, 122, 123, 124, 125, 126, 127, 128, | ||
20 | 129, 130, 131, 132, 133, 134, 135, 136, | ||
21 | 137, 138, 139, 140, 141, 142, 143, 144, | ||
22 | 145, 146, 147, 148, 149, 150, 151, 152, | ||
23 | 153, 154, 155, 156, 157, 158, 159, 160, | ||
24 | 161, 162, 163, 164, 165, 166, 167, 168, | ||
25 | 169, 170, 171, 172, 173, 174, 175, 176, | ||
26 | 177, 178, 179, 180, 181, 182, 183, 184, | ||
27 | 185, 186, 187, 188, 189, 190, 191, 192, | ||
28 | 193, 194, 195, 196, 197, 198, 199, 200, | ||
29 | 201, 202, 203, 204, 205, 206, 207, 208, | ||
30 | 209, 210, 211, 212, 213, 214, 215, 216, | ||
31 | 217, 218, 219, 220, 221, 222, 223, 224, | ||
32 | 225, 226, 227, 228, 229, 230, 231, 232, | ||
33 | 233, 234, 235, 236, 237, 238, 239, 240, | ||
34 | 241, 242, 243, 244, 245, 246, 247, 248, | ||
35 | 249, 250, 251, 252, 253, 254, 255, 256, | ||
36 | } | ||
37 | assert(24.5 + 0.6 == 25.1) | ||
38 | local t = {foo = function (self, x) return x + self.x end, x = 10} | ||
39 | t.t = t | ||
40 | assert(t:foo(1.5) == 11.5) | ||
41 | assert(t.t:foo(0.5) == 10.5) -- bug in 5.2 alpha | ||
42 | assert(24.3 == 24.3) | ||
43 | assert((function () return t.x end)() == 10) | ||
44 | end | ||
45 | |||
46 | |||
47 | foo() | ||
48 | foo = nil | ||
49 | |||
50 | if _soft then return 10 end | ||
51 | |||
52 | print "testing large programs (>64k)" | ||
53 | |||
54 | -- template to create a very big test file | ||
55 | prog = [[$ | ||
56 | |||
57 | local a,b | ||
58 | |||
59 | b = {$1$ | ||
60 | b30009 = 65534, | ||
61 | b30010 = 65535, | ||
62 | b30011 = 65536, | ||
63 | b30012 = 65537, | ||
64 | b30013 = 16777214, | ||
65 | b30014 = 16777215, | ||
66 | b30015 = 16777216, | ||
67 | b30016 = 16777217, | ||
68 | b30017 = 0x7fffff, | ||
69 | b30018 = -0x7fffff, | ||
70 | b30019 = 0x1ffffff, | ||
71 | b30020 = -0x1ffffd, | ||
72 | b30021 = -65534, | ||
73 | b30022 = -65535, | ||
74 | b30023 = -65536, | ||
75 | b30024 = -0xffffff, | ||
76 | b30025 = 15012.5, | ||
77 | $2$ | ||
78 | }; | ||
79 | |||
80 | assert(b.a50008 == 25004 and b["a11"] == -5.5) | ||
81 | assert(b.a33007 == -16503.5 and b.a50009 == -25004.5) | ||
82 | assert(b["b"..30024] == -0xffffff) | ||
83 | |||
84 | function b:xxx (a,b) return a+b end | ||
85 | assert(b:xxx(10, 12) == 22) -- pushself with non-constant index | ||
86 | b["xxx"] = undef | ||
87 | |||
88 | s = 0; n=0 | ||
89 | for a,b in pairs(b) do s=s+b; n=n+1 end | ||
90 | -- with 32-bit floats, exact value of 's' depends on summation order | ||
91 | assert(81800000.0 < s and s < 81860000 and n == 70001) | ||
92 | |||
93 | a = nil; b = nil | ||
94 | print'+' | ||
95 | |||
96 | function f(x) b=x end | ||
97 | |||
98 | a = f{$3$} or 10 | ||
99 | |||
100 | assert(a==10) | ||
101 | assert(b[1] == "a10" and b[2] == 5 and b[#b-1] == "a50009") | ||
102 | |||
103 | |||
104 | function xxxx (x) return b[x] end | ||
105 | |||
106 | assert(xxxx(3) == "a11") | ||
107 | |||
108 | a = nil; b=nil | ||
109 | xxxx = nil | ||
110 | |||
111 | return 10 | ||
112 | |||
113 | ]] | ||
114 | |||
115 | -- functions to fill in the $n$ | ||
116 | |||
117 | local function sig (x) | ||
118 | return (x % 2 == 0) and '' or '-' | ||
119 | end | ||
120 | |||
121 | F = { | ||
122 | function () -- $1$ | ||
123 | for i=10,50009 do | ||
124 | io.write('a', i, ' = ', sig(i), 5+((i-10)/2), ',\n') | ||
125 | end | ||
126 | end, | ||
127 | |||
128 | function () -- $2$ | ||
129 | for i=30026,50009 do | ||
130 | io.write('b', i, ' = ', sig(i), 15013+((i-30026)/2), ',\n') | ||
131 | end | ||
132 | end, | ||
133 | |||
134 | function () -- $3$ | ||
135 | for i=10,50009 do | ||
136 | io.write('"a', i, '", ', sig(i), 5+((i-10)/2), ',\n') | ||
137 | end | ||
138 | end, | ||
139 | } | ||
140 | |||
141 | file = os.tmpname() | ||
142 | io.output(file) | ||
143 | for s in string.gmatch(prog, "$([^$]+)") do | ||
144 | local n = tonumber(s) | ||
145 | if not n then io.write(s) else F[n]() end | ||
146 | end | ||
147 | io.close() | ||
148 | result = dofile(file) | ||
149 | assert(os.remove(file)) | ||
150 | print'OK' | ||
151 | return result | ||
152 | |||