aboutsummaryrefslogtreecommitdiff
path: root/zig-lua/lua-5.4.7/testes
diff options
context:
space:
mode:
Diffstat (limited to 'zig-lua/lua-5.4.7/testes')
-rw-r--r--zig-lua/lua-5.4.7/testes/all.lua312
-rw-r--r--zig-lua/lua-5.4.7/testes/api.lua1543
-rw-r--r--zig-lua/lua-5.4.7/testes/attrib.lua527
-rw-r--r--zig-lua/lua-5.4.7/testes/big.lua82
-rw-r--r--zig-lua/lua-5.4.7/testes/bitwise.lua363
-rw-r--r--zig-lua/lua-5.4.7/testes/bwcoercion.lua78
-rw-r--r--zig-lua/lua-5.4.7/testes/calls.lua497
-rw-r--r--zig-lua/lua-5.4.7/testes/closure.lua272
-rw-r--r--zig-lua/lua-5.4.7/testes/code.lua449
-rw-r--r--zig-lua/lua-5.4.7/testes/constructs.lua406
-rw-r--r--zig-lua/lua-5.4.7/testes/coroutine.lua1156
-rw-r--r--zig-lua/lua-5.4.7/testes/cstack.lua197
-rw-r--r--zig-lua/lua-5.4.7/testes/db.lua1054
-rw-r--r--zig-lua/lua-5.4.7/testes/errors.lua696
-rw-r--r--zig-lua/lua-5.4.7/testes/events.lua491
-rw-r--r--zig-lua/lua-5.4.7/testes/files.lua951
-rw-r--r--zig-lua/lua-5.4.7/testes/gc.lua695
-rw-r--r--zig-lua/lua-5.4.7/testes/gengc.lua172
-rw-r--r--zig-lua/lua-5.4.7/testes/goto.lua271
-rw-r--r--zig-lua/lua-5.4.7/testes/heavy.lua173
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/P1/dummy2
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/lib1.c44
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/lib11.c10
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/lib2.c23
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/lib21.c10
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/lib22.c25
-rw-r--r--zig-lua/lua-5.4.7/testes/libs/makefile27
-rw-r--r--zig-lua/lua-5.4.7/testes/literals.lua343
-rw-r--r--zig-lua/lua-5.4.7/testes/locals.lua1181
-rw-r--r--zig-lua/lua-5.4.7/testes/main.lua563
-rw-r--r--zig-lua/lua-5.4.7/testes/math.lua1024
-rw-r--r--zig-lua/lua-5.4.7/testes/nextvar.lua825
-rwxr-xr-xzig-lua/lua-5.4.7/testes/packtests55
-rw-r--r--zig-lua/lua-5.4.7/testes/pm.lua440
-rw-r--r--zig-lua/lua-5.4.7/testes/sort.lua311
-rw-r--r--zig-lua/lua-5.4.7/testes/strings.lua526
-rw-r--r--zig-lua/lua-5.4.7/testes/tpack.lua322
-rw-r--r--zig-lua/lua-5.4.7/testes/tracegc.lua40
-rw-r--r--zig-lua/lua-5.4.7/testes/utf8.lua259
-rw-r--r--zig-lua/lua-5.4.7/testes/vararg.lua151
-rw-r--r--zig-lua/lua-5.4.7/testes/verybig.lua152
41 files changed, 16718 insertions, 0 deletions
diff --git a/zig-lua/lua-5.4.7/testes/all.lua b/zig-lua/lua-5.4.7/testes/all.lua
new file mode 100644
index 0000000..5df0ff9
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/all.lua
@@ -0,0 +1,312 @@
1#!../lua
2-- $Id: testes/all.lua $
3-- See Copyright Notice at the end of this file
4
5
6local version = "Lua 5.4"
7if _VERSION ~= version then
8 io.stderr:write("This test suite is for ", version,
9 ", not for ", _VERSION, "\nExiting tests")
10 return
11end
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
28local usertests = rawget(_G, "_U")
29
30if usertests then
31 -- tests for sissies ;) Avoid problems
32 _soft = true
33 _port = true
34 _nomsg = true
35end
36
37-- tests should require debug when needed
38debug = nil
39
40
41if usertests then
42 T = nil -- no "internal" tests for user tests
43else
44 T = rawget(_G, "T") -- avoid problems with 'strict' module
45end
46
47
48--[=[
49 example of a long [comment],
50 [[spanning several [lines]]]
51
52]=]
53
54print("\n\tStarting Tests")
55
56do
57 -- set random seed
58 local random_x, random_y = math.randomseed()
59 print(string.format("random seeds: %d, %d", random_x, random_y))
60end
61
62print("current path:\n****" .. package.path .. "****\n")
63
64
65local initclock = os.clock()
66local lastclock = initclock
67local walltime = os.time()
68
69local collectgarbage = collectgarbage
70
71do -- (
72
73-- track messages for tests not performed
74local msgs = {}
75function Message (m)
76 if not _nomsg then
77 print(m)
78 msgs[#msgs+1] = string.sub(m, 3, -3)
79 end
80end
81
82assert(os.setlocale"C")
83
84local T,print,format,write,assert,type,unpack,floor =
85 T,print,string.format,io.write,assert,type,table.unpack,math.floor
86
87-- use K for 1000 and M for 1000000 (not 2^10 -- 2^20)
88local function F (m)
89 local function round (m)
90 m = m + 0.04999
91 return format("%.1f", m) -- keep one decimal digit
92 end
93 if m < 1000 then return m
94 else
95 m = m / 1000
96 if m < 1000 then return round(m).."K"
97 else
98 return round(m/1000).."M"
99 end
100 end
101end
102
103local Cstacklevel
104
105local showmem
106if not T then
107 local max = 0
108 showmem = function ()
109 local m = collectgarbage("count") * 1024
110 max = (m > max) and m or max
111 print(format(" ---- total memory: %s, max memory: %s ----\n",
112 F(m), F(max)))
113 end
114 Cstacklevel = function () return 0 end -- no info about stack level
115else
116 showmem = function ()
117 T.checkmemory()
118 local total, numblocks, maxmem = T.totalmem()
119 local count = collectgarbage("count")
120 print(format(
121 "\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n",
122 F(total), count, F(maxmem), numblocks))
123 print(format("\t(strings: %d, tables: %d, functions: %d, "..
124 "\n\tudata: %d, threads: %d)",
125 T.totalmem"string", T.totalmem"table", T.totalmem"function",
126 T.totalmem"userdata", T.totalmem"thread"))
127 end
128
129 Cstacklevel = function ()
130 local _, _, ncalls = T.stacklevel()
131 return ncalls -- number of C calls
132 end
133end
134
135
136local Cstack = Cstacklevel()
137
138--
139-- redefine dofile to run files through dump/undump
140--
141local function report (n) print("\n***** FILE '"..n.."'*****") end
142local olddofile = dofile
143local dofile = function (n, strip)
144 showmem()
145 local c = os.clock()
146 print(string.format("time: %g (+%g)", c - initclock, c - lastclock))
147 lastclock = c
148 report(n)
149 local f = assert(loadfile(n))
150 local b = string.dump(f, strip)
151 f = assert(load(b))
152 return f()
153end
154
155dofile('main.lua')
156
157-- trace GC cycles
158require"tracegc".start()
159
160report"gc.lua"
161local f = assert(loadfile('gc.lua'))
162f()
163
164dofile('db.lua')
165assert(dofile('calls.lua') == deep and deep)
166_G.deep = nil
167olddofile('strings.lua')
168olddofile('literals.lua')
169dofile('tpack.lua')
170assert(dofile('attrib.lua') == 27)
171dofile('gengc.lua')
172assert(dofile('locals.lua') == 5)
173dofile('constructs.lua')
174dofile('code.lua', true)
175if not _G._soft then
176 report('big.lua')
177 local f = coroutine.wrap(assert(loadfile('big.lua')))
178 assert(f() == 'b')
179 assert(f() == 'a')
180end
181dofile('cstack.lua')
182dofile('nextvar.lua')
183dofile('pm.lua')
184dofile('utf8.lua')
185dofile('api.lua')
186assert(dofile('events.lua') == 12)
187dofile('vararg.lua')
188dofile('closure.lua')
189dofile('coroutine.lua')
190dofile('goto.lua', true)
191dofile('errors.lua')
192dofile('math.lua')
193dofile('sort.lua', true)
194dofile('bitwise.lua')
195assert(dofile('verybig.lua', true) == 10); collectgarbage()
196dofile('files.lua')
197
198if #msgs > 0 then
199 local m = table.concat(msgs, "\n ")
200 warn("#tests not performed:\n ", m, "\n")
201end
202
203print("(there should be two warnings now)")
204warn("@on")
205warn("#This is ", "an expected", " warning")
206warn("@off")
207warn("******** THIS WARNING SHOULD NOT APPEAR **********")
208warn("******** THIS WARNING ALSO SHOULD NOT APPEAR **********")
209warn("@on")
210warn("#This is", " another one")
211
212-- no test module should define 'debug'
213assert(debug == nil)
214
215local debug = require "debug"
216
217print(string.format("%d-bit integers, %d-bit floats",
218 string.packsize("j") * 8, string.packsize("n") * 8))
219
220debug.sethook(function (a) assert(type(a) == 'string') end, "cr")
221
222-- to survive outside block
223_G.showmem = showmem
224
225
226assert(Cstack == Cstacklevel(),
227 "should be at the same C-stack level it was when started the tests")
228
229end --)
230
231local _G, showmem, print, format, clock, time, difftime,
232 assert, open, warn =
233 _G, showmem, print, string.format, os.clock, os.time, os.difftime,
234 assert, io.open, warn
235
236-- file with time of last performed test
237local fname = T and "time-debug.txt" or "time.txt"
238local lasttime
239
240if not usertests then
241 -- open file with time of last performed test
242 local f = io.open(fname)
243 if f then
244 lasttime = assert(tonumber(f:read'a'))
245 f:close();
246 else -- no such file; assume it is recording time for first time
247 lasttime = nil
248 end
249end
250
251-- erase (almost) all globals
252print('cleaning all!!!!')
253for n in pairs(_G) do
254 if not ({___Glob = 1, tostring = 1})[n] then
255 _G[n] = undef
256 end
257end
258
259
260collectgarbage()
261collectgarbage()
262collectgarbage()
263collectgarbage()
264collectgarbage()
265collectgarbage();showmem()
266
267local clocktime = clock() - initclock
268walltime = difftime(time(), walltime)
269
270print(format("\n\ntotal time: %.2fs (wall time: %gs)\n", clocktime, walltime))
271
272if not usertests then
273 lasttime = lasttime or clocktime -- if no last time, ignore difference
274 -- check whether current test time differs more than 5% from last time
275 local diff = (clocktime - lasttime) / lasttime
276 local tolerance = 0.05 -- 5%
277 if (diff >= tolerance or diff <= -tolerance) then
278 warn(format("#time difference from previous test: %+.1f%%",
279 diff * 100))
280 end
281 assert(open(fname, "w")):write(clocktime):close()
282end
283
284print("final OK !!!")
285
286
287
288--[[
289*****************************************************************************
290* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
291*
292* Permission is hereby granted, free of charge, to any person obtaining
293* a copy of this software and associated documentation files (the
294* "Software"), to deal in the Software without restriction, including
295* without limitation the rights to use, copy, modify, merge, publish,
296* distribute, sublicense, and/or sell copies of the Software, and to
297* permit persons to whom the Software is furnished to do so, subject to
298* the following conditions:
299*
300* The above copyright notice and this permission notice shall be
301* included in all copies or substantial portions of the Software.
302*
303* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
304* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
305* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
306* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
307* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
308* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
309* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
310*****************************************************************************
311]]
312
diff --git a/zig-lua/lua-5.4.7/testes/api.lua b/zig-lua/lua-5.4.7/testes/api.lua
new file mode 100644
index 0000000..752ff18
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/api.lua
@@ -0,0 +1,1543 @@
1-- $Id: testes/api.lua $
2-- See Copyright Notice in file all.lua
3
4if T==nil then
5 (Message or print)('\n >>> testC not active: skipping API tests <<<\n')
6 return
7end
8
9local debug = require "debug"
10
11local pack = table.pack
12
13
14-- standard error message for memory errors
15local MEMERRMSG = "not enough memory"
16
17local function tcheck (t1, t2)
18 assert(t1.n == (t2.n or #t2) + 1)
19 for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end
20end
21
22
23local function checkerr (msg, f, ...)
24 local stat, err = pcall(f, ...)
25 assert(not stat and string.find(err, msg))
26end
27
28
29print('testing C API')
30
31local a = T.testC("pushvalue R; return 1")
32assert(a == debug.getregistry())
33
34
35-- absindex
36assert(T.testC("settop 10; absindex -1; return 1") == 10)
37assert(T.testC("settop 5; absindex -5; return 1") == 1)
38assert(T.testC("settop 10; absindex 1; return 1") == 1)
39assert(T.testC("settop 10; absindex R; return 1") < -10)
40
41-- testing alignment
42a = T.d2s(12458954321123.0)
43assert(a == string.pack("d", 12458954321123.0))
44assert(T.s2d(a) == 12458954321123.0)
45
46local a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2")
47assert(a == 2 and b == 3 and not c)
48
49local f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2")
50a,b,c = f()
51assert(a == 2 and b == 3 and not c)
52
53-- test that all trues are equal
54a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3")
55assert(a == b and a == true and c == false)
56a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\
57 tobool -3; tobool -3; tobool -3; return 3"
58assert(a==false and b==true and c==false)
59
60
61a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40)
62assert(a == 40 and b == 5 and not c)
63
64local t = pack(T.testC("settop 5; return *", 2, 3))
65tcheck(t, {n=4,2,3})
66
67t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23))
68assert(t.n == 10 and t[1] == nil and t[10] == nil)
69
70t = pack(T.testC("remove -2; return *", 2, 3, 4))
71tcheck(t, {n=2,2,4})
72
73t = pack(T.testC("insert -1; return *", 2, 3))
74tcheck(t, {n=2,2,3})
75
76t = pack(T.testC("insert 3; return *", 2, 3, 4, 5))
77tcheck(t, {n=4,2,5,3,4})
78
79t = pack(T.testC("replace 2; return *", 2, 3, 4, 5))
80tcheck(t, {n=3,5,3,4})
81
82t = pack(T.testC("replace -2; return *", 2, 3, 4, 5))
83tcheck(t, {n=3,2,3,5})
84
85t = pack(T.testC("remove 3; return *", 2, 3, 4, 5))
86tcheck(t, {n=3,2,4,5})
87
88t = pack(T.testC("copy 3 4; return *", 2, 3, 4, 5))
89tcheck(t, {n=4,2,3,3,5})
90
91t = pack(T.testC("copy -3 -1; return *", 2, 3, 4, 5))
92tcheck(t, {n=4,2,3,4,3})
93
94do -- testing 'rotate'
95 local t = {10, 20, 30, 40, 50, 60}
96 for i = -6, 6 do
97 local s = string.format("rotate 2 %d; return 7", i)
98 local t1 = pack(T.testC(s, 10, 20, 30, 40, 50, 60))
99 tcheck(t1, t)
100 table.insert(t, 1, table.remove(t))
101 end
102
103 t = pack(T.testC("rotate -2 1; return *", 10, 20, 30, 40))
104 tcheck(t, {10, 20, 40, 30})
105 t = pack(T.testC("rotate -2 -1; return *", 10, 20, 30, 40))
106 tcheck(t, {10, 20, 40, 30})
107
108 -- some corner cases
109 t = pack(T.testC("rotate -1 0; return *", 10, 20, 30, 40))
110 tcheck(t, {10, 20, 30, 40})
111 t = pack(T.testC("rotate -1 1; return *", 10, 20, 30, 40))
112 tcheck(t, {10, 20, 30, 40})
113 t = pack(T.testC("rotate 5 -1; return *", 10, 20, 30, 40))
114 tcheck(t, {10, 20, 30, 40})
115end
116
117
118-- testing warnings
119T.testC([[
120 warningC "#This shold be a"
121 warningC " single "
122 warning "warning"
123 warningC "#This should be "
124 warning "another one"
125]])
126
127
128-- testing message handlers
129do
130 local f = T.makeCfunc[[
131 getglobal error
132 pushstring bola
133 pcall 1 1 1 # call 'error' with given handler
134 pushstatus
135 return 2 # return error message and status
136 ]]
137
138 local msg, st = f(string.upper) -- function handler
139 assert(st == "ERRRUN" and msg == "BOLA")
140 local msg, st = f(string.len) -- function handler
141 assert(st == "ERRRUN" and msg == 4)
142
143end
144
145t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \
146 insert 2; pushvalue 1; remove 1; insert 1; \
147 insert -2; pushvalue -2; remove -3; return *",
148 2, 3, 4, 5, 10, 40, 90))
149tcheck(t, {n=7,2,3,4,5,10,40,90})
150
151t = pack(T.testC("concat 5; return *", "alo", 2, 3, "joao", 12))
152tcheck(t, {n=1,"alo23joao12"})
153
154-- testing MULTRET
155t = pack(T.testC("call 2,-1; return *",
156 function (a,b) return 1,2,3,4,a,b end, "alo", "joao"))
157tcheck(t, {n=6,1,2,3,4,"alo", "joao"})
158
159do -- test returning more results than fit in the caller stack
160 local a = {}
161 for i=1,1000 do a[i] = true end; a[999] = 10
162 local b = T.testC([[pcall 1 -1 0; pop 1; tostring -1; return 1]],
163 table.unpack, a)
164 assert(b == "10")
165end
166
167
168-- testing globals
169_G.AA = 14; _G.BB = "a31"
170local a = {T.testC[[
171 getglobal AA;
172 getglobal BB;
173 getglobal BB;
174 setglobal AA;
175 return *
176]]}
177assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.AA == "a31")
178
179_G.AA, _G.BB = nil
180
181-- testing arith
182assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5)
183assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10)
184assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200)
185assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000)
186assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5)
187assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10)
188assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200)
189assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000)
190assert(T.testC("arith /; return 1", 2, 0) == 10.0/0)
191a = T.testC("pushnum 10; pushint 3; arith \\; return 1")
192assert(a == 3.0 and math.type(a) == "float")
193a = T.testC("pushint 10; pushint 3; arith \\; return 1")
194assert(a == 3 and math.type(a) == "integer")
195a = assert(T.testC("pushint 10; pushint 3; arith +; return 1"))
196assert(a == 13 and math.type(a) == "integer")
197a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1"))
198assert(a == 13 and math.type(a) == "float")
199a,b,c = T.testC([[pushnum 1;
200 pushstring 10; arith _;
201 pushstring 5; return 3]])
202assert(a == 1 and b == -10 and c == "5")
203local mt = {
204 __add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end,
205 __mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end,
206 __unm = function (a) return setmetatable({a[1]* 2}, mt) end}
207a,b,c = setmetatable({4}, mt),
208 setmetatable({8}, mt),
209 setmetatable({-3}, mt)
210local x,y,z = T.testC("arith +; return 2", 10, a, b)
211assert(x == 10 and y[1] == 12 and z == nil)
212assert(T.testC("arith %; return 1", a, c)[1] == 4%-3)
213assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] ==
214 8 % (4 + (-3)*2))
215
216-- errors in arithmetic
217checkerr("divide by zero", T.testC, "arith \\", 10, 0)
218checkerr("%%0", T.testC, "arith %", 10, 0)
219
220
221-- testing lessthan and lessequal
222assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2))
223assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2))
224assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2))
225assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2))
226assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2))
227assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2"))
228assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2"))
229
230-- non-valid indices produce false
231assert(not T.testC("compare LT 1 4, return 1"))
232assert(not T.testC("compare LE 9 1, return 1"))
233assert(not T.testC("compare EQ 9 9, return 1"))
234
235local b = {__lt = function (a,b) return a[1] < b[1] end}
236local a1,a3,a4 = setmetatable({1}, b),
237 setmetatable({3}, b),
238 setmetatable({4}, b)
239assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2))
240assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2))
241assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2))
242a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20)
243assert(a == 20 and b == false)
244a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20)
245assert(a == 20 and b == false)
246a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20)
247assert(a == 20 and b == true)
248
249
250do -- testing lessthan and lessequal with metamethods
251 local mt = {__lt = function (a,b) return a[1] < b[1] end,
252 __le = function (a,b) return a[1] <= b[1] end,
253 __eq = function (a,b) return a[1] == b[1] end}
254 local function O (x)
255 return setmetatable({x}, mt)
256 end
257
258 local a, b = T.testC("compare LT 2 3; pushint 10; return 2", O(1), O(2))
259 assert(a == true and b == 10)
260 local a, b = T.testC("compare LE 2 3; pushint 10; return 2", O(3), O(2))
261 assert(a == false and b == 10)
262 local a, b = T.testC("compare EQ 2 3; pushint 10; return 2", O(3), O(3))
263 assert(a == true and b == 10)
264end
265
266-- testing length
267local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
268a,b,c = T.testC([[
269 len 2;
270 Llen 2;
271 objsize 2;
272 return 3
273]], t)
274assert(a == 20 and b == 20 and c == 0)
275
276t.x = "234"; t[1] = 20
277a,b,c = T.testC([[
278 len 2;
279 Llen 2;
280 objsize 2;
281 return 3
282]], t)
283assert(a == "234" and b == 234 and c == 1)
284
285t.x = print; t[1] = 20
286a,c = T.testC([[
287 len 2;
288 objsize 2;
289 return 2
290]], t)
291assert(a == print and c == 1)
292
293
294-- testing __concat
295
296a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end})
297x,y = T.testC([[
298 pushnum 5
299 pushvalue 2;
300 pushvalue 2;
301 concat 2;
302 pushvalue -2;
303 return 2;
304]], a, a)
305assert(x == a..a and y == 5)
306
307-- concat with 0 elements
308assert(T.testC("concat 0; return 1") == "")
309
310-- concat with 1 element
311assert(T.testC("concat 1; return 1", "xuxu") == "xuxu")
312
313
314
315-- testing lua_is
316
317local function B (x) return x and 1 or 0 end
318
319local function count (x, n)
320 n = n or 2
321 local prog = [[
322 isnumber %d;
323 isstring %d;
324 isfunction %d;
325 iscfunction %d;
326 istable %d;
327 isuserdata %d;
328 isnil %d;
329 isnull %d;
330 return 8
331 ]]
332 prog = string.format(prog, n, n, n, n, n, n, n, n)
333 local a,b,c,d,e,f,g,h = T.testC(prog, x)
334 return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h))
335end
336
337assert(count(3) == 2)
338assert(count('alo') == 1)
339assert(count('32') == 2)
340assert(count({}) == 1)
341assert(count(print) == 2)
342assert(count(function () end) == 1)
343assert(count(nil) == 1)
344assert(count(io.stdin) == 1)
345assert(count(nil, 15) == 100)
346
347
348-- testing lua_to...
349
350local function to (s, x, n)
351 n = n or 2
352 return T.testC(string.format("%s %d; return 1", s, n), x)
353end
354
355local null = T.pushuserdata(0)
356local hfunc = string.gmatch("", "") -- a "heavy C function" (with upvalues)
357assert(debug.getupvalue(hfunc, 1))
358assert(to("tostring", {}) == nil)
359assert(to("tostring", "alo") == "alo")
360assert(to("tostring", 12) == "12")
361assert(to("tostring", 12, 3) == nil)
362assert(to("objsize", {}) == 0)
363assert(to("objsize", {1,2,3}) == 3)
364assert(to("objsize", "alo\0\0a") == 6)
365assert(to("objsize", T.newuserdata(0)) == 0)
366assert(to("objsize", T.newuserdata(101)) == 101)
367assert(to("objsize", 124) == 0)
368assert(to("objsize", true) == 0)
369assert(to("tonumber", {}) == 0)
370assert(to("tonumber", "12") == 12)
371assert(to("tonumber", "s2") == 0)
372assert(to("tonumber", 1, 20) == 0)
373assert(to("topointer", 10) == null)
374assert(to("topointer", true) == null)
375assert(to("topointer", nil) == null)
376assert(to("topointer", "abc") ~= null)
377assert(to("topointer", string.rep("x", 10)) ==
378 to("topointer", string.rep("x", 10))) -- short strings
379do -- long strings
380 local s1 = string.rep("x", 300)
381 local s2 = string.rep("x", 300)
382 assert(to("topointer", s1) ~= to("topointer", s2))
383end
384assert(to("topointer", T.pushuserdata(20)) ~= null)
385assert(to("topointer", io.read) ~= null) -- light C function
386assert(to("topointer", hfunc) ~= null) -- "heavy" C function
387assert(to("topointer", function () end) ~= null) -- Lua function
388assert(to("topointer", io.stdin) ~= null) -- full userdata
389assert(to("func2num", 20) == 0)
390assert(to("func2num", T.pushuserdata(10)) == 0)
391assert(to("func2num", io.read) ~= 0) -- light C function
392assert(to("func2num", hfunc) ~= 0) -- "heavy" C function (with upvalue)
393a = to("tocfunction", math.deg)
394assert(a(3) == math.deg(3) and a == math.deg)
395
396
397print("testing panic function")
398do
399 -- trivial error
400 assert(T.checkpanic("pushstring hi; error") == "hi")
401
402 -- using the stack inside panic
403 assert(T.checkpanic("pushstring hi; error;",
404 [[checkstack 5 XX
405 pushstring ' alo'
406 pushstring ' mundo'
407 concat 3]]) == "hi alo mundo")
408
409 -- "argerror" without frames
410 assert(T.checkpanic("loadstring 4") ==
411 "bad argument #4 (string expected, got no value)")
412
413
414 -- memory error
415 T.totalmem(T.totalmem()+10000) -- set low memory limit (+10k)
416 assert(T.checkpanic("newuserdata 20000") == MEMERRMSG)
417 T.totalmem(0) -- restore high limit
418
419 -- stack error
420 if not _soft then
421 local msg = T.checkpanic[[
422 pushstring "function f() f() end"
423 loadstring -1; call 0 0
424 getglobal f; call 0 0
425 ]]
426 assert(string.find(msg, "stack overflow"))
427 end
428
429 -- exit in panic still close to-be-closed variables
430 assert(T.checkpanic([[
431 pushstring "return {__close = function () Y = 'ho'; end}"
432 newtable
433 loadstring -2
434 call 0 1
435 setmetatable -2
436 toclose -1
437 pushstring "hi"
438 error
439 ]],
440 [[
441 getglobal Y
442 concat 2 # concat original error with global Y
443 ]]) == "hiho")
444
445
446end
447
448-- testing deep C stack
449if not _soft then
450 print("testing stack overflow")
451 collectgarbage("stop")
452 checkerr("XXXX", T.testC, "checkstack 1000023 XXXX") -- too deep
453 -- too deep (with no message)
454 checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''")
455 local s = string.rep("pushnil;checkstack 1 XX;", 1000000)
456 checkerr("overflow", T.testC, s)
457 collectgarbage("restart")
458 print'+'
459end
460
461local lim = _soft and 500 or 12000
462local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"}
463for i = 1,lim do
464 prog[#prog + 1] = "pushnum " .. i
465 prog[#prog + 1] = "pushnum " .. i * 10
466end
467
468prog[#prog + 1] = "rawgeti R 2" -- get global table in registry
469prog[#prog + 1] = "insert " .. -(2*lim + 2)
470
471for i = 1,lim do
472 prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1)
473end
474
475prog[#prog + 1] = "return 2"
476
477prog = table.concat(prog, ";")
478local g, t = T.testC(prog)
479assert(g == _G)
480for i = 1,lim do assert(t[i] == i*10); t[i] = undef end
481assert(next(t) == nil)
482prog, g, t = nil
483
484-- testing errors
485
486a = T.testC([[
487 loadstring 2; pcall 0 1 0;
488 pushvalue 3; insert -2; pcall 1 1 0;
489 pcall 0 0 0;
490 return 1
491]], "XX=150", function (a) assert(a==nil); return 3 end)
492
493assert(type(a) == 'string' and XX == 150)
494_G.XX = nil
495
496local function check3(p, ...)
497 local arg = {...}
498 assert(#arg == 3)
499 assert(string.find(arg[3], p))
500end
501check3(":1:", T.testC("loadstring 2; return *", "x="))
502check3("%.", T.testC("loadfile 2; return *", "."))
503check3("xxxx", T.testC("loadfile 2; return *", "xxxx"))
504
505-- test errors in non protected threads
506local function checkerrnopro (code, msg)
507 local th = coroutine.create(function () end) -- create new thread
508 local stt, err = pcall(T.testC, th, code) -- run code there
509 assert(not stt and string.find(err, msg))
510end
511
512if not _soft then
513 collectgarbage("stop") -- avoid __gc with full stack
514 checkerrnopro("pushnum 3; call 0 0", "attempt to call")
515 print"testing stack overflow in unprotected thread"
516 function F () F() end
517 checkerrnopro("getglobal 'F'; call 0 0;", "stack overflow")
518 F = nil
519 collectgarbage("restart")
520end
521print"+"
522
523
524-- testing table access
525
526do -- getp/setp
527 local a = {}
528 local a1 = T.testC("rawsetp 2 1; return 1", a, 20)
529 assert(a == a1)
530 assert(a[T.pushuserdata(1)] == 20)
531 local a1, res = T.testC("rawgetp -1 1; return 2", a)
532 assert(a == a1 and res == 20)
533end
534
535
536do -- using the table itself as index
537 local a = {}
538 a[a] = 10
539 local prog = "gettable -1; return *"
540 local res = {T.testC(prog, a)}
541 assert(#res == 2 and res[1] == prog and res[2] == 10)
542
543 local prog = "settable -2; return *"
544 local res = {T.testC(prog, a, 20)}
545 assert(a[a] == 20)
546 assert(#res == 1 and res[1] == prog)
547
548 -- raw
549 a[a] = 10
550 local prog = "rawget -1; return *"
551 local res = {T.testC(prog, a)}
552 assert(#res == 2 and res[1] == prog and res[2] == 10)
553
554 local prog = "rawset -2; return *"
555 local res = {T.testC(prog, a, 20)}
556 assert(a[a] == 20)
557 assert(#res == 1 and res[1] == prog)
558
559 -- using the table as the value to set
560 local prog = "rawset -1; return *"
561 local res = {T.testC(prog, 30, a)}
562 assert(a[30] == a)
563 assert(#res == 1 and res[1] == prog)
564
565 local prog = "settable -1; return *"
566 local res = {T.testC(prog, 40, a)}
567 assert(a[40] == a)
568 assert(#res == 1 and res[1] == prog)
569
570 local prog = "rawseti -1 100; return *"
571 local res = {T.testC(prog, a)}
572 assert(a[100] == a)
573 assert(#res == 1 and res[1] == prog)
574
575 local prog = "seti -1 200; return *"
576 local res = {T.testC(prog, a)}
577 assert(a[200] == a)
578 assert(#res == 1 and res[1] == prog)
579end
580
581a = {x=0, y=12}
582x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2",
583 a, 3, "y", 4, "x")
584assert(x == 0 and y == 12)
585T.testC("settable -5", a, 3, 4, "x", 15)
586assert(a.x == 15)
587a[a] = print
588x = T.testC("gettable 2; return 1", a) -- table and key are the same object!
589assert(x == print)
590T.testC("settable 2", a, "x") -- table and key are the same object!
591assert(a[a] == "x")
592
593b = setmetatable({p = a}, {})
594getmetatable(b).__index = function (t, i) return t.p[i] end
595local k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x")
596assert(x == 15 and k == 35)
597k = T.testC("getfield 2 y, return 1", b)
598assert(k == 12)
599getmetatable(b).__index = function (t, i) return a[i] end
600getmetatable(b).__newindex = function (t, i,v ) a[i] = v end
601y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b)
602assert(y == 12)
603k = T.testC("settable -5, return 1", b, 3, 4, "x", 16)
604assert(a.x == 16 and k == 4)
605a[b] = 'xuxu'
606y = T.testC("gettable 2, return 1", b)
607assert(y == 'xuxu')
608T.testC("settable 2", b, 19)
609assert(a[b] == 19)
610
611--
612do -- testing getfield/setfield with long keys
613 local t = {_012345678901234567890123456789012345678901234567890123456789 = 32}
614 local a = T.testC([[
615 getfield 2 _012345678901234567890123456789012345678901234567890123456789
616 return 1
617 ]], t)
618 assert(a == 32)
619 local a = T.testC([[
620 pushnum 33
621 setglobal _012345678901234567890123456789012345678901234567890123456789
622 ]])
623 assert(_012345678901234567890123456789012345678901234567890123456789 == 33)
624 _012345678901234567890123456789012345678901234567890123456789 = nil
625end
626
627-- testing next
628a = {}
629t = pack(T.testC("next; return *", a, nil))
630tcheck(t, {n=1,a})
631a = {a=3}
632t = pack(T.testC("next; return *", a, nil))
633tcheck(t, {n=3,a,'a',3})
634t = pack(T.testC("next; pop 1; next; return *", a, nil))
635tcheck(t, {n=1,a})
636
637
638
639-- testing upvalues
640
641do
642 local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
643 t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]])
644 assert(b == 10 and c == 20 and type(t) == 'table')
645 a, b = A([[tostring U3; tonumber U4; return 2]])
646 assert(a == nil and b == 0)
647 A([[pushnum 100; pushnum 200; replace U2; replace U1]])
648 b, c = A([[pushvalue U1; pushvalue U2; return 2]])
649 assert(b == 100 and c == 200)
650 A([[replace U2; replace U1]], {x=1}, {x=2})
651 b, c = A([[pushvalue U1; pushvalue U2; return 2]])
652 assert(b.x == 1 and c.x == 2)
653 T.checkmemory()
654end
655
656
657-- testing absent upvalues from C-function pointers
658assert(T.testC[[isnull U1; return 1]] == true)
659assert(T.testC[[isnull U100; return 1]] == true)
660assert(T.testC[[pushvalue U1; return 1]] == nil)
661
662local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
663assert(T.upvalue(f, 1) == 10 and
664 T.upvalue(f, 2) == 20 and
665 T.upvalue(f, 3) == nil)
666T.upvalue(f, 2, "xuxu")
667assert(T.upvalue(f, 2) == "xuxu")
668
669
670-- large closures
671do
672 local A = "checkstack 300 msg;" ..
673 string.rep("pushnum 10;", 255) ..
674 "pushcclosure 255; return 1"
675 A = T.testC(A)
676 for i=1,255 do
677 assert(A(("pushvalue U%d; return 1"):format(i)) == 10)
678 end
679 assert(A("isnull U256; return 1"))
680 assert(not A("isnil U256; return 1"))
681end
682
683
684
685-- testing get/setuservalue
686-- bug in 5.1.2
687checkerr("got number", debug.setuservalue, 3, {})
688checkerr("got nil", debug.setuservalue, nil, {})
689checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {})
690
691-- testing multiple user values
692local b = T.newuserdata(0, 10)
693for i = 1, 10 do
694 local v, p = debug.getuservalue(b, i)
695 assert(v == nil and p)
696end
697do -- indices out of range
698 local v, p = debug.getuservalue(b, -2)
699 assert(v == nil and not p)
700 local v, p = debug.getuservalue(b, 11)
701 assert(v == nil and not p)
702end
703local t = {true, false, 4.56, print, {}, b, "XYZ"}
704for k, v in ipairs(t) do
705 debug.setuservalue(b, v, k)
706end
707for k, v in ipairs(t) do
708 local v1, p = debug.getuservalue(b, k)
709 assert(v1 == v and p)
710end
711
712assert(not debug.getuservalue(4))
713
714debug.setuservalue(b, function () return 10 end, 10)
715collectgarbage() -- function should not be collected
716assert(debug.getuservalue(b, 10)() == 10)
717
718debug.setuservalue(b, 134)
719collectgarbage() -- number should not be a problem for collector
720assert(debug.getuservalue(b) == 134)
721
722
723-- test barrier for uservalues
724do
725 local oldmode = collectgarbage("incremental")
726 T.gcstate("atomic")
727 assert(T.gccolor(b) == "black")
728 debug.setuservalue(b, {x = 100})
729 T.gcstate("pause") -- complete collection
730 assert(debug.getuservalue(b).x == 100) -- uvalue should be there
731 collectgarbage(oldmode)
732end
733
734-- long chain of userdata
735for i = 1, 1000 do
736 local bb = T.newuserdata(0, 1)
737 debug.setuservalue(bb, b)
738 b = bb
739end
740collectgarbage() -- nothing should not be collected
741for i = 1, 1000 do
742 b = debug.getuservalue(b)
743end
744assert(debug.getuservalue(b).x == 100)
745b = nil
746
747
748-- testing locks (refs)
749
750-- reuse of references
751local i = T.ref{}
752T.unref(i)
753assert(T.ref{} == i)
754
755local Arr = {}
756local Lim = 100
757for i=1,Lim do -- lock many objects
758 Arr[i] = T.ref({})
759end
760
761assert(T.ref(nil) == -1 and T.getref(-1) == nil)
762T.unref(-1); T.unref(-1)
763
764for i=1,Lim do -- unlock all them
765 T.unref(Arr[i])
766end
767
768local function printlocks ()
769 local f = T.makeCfunc("gettable R; return 1")
770 local n = f("n")
771 print("n", n)
772 for i=0,n do
773 print(i, f(i))
774 end
775end
776
777
778for i=1,Lim do -- lock many objects
779 Arr[i] = T.ref({})
780end
781
782for i=1,Lim,2 do -- unlock half of them
783 T.unref(Arr[i])
784end
785
786assert(type(T.getref(Arr[2])) == 'table')
787
788
789assert(T.getref(-1) == nil)
790
791
792a = T.ref({})
793
794collectgarbage()
795
796assert(type(T.getref(a)) == 'table')
797
798
799-- colect in cl the `val' of all collected userdata
800local tt = {}
801local cl = {n=0}
802A = nil; B = nil
803local F
804F = function (x)
805 local udval = T.udataval(x)
806 table.insert(cl, udval)
807 local d = T.newuserdata(100) -- create garbage
808 d = nil
809 assert(debug.getmetatable(x).__gc == F)
810 assert(load("table.insert({}, {})"))() -- create more garbage
811 assert(not collectgarbage()) -- GC during GC (no op)
812 local dummy = {} -- create more garbage during GC
813 if A ~= nil then
814 assert(type(A) == "userdata")
815 assert(T.udataval(A) == B)
816 debug.getmetatable(A) -- just access it
817 end
818 A = x -- ressurect userdata
819 B = udval
820 return 1,2,3
821end
822tt.__gc = F
823
824
825-- test whether udate collection frees memory in the right time
826do
827 collectgarbage();
828 collectgarbage();
829 local x = collectgarbage("count");
830 local a = T.newuserdata(5001)
831 assert(T.testC("objsize 2; return 1", a) == 5001)
832 assert(collectgarbage("count") >= x+4)
833 a = nil
834 collectgarbage();
835 assert(collectgarbage("count") <= x+1)
836 -- udata without finalizer
837 x = collectgarbage("count")
838 collectgarbage("stop")
839 for i=1,1000 do T.newuserdata(0) end
840 assert(collectgarbage("count") > x+10)
841 collectgarbage()
842 assert(collectgarbage("count") <= x+1)
843 -- udata with finalizer
844 collectgarbage()
845 x = collectgarbage("count")
846 collectgarbage("stop")
847 a = {__gc = function () end}
848 for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end
849 assert(collectgarbage("count") >= x+10)
850 collectgarbage() -- this collection only calls TM, without freeing memory
851 assert(collectgarbage("count") >= x+10)
852 collectgarbage() -- now frees memory
853 assert(collectgarbage("count") <= x+1)
854 collectgarbage("restart")
855end
856
857
858collectgarbage("stop")
859
860-- create 3 userdatas with tag `tt'
861a = T.newuserdata(0); debug.setmetatable(a, tt); local na = T.udataval(a)
862b = T.newuserdata(0); debug.setmetatable(b, tt); local nb = T.udataval(b)
863c = T.newuserdata(0); debug.setmetatable(c, tt); local nc = T.udataval(c)
864
865-- create userdata without meta table
866x = T.newuserdata(4)
867y = T.newuserdata(0)
868
869checkerr("FILE%* expected, got userdata", io.input, a)
870checkerr("FILE%* expected, got userdata", io.input, x)
871
872assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil)
873
874local d = T.ref(a);
875local e = T.ref(b);
876local f = T.ref(c);
877t = {T.getref(d), T.getref(e), T.getref(f)}
878assert(t[1] == a and t[2] == b and t[3] == c)
879
880t=nil; a=nil; c=nil;
881T.unref(e); T.unref(f)
882
883collectgarbage()
884
885-- check that unref objects have been collected
886assert(#cl == 1 and cl[1] == nc)
887
888x = T.getref(d)
889assert(type(x) == 'userdata' and debug.getmetatable(x) == tt)
890x =nil
891tt.b = b -- create cycle
892tt=nil -- frees tt for GC
893A = nil
894b = nil
895T.unref(d);
896local n5 = T.newuserdata(0)
897debug.setmetatable(n5, {__gc=F})
898n5 = T.udataval(n5)
899collectgarbage()
900assert(#cl == 4)
901-- check order of collection
902assert(cl[2] == n5 and cl[3] == nb and cl[4] == na)
903
904collectgarbage"restart"
905
906
907a, na = {}, {}
908for i=30,1,-1 do
909 a[i] = T.newuserdata(0)
910 debug.setmetatable(a[i], {__gc=F})
911 na[i] = T.udataval(a[i])
912end
913cl = {}
914a = nil; collectgarbage()
915assert(#cl == 30)
916for i=1,30 do assert(cl[i] == na[i]) end
917na = nil
918
919
920for i=2,Lim,2 do -- unlock the other half
921 T.unref(Arr[i])
922end
923
924x = T.newuserdata(41); debug.setmetatable(x, {__gc=F})
925assert(T.testC("objsize 2; return 1", x) == 41)
926cl = {}
927a = {[x] = 1}
928x = T.udataval(x)
929collectgarbage()
930-- old `x' cannot be collected (`a' still uses it)
931assert(#cl == 0)
932for n in pairs(a) do a[n] = undef end
933collectgarbage()
934assert(#cl == 1 and cl[1] == x) -- old `x' must be collected
935
936-- testing lua_equal
937assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20))
938assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo"))
939assert(T.testC("compare EQ 2 3; return 1", nil, nil))
940assert(not T.testC("compare EQ 2 3; return 1", {}, {}))
941assert(not T.testC("compare EQ 2 3; return 1"))
942assert(not T.testC("compare EQ 2 3; return 1", 3))
943
944-- testing lua_equal with fallbacks
945do
946 local map = {}
947 local t = {__eq = function (a,b) return map[a] == map[b] end}
948 local function f(x)
949 local u = T.newuserdata(0)
950 debug.setmetatable(u, t)
951 map[u] = x
952 return u
953 end
954 assert(f(10) == f(10))
955 assert(f(10) ~= f(11))
956 assert(T.testC("compare EQ 2 3; return 1", f(10), f(10)))
957 assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20)))
958 t.__eq = nil
959 assert(f(10) ~= f(10))
960end
961
962print'+'
963
964
965
966-- testing changing hooks during hooks
967_G.TT = {}
968T.sethook([[
969 # set a line hook after 3 count hooks
970 sethook 4 0 '
971 getglobal TT;
972 pushvalue -3; append -2
973 pushvalue -2; append -2
974 ']], "c", 3)
975local a = 1 -- counting
976a = 1 -- counting
977a = 1 -- count hook (set line hook)
978a = 1 -- line hook
979a = 1 -- line hook
980debug.sethook()
981local t = _G.TT
982assert(t[1] == "line")
983local line = t[2]
984assert(t[3] == "line" and t[4] == line + 1)
985assert(t[5] == "line" and t[6] == line + 2)
986assert(t[7] == nil)
987_G.TT = nil
988
989
990-------------------------------------------------------------------------
991do -- testing errors during GC
992 warn("@off")
993 collectgarbage("stop")
994 local a = {}
995 for i=1,20 do
996 a[i] = T.newuserdata(i) -- creates several udata
997 end
998 for i=1,20,2 do -- mark half of them to raise errors during GC
999 debug.setmetatable(a[i],
1000 {__gc = function (x) error("@expected error in gc") end})
1001 end
1002 for i=2,20,2 do -- mark the other half to count and to create more garbage
1003 debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end})
1004 end
1005 a = nil
1006 _G.A = 0
1007 collectgarbage()
1008 assert(A == 10) -- number of normal collections
1009 collectgarbage("restart")
1010 warn("@on")
1011end
1012_G.A = nil
1013-------------------------------------------------------------------------
1014-- test for userdata vals
1015do
1016 local a = {}; local lim = 30
1017 for i=0,lim do a[i] = T.pushuserdata(i) end
1018 for i=0,lim do assert(T.udataval(a[i]) == i) end
1019 for i=0,lim do assert(T.pushuserdata(i) == a[i]) end
1020 for i=0,lim do a[a[i]] = i end
1021 for i=0,lim do a[T.pushuserdata(i)] = i end
1022 assert(type(tostring(a[1])) == "string")
1023end
1024
1025
1026-------------------------------------------------------------------------
1027-- testing multiple states
1028T.closestate(T.newstate());
1029L1 = T.newstate()
1030assert(L1)
1031
1032assert(T.doremote(L1, "X='a'; return 'a'") == 'a')
1033
1034
1035assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0)
1036
1037a, b = T.doremote(L1, "return f()")
1038assert(a == 'alo' and b == '3')
1039
1040T.doremote(L1, "_ERRORMESSAGE = nil")
1041-- error: `sin' is not defined
1042a, b, c = T.doremote(L1, "return sin(1)")
1043assert(a == nil and c == 2) -- 2 == run-time error
1044
1045-- error: syntax error
1046a, b, c = T.doremote(L1, "return a+")
1047assert(a == nil and c == 3 and type(b) == "string") -- 3 == syntax error
1048
1049T.loadlib(L1)
1050a, b, c = T.doremote(L1, [[
1051 string = require'string'
1052 a = require'_G'; assert(a == _G and require("_G") == a)
1053 io = require'io'; assert(type(io.read) == "function")
1054 assert(require("io") == io)
1055 a = require'table'; assert(type(a.insert) == "function")
1056 a = require'debug'; assert(type(a.getlocal) == "function")
1057 a = require'math'; assert(type(a.sin) == "function")
1058 return string.sub('okinama', 1, 2)
1059]])
1060assert(a == "ok")
1061
1062T.closestate(L1);
1063
1064
1065L1 = T.newstate()
1066T.loadlib(L1)
1067T.doremote(L1, "a = {}")
1068T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1;
1069 settable -3]])
1070assert(T.doremote(L1, "return a.x") == "1")
1071
1072T.closestate(L1)
1073
1074L1 = nil
1075
1076print('+')
1077-------------------------------------------------------------------------
1078-- testing to-be-closed variables
1079-------------------------------------------------------------------------
1080print"testing to-be-closed variables"
1081
1082do
1083 local openresource = {}
1084
1085 local function newresource ()
1086 local x = setmetatable({10}, {__close = function(y)
1087 assert(openresource[#openresource] == y)
1088 openresource[#openresource] = nil
1089 y[1] = y[1] + 1
1090 end})
1091 openresource[#openresource + 1] = x
1092 return x
1093 end
1094
1095 local a, b = T.testC([[
1096 call 0 1 # create resource
1097 pushnil
1098 toclose -2 # mark call result to be closed
1099 toclose -1 # mark nil to be closed (will be ignored)
1100 return 2
1101 ]], newresource)
1102 assert(a[1] == 11 and b == nil)
1103 assert(#openresource == 0) -- was closed
1104
1105 -- repeat the test, but calling function in a 'multret' context
1106 local a = {T.testC([[
1107 call 0 1 # create resource
1108 toclose 2 # mark it to be closed
1109 return 2
1110 ]], newresource)}
1111 assert(type(a[1]) == "string" and a[2][1] == 11)
1112 assert(#openresource == 0) -- was closed
1113
1114 -- closing by error
1115 local a, b = pcall(T.makeCfunc[[
1116 call 0 1 # create resource
1117 toclose -1 # mark it to be closed
1118 error # resource is the error object
1119 ]], newresource)
1120 assert(a == false and b[1] == 11)
1121 assert(#openresource == 0) -- was closed
1122
1123 -- non-closable value
1124 local a, b = pcall(T.makeCfunc[[
1125 newtable # create non-closable object
1126 toclose -1 # mark it to be closed (should raise an error)
1127 abort # will not be executed
1128 ]])
1129 assert(a == false and
1130 string.find(b, "non%-closable value"))
1131
1132 local function check (n)
1133 assert(#openresource == n)
1134 end
1135
1136 -- closing resources with 'closeslot'
1137 _ENV.xxx = true
1138 local a = T.testC([[
1139 pushvalue 2 # stack: S, NR, CH, NR
1140 call 0 1 # create resource; stack: S, NR, CH, R
1141 toclose -1 # mark it to be closed
1142 pushvalue 2 # stack: S, NR, CH, R, NR
1143 call 0 1 # create another resource; stack: S, NR, CH, R, R
1144 toclose -1 # mark it to be closed
1145 pushvalue 3 # stack: S, NR, CH, R, R, CH
1146 pushint 2 # there should be two open resources
1147 call 1 0 # stack: S, NR, CH, R, R
1148 closeslot -1 # close second resource
1149 pushvalue 3 # stack: S, NR, CH, R, R, CH
1150 pushint 1 # there should be one open resource
1151 call 1 0 # stack: S, NR, CH, R, R
1152 closeslot 4
1153 setglobal "xxx" # previous op. erased the slot
1154 pop 1 # pop other resource from the stack
1155 pushint *
1156 return 1 # return stack size
1157 ]], newresource, check)
1158 assert(a == 3 and _ENV.xxx == nil) -- no extra items left in the stack
1159
1160 -- closing resources with 'pop'
1161 local a = T.testC([[
1162 pushvalue 2 # stack: S, NR, CH, NR
1163 call 0 1 # create resource; stack: S, NR, CH, R
1164 toclose -1 # mark it to be closed
1165 pushvalue 2 # stack: S, NR, CH, R, NR
1166 call 0 1 # create another resource; stack: S, NR, CH, R, R
1167 toclose -1 # mark it to be closed
1168 pushvalue 3 # stack: S, NR, CH, R, R, CH
1169 pushint 2 # there should be two open resources
1170 call 1 0 # stack: S, NR, CH, R, R
1171 pop 1 # pop second resource
1172 pushvalue 3 # stack: S, NR, CH, R, CH
1173 pushint 1 # there should be one open resource
1174 call 1 0 # stack: S, NR, CH, R
1175 pop 1 # pop other resource from the stack
1176 pushvalue 3 # stack: S, NR, CH, CH
1177 pushint 0 # there should be no open resources
1178 call 1 0 # stack: S, NR, CH
1179 pushint *
1180 return 1 # return stack size
1181 ]], newresource, check)
1182 assert(a == 3) -- no extra items left in the stack
1183
1184 -- non-closable value
1185 local a, b = pcall(T.makeCfunc[[
1186 pushint 32
1187 toclose -1
1188 ]])
1189 assert(not a and string.find(b, "(C temporary)"))
1190
1191end
1192
1193
1194--[[
1195** {==================================================================
1196** Testing memory limits
1197** ===================================================================
1198--]]
1199
1200print("memory-allocation errors")
1201
1202checkerr("block too big", T.newuserdata, math.maxinteger)
1203collectgarbage()
1204local f = load"local a={}; for i=1,100000 do a[i]=i end"
1205T.alloccount(10)
1206checkerr(MEMERRMSG, f)
1207T.alloccount() -- remove limit
1208
1209
1210-- test memory errors; increase limit for maximum memory by steps,
1211-- o that we get memory errors in all allocations of a given
1212-- task, until there is enough memory to complete the task without
1213-- errors.
1214local function testbytes (s, f)
1215 collectgarbage()
1216 local M = T.totalmem()
1217 local oldM = M
1218 local a,b = nil
1219 while true do
1220 collectgarbage(); collectgarbage()
1221 T.totalmem(M)
1222 a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
1223 T.totalmem(0) -- remove limit
1224 if a and b == "OK" then break end -- stop when no more errors
1225 if b ~= "OK" and b ~= MEMERRMSG then -- not a memory error?
1226 error(a, 0) -- propagate it
1227 end
1228 M = M + 7 -- increase memory limit
1229 end
1230 print(string.format("minimum memory for %s: %d bytes", s, M - oldM))
1231 return a
1232end
1233
1234-- test memory errors; increase limit for number of allocations one
1235-- by one, so that we get memory errors in all allocations of a given
1236-- task, until there is enough allocations to complete the task without
1237-- errors.
1238
1239local function testalloc (s, f)
1240 collectgarbage()
1241 local M = 0
1242 local a,b = nil
1243 while true do
1244 collectgarbage(); collectgarbage()
1245 T.alloccount(M)
1246 a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
1247 T.alloccount() -- remove limit
1248 if a and b == "OK" then break end -- stop when no more errors
1249 if b ~= "OK" and b ~= MEMERRMSG then -- not a memory error?
1250 error(a, 0) -- propagate it
1251 end
1252 M = M + 1 -- increase allocation limit
1253 end
1254 print(string.format("minimum allocations for %s: %d allocations", s, M))
1255 return a
1256end
1257
1258
1259local function testamem (s, f)
1260 testalloc(s, f)
1261 return testbytes(s, f)
1262end
1263
1264
1265-- doing nothing
1266b = testamem("doing nothing", function () return 10 end)
1267assert(b == 10)
1268
1269-- testing memory errors when creating a new state
1270
1271testamem("state creation", function ()
1272 local st = T.newstate()
1273 if st then T.closestate(st) end -- close new state
1274 return st
1275end)
1276
1277testamem("empty-table creation", function ()
1278 return {}
1279end)
1280
1281testamem("string creation", function ()
1282 return "XXX" .. "YYY"
1283end)
1284
1285testamem("coroutine creation", function()
1286 return coroutine.create(print)
1287end)
1288
1289
1290-- testing to-be-closed variables
1291testamem("to-be-closed variables", function()
1292 local flag
1293 do
1294 local x <close> =
1295 setmetatable({}, {__close = function () flag = true end})
1296 flag = false
1297 local x = {}
1298 end
1299 return flag
1300end)
1301
1302
1303-- testing threads
1304
1305-- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1)
1306local mt = T.testC("rawgeti R 1; return 1")
1307assert(type(mt) == "thread" and coroutine.running() == mt)
1308
1309
1310
1311local function expand (n,s)
1312 if n==0 then return "" end
1313 local e = string.rep("=", n)
1314 return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n",
1315 e, s, expand(n-1,s), e)
1316end
1317
1318G=0; collectgarbage(); a =collectgarbage("count")
1319load(expand(20,"G=G+1"))()
1320assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1)
1321G = nil
1322
1323testamem("running code on new thread", function ()
1324 return T.doonnewstack("local x=1") == 0 -- try to create thread
1325end)
1326
1327
1328-- testing memory x compiler
1329
1330testamem("loadstring", function ()
1331 return load("x=1") -- try to do load a string
1332end)
1333
1334
1335local testprog = [[
1336local function foo () return end
1337local t = {"x"}
1338AA = "aaa"
1339for i = 1, #t do AA = AA .. t[i] end
1340return true
1341]]
1342
1343-- testing memory x dofile
1344_G.AA = nil
1345local t =os.tmpname()
1346local f = assert(io.open(t, "w"))
1347f:write(testprog)
1348f:close()
1349testamem("dofile", function ()
1350 local a = loadfile(t)
1351 return a and a()
1352end)
1353assert(os.remove(t))
1354assert(_G.AA == "aaax")
1355
1356
1357-- other generic tests
1358
1359testamem("gsub", function ()
1360 local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end)
1361 return (a == 'ablo ablo')
1362end)
1363
1364testamem("dump/undump", function ()
1365 local a = load(testprog)
1366 local b = a and string.dump(a)
1367 a = b and load(b)
1368 return a and a()
1369end)
1370
1371_G.AA = nil
1372
1373local t = os.tmpname()
1374testamem("file creation", function ()
1375 local f = assert(io.open(t, 'w'))
1376 assert (not io.open"nomenaoexistente")
1377 io.close(f);
1378 return not loadfile'nomenaoexistente'
1379end)
1380assert(os.remove(t))
1381
1382testamem("table creation", function ()
1383 local a, lim = {}, 10
1384 for i=1,lim do a[i] = i; a[i..'a'] = {} end
1385 return (type(a[lim..'a']) == 'table' and a[lim] == lim)
1386end)
1387
1388testamem("constructors", function ()
1389 local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5}
1390 return (type(a) == 'table' and a.e == 5)
1391end)
1392
1393local a = 1
1394local close = nil
1395testamem("closure creation", function ()
1396 function close (b)
1397 return function (x) return b + x end
1398 end
1399 return (close(2)(4) == 6)
1400end)
1401
1402testamem("using coroutines", function ()
1403 local a = coroutine.wrap(function ()
1404 coroutine.yield(string.rep("a", 10))
1405 return {}
1406 end)
1407 assert(string.len(a()) == 10)
1408 return a()
1409end)
1410
1411do -- auxiliary buffer
1412 local lim = 100
1413 local a = {}; for i = 1, lim do a[i] = "01234567890123456789" end
1414 testamem("auxiliary buffer", function ()
1415 return (#table.concat(a, ",") == 20*lim + lim - 1)
1416 end)
1417end
1418
1419testamem("growing stack", function ()
1420 local function foo (n)
1421 if n == 0 then return 1 else return 1 + foo(n - 1) end
1422 end
1423 return foo(100)
1424end)
1425
1426-- }==================================================================
1427
1428
1429do -- testing failing in 'lua_checkstack'
1430 local res = T.testC([[rawcheckstack 500000; return 1]])
1431 assert(res == false)
1432 local L = T.newstate()
1433 T.alloccount(0) -- will be unable to reallocate the stack
1434 res = T.testC(L, [[rawcheckstack 5000; return 1]])
1435 T.alloccount()
1436 T.closestate(L)
1437 assert(res == false)
1438end
1439
1440do -- closing state with no extra memory
1441 local L = T.newstate()
1442 T.alloccount(0)
1443 T.closestate(L)
1444 T.alloccount()
1445end
1446
1447do -- garbage collection with no extra memory
1448 local L = T.newstate()
1449 T.loadlib(L)
1450 local res = (T.doremote(L, [[
1451 _ENV = require"_G"
1452 local T = require"T"
1453 local a = {}
1454 for i = 1, 1000 do a[i] = 'i' .. i end -- grow string table
1455 local stsize, stuse = T.querystr()
1456 assert(stuse > 1000)
1457 local function foo (n)
1458 if n > 0 then foo(n - 1) end
1459 end
1460 foo(180) -- grow stack
1461 local _, stksize = T.stacklevel()
1462 assert(stksize > 180)
1463 a = nil
1464 T.alloccount(0)
1465 collectgarbage()
1466 T.alloccount()
1467 -- stack and string table could not be reallocated,
1468 -- so they kept their sizes (without errors)
1469 assert(select(2, T.stacklevel()) == stksize)
1470 assert(T.querystr() == stsize)
1471 return 'ok'
1472 ]]))
1473 assert(res == 'ok')
1474 T.closestate(L)
1475end
1476
1477print'+'
1478
1479-- testing some auxlib functions
1480local function gsub (a, b, c)
1481 a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c)
1482 assert(b == 5)
1483 return a
1484end
1485
1486assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//")
1487assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.")
1488assert(gsub("", "alo", "//") == "")
1489assert(gsub("...", ".", "/.") == "/././.")
1490assert(gsub("...", "...", "") == "")
1491
1492
1493-- testing luaL_newmetatable
1494local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3")
1495assert(type(mt_xuxu) == "table" and res and top == 3)
1496local d, res, top = T.testC("newmetatable xuxu; gettop; return 3")
1497assert(mt_xuxu == d and not res and top == 3)
1498d, res, top = T.testC("newmetatable xuxu1; gettop; return 3")
1499assert(mt_xuxu ~= d and res and top == 3)
1500
1501x = T.newuserdata(0);
1502y = T.newuserdata(0);
1503T.testC("pushstring xuxu; gettable R; setmetatable 2", x)
1504assert(getmetatable(x) == mt_xuxu)
1505
1506-- testing luaL_testudata
1507-- correct metatable
1508local res1, res2, top = T.testC([[testudata -1 xuxu
1509 testudata 2 xuxu
1510 gettop
1511 return 3]], x)
1512assert(res1 and res2 and top == 4)
1513
1514-- wrong metatable
1515res1, res2, top = T.testC([[testudata -1 xuxu1
1516 testudata 2 xuxu1
1517 gettop
1518 return 3]], x)
1519assert(not res1 and not res2 and top == 4)
1520
1521-- non-existent type
1522res1, res2, top = T.testC([[testudata -1 xuxu2
1523 testudata 2 xuxu2
1524 gettop
1525 return 3]], x)
1526assert(not res1 and not res2 and top == 4)
1527
1528-- userdata has no metatable
1529res1, res2, top = T.testC([[testudata -1 xuxu
1530 testudata 2 xuxu
1531 gettop
1532 return 3]], y)
1533assert(not res1 and not res2 and top == 4)
1534
1535-- erase metatables
1536do
1537 local r = debug.getregistry()
1538 assert(r.xuxu == mt_xuxu and r.xuxu1 == d)
1539 r.xuxu = nil; r.xuxu1 = nil
1540end
1541
1542print'OK'
1543
diff --git a/zig-lua/lua-5.4.7/testes/attrib.lua b/zig-lua/lua-5.4.7/testes/attrib.lua
new file mode 100644
index 0000000..458488a
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/attrib.lua
@@ -0,0 +1,527 @@
1-- $Id: testes/attrib.lua $
2-- See Copyright Notice in file all.lua
3
4print "testing require"
5
6assert(require"string" == string)
7assert(require"math" == math)
8assert(require"table" == table)
9assert(require"io" == io)
10assert(require"os" == os)
11assert(require"coroutine" == coroutine)
12
13assert(type(package.path) == "string")
14assert(type(package.cpath) == "string")
15assert(type(package.loaded) == "table")
16assert(type(package.preload) == "table")
17
18assert(type(package.config) == "string")
19print("package config: "..string.gsub(package.config, "\n", "|"))
20
21do
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 occurrence 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)))
40end
41
42do
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
48end
49
50
51do print"testing 'require' message"
52 local oldpath = package.path
53 local oldcpath = package.cpath
54
55 package.path = "?.lua;?/?"
56 package.cpath = "?.so;?/init"
57
58 local st, msg = pcall(require, 'XXX')
59
60 local expected = [[module 'XXX' not found:
61 no field package.preload['XXX']
62 no file 'XXX.lua'
63 no file 'XXX/XXX'
64 no file 'XXX.so'
65 no file 'XXX/init']]
66
67 assert(msg == expected)
68
69 package.path = oldpath
70 package.cpath = oldcpath
71end
72
73print('+')
74
75
76-- The next tests for 'require' assume some specific directories and
77-- libraries.
78
79if not _port then --[
80
81local dirsep = string.match(package.config, "^([^\n]+)\n")
82
83-- auxiliary directory with C modules and temporary files
84local DIR = "libs" .. dirsep
85
86-- prepend DIR to a name and correct directory separators
87local function D (x)
88 local x = string.gsub(x, "/", dirsep)
89 return DIR .. x
90end
91
92-- prepend DIR and pospend proper C lib. extension to a name
93local function DC (x)
94 local ext = (dirsep == '\\') and ".dll" or ".so"
95 return D(x .. ext)
96end
97
98
99local function createfiles (files, preextras, posextras)
100 for n,c in pairs(files) do
101 io.output(D(n))
102 io.write(string.format(preextras, n))
103 io.write(c)
104 io.write(string.format(posextras, n))
105 io.close(io.output())
106 end
107end
108
109local function removefiles (files)
110 for n in pairs(files) do
111 os.remove(D(n))
112 end
113end
114
115local files = {
116 ["names.lua"] = "do return {...} end\n",
117 ["err.lua"] = "B = 15; a = a + 1;",
118 ["synerr.lua"] = "B =",
119 ["A.lua"] = "",
120 ["B.lua"] = "assert(...=='B');require 'A'",
121 ["A.lc"] = "",
122 ["A"] = "",
123 ["L"] = "",
124 ["XXxX"] = "",
125 ["C.lua"] = "package.loaded[...] = 25; require'C'",
126}
127
128AA = nil
129local extras = [[
130NAME = '%s'
131REQUIRED = ...
132return AA]]
133
134createfiles(files, "", extras)
135
136-- testing explicit "dir" separator in 'searchpath'
137assert(package.searchpath("C.lua", D"?", "", "") == D"C.lua")
138assert(package.searchpath("C.lua", D"?", ".", ".") == D"C.lua")
139assert(package.searchpath("--x-", D"?", "-", "X") == D"XXxX")
140assert(package.searchpath("---xX", D"?", "---", "XX") == D"XXxX")
141assert(package.searchpath(D"C.lua", "?", dirsep) == D"C.lua")
142assert(package.searchpath(".\\C.lua", D"?", "\\") == D"./C.lua")
143
144local oldpath = package.path
145
146package.path = string.gsub("D/?.lua;D/?.lc;D/?;D/??x?;D/L", "D/", DIR)
147
148local try = function (p, n, r, ext)
149 NAME = nil
150 local rr, x = require(p)
151 assert(NAME == n)
152 assert(REQUIRED == p)
153 assert(rr == r)
154 assert(ext == x)
155end
156
157local a = require"names"
158assert(a[1] == "names" and a[2] == D"names.lua")
159
160local st, msg = pcall(require, "err")
161assert(not st and string.find(msg, "arithmetic") and B == 15)
162st, msg = pcall(require, "synerr")
163assert(not st and string.find(msg, "error loading module"))
164
165assert(package.searchpath("C", package.path) == D"C.lua")
166assert(require"C" == 25)
167assert(require"C" == 25)
168AA = nil
169try('B', 'B.lua', true, "libs/B.lua")
170assert(package.loaded.B)
171assert(require"B" == true)
172assert(package.loaded.A)
173assert(require"C" == 25)
174package.loaded.A = nil
175try('B', nil, true, nil) -- should not reload package
176try('A', 'A.lua', true, "libs/A.lua")
177package.loaded.A = nil
178os.remove(D'A.lua')
179AA = {}
180try('A', 'A.lc', AA, "libs/A.lc") -- now must find second option
181assert(package.searchpath("A", package.path) == D"A.lc")
182assert(require("A") == AA)
183AA = false
184try('K', 'L', false, "libs/L") -- default option
185try('K', 'L', false, "libs/L") -- default option (should reload it)
186assert(rawget(_G, "_REQUIREDNAME") == nil)
187
188AA = "x"
189try("X", "XXxX", AA, "libs/XXxX")
190
191
192removefiles(files)
193NAME, REQUIRED, AA, B = nil
194
195
196-- testing require of sub-packages
197
198local _G = _G
199
200package.path = string.gsub("D/?.lua;D/?/init.lua", "D/", DIR)
201
202files = {
203 ["P1/init.lua"] = "AA = 10",
204 ["P1/xuxu.lua"] = "AA = 20",
205}
206
207createfiles(files, "_ENV = {}\n", "\nreturn _ENV\n")
208AA = 0
209
210local m, ext = assert(require"P1")
211assert(ext == "libs/P1/init.lua")
212assert(AA == 0 and m.AA == 10)
213assert(require"P1" == m)
214assert(require"P1" == m)
215
216assert(package.searchpath("P1.xuxu", package.path) == D"P1/xuxu.lua")
217m.xuxu, ext = assert(require"P1.xuxu")
218assert(AA == 0 and m.xuxu.AA == 20)
219assert(ext == "libs/P1/xuxu.lua")
220assert(require"P1.xuxu" == m.xuxu)
221assert(require"P1.xuxu" == m.xuxu)
222assert(require"P1" == m and m.AA == 10)
223
224
225removefiles(files)
226AA = nil
227
228package.path = ""
229assert(not pcall(require, "file_does_not_exist"))
230package.path = "??\0?"
231assert(not pcall(require, "file_does_not_exist1"))
232
233package.path = oldpath
234
235-- check 'require' error message
236local fname = "file_does_not_exist2"
237local m, err = pcall(require, fname)
238for t in string.gmatch(package.path..";"..package.cpath, "[^;]+") do
239 t = string.gsub(t, "?", fname)
240 assert(string.find(err, t, 1, true))
241end
242
243do -- testing 'package.searchers' not being a table
244 local searchers = package.searchers
245 package.searchers = 3
246 local st, msg = pcall(require, 'a')
247 assert(not st and string.find(msg, "must be a table"))
248 package.searchers = searchers
249end
250
251local function import(...)
252 local f = {...}
253 return function (m)
254 for i=1, #f do m[f[i]] = _G[f[i]] end
255 end
256end
257
258-- cannot change environment of a C function
259assert(not pcall(module, 'XUXU'))
260
261
262
263-- testing require of C libraries
264
265
266local p = "" -- On Mac OS X, redefine this to "_"
267
268-- check whether loadlib works in this system
269local st, err, when = package.loadlib(DC"lib1", "*")
270if not st then
271 local f, err, when = package.loadlib("donotexist", p.."xuxu")
272 assert(not f and type(err) == "string" and when == "absent")
273 ;(Message or print)('\n >>> cannot load dynamic library <<<\n')
274 print(err, when)
275else
276 -- tests for loadlib
277 local f = assert(package.loadlib(DC"lib1", p.."onefunction"))
278 local a, b = f(15, 25)
279 assert(a == 25 and b == 15)
280
281 f = assert(package.loadlib(DC"lib1", p.."anotherfunc"))
282 assert(f(10, 20) == "10%20\n")
283
284 -- check error messages
285 local f, err, when = package.loadlib(DC"lib1", p.."xuxu")
286 assert(not f and type(err) == "string" and when == "init")
287 f, err, when = package.loadlib("donotexist", p.."xuxu")
288 assert(not f and type(err) == "string" and when == "open")
289
290 -- symbols from 'lib1' must be visible to other libraries
291 f = assert(package.loadlib(DC"lib11", p.."luaopen_lib11"))
292 assert(f() == "exported")
293
294 -- test C modules with prefixes in names
295 package.cpath = DC"?"
296 local lib2, ext = require"lib2-v2"
297 assert(string.find(ext, "libs/lib2-v2", 1, true))
298 -- check correct access to global environment and correct
299 -- parameters
300 assert(_ENV.x == "lib2-v2" and _ENV.y == DC"lib2-v2")
301 assert(lib2.id("x") == true) -- a different "id" implementation
302
303 -- test C submodules
304 local fs, ext = require"lib1.sub"
305 assert(_ENV.x == "lib1.sub" and _ENV.y == DC"lib1")
306 assert(string.find(ext, "libs/lib1", 1, true))
307 assert(fs.id(45) == 45)
308 _ENV.x, _ENV.y = nil
309end
310
311_ENV = _G
312
313
314-- testing preload
315
316do
317 local p = package
318 package = {}
319 p.preload.pl = function (...)
320 local _ENV = {...}
321 function xuxu (x) return x+20 end
322 return _ENV
323 end
324
325 local pl, ext = require"pl"
326 assert(require"pl" == pl)
327 assert(pl.xuxu(10) == 30)
328 assert(pl[1] == "pl" and pl[2] == ":preload:" and ext == ":preload:")
329
330 package = p
331 assert(type(package.path) == "string")
332end
333
334print('+')
335
336end --]
337
338print("testing assignments, logical operators, and constructors")
339
340local res, res2 = 27
341
342local a, b = 1, 2+3
343assert(a==1 and b==5)
344a={}
345local function f() return 10, 11, 12 end
346a.x, b, a[1] = 1, 2, f()
347assert(a.x==1 and b==2 and a[1]==10)
348a[f()], b, a[f()+3] = f(), a, 'x'
349assert(a[10] == 10 and b == a and a[13] == 'x')
350
351do
352 local f = function (n) local x = {}; for i=1,n do x[i]=i end;
353 return table.unpack(x) end;
354 local a,b,c
355 a,b = 0, f(1)
356 assert(a == 0 and b == 1)
357 a,b = 0, f(1)
358 assert(a == 0 and b == 1)
359 a,b,c = 0,5,f(4)
360 assert(a==0 and b==5 and c==1)
361 a,b,c = 0,5,f(0)
362 assert(a==0 and b==5 and c==nil)
363end
364
365local a, b, c, d = 1 and nil, 1 or nil, (1 and (nil or 1)), 6
366assert(not a and b and c and d==6)
367
368d = 20
369a, b, c, d = f()
370assert(a==10 and b==11 and c==12 and d==nil)
371a,b = f(), 1, 2, 3, f()
372assert(a==10 and b==1)
373
374assert(a<b == false and a>b == true)
375assert((10 and 2) == 2)
376assert((10 or 2) == 10)
377assert((10 or assert(nil)) == 10)
378assert(not (nil and assert(nil)))
379assert((nil or "alo") == "alo")
380assert((nil and 10) == nil)
381assert((false and 10) == false)
382assert((true or 10) == true)
383assert((false or 10) == 10)
384assert(false ~= nil)
385assert(nil ~= false)
386assert(not nil == true)
387assert(not not nil == false)
388assert(not not 1 == true)
389assert(not not a == true)
390assert(not not (6 or nil) == true)
391assert(not not (nil and 56) == false)
392assert(not not (nil and true) == false)
393assert(not 10 == false)
394assert(not {} == false)
395assert(not 0.5 == false)
396assert(not "x" == false)
397
398assert({} ~= {})
399print('+')
400
401a = {}
402a[true] = 20
403a[false] = 10
404assert(a[1<2] == 20 and a[1>2] == 10)
405
406function f(a) return a end
407
408local a = {}
409for i=3000,-3000,-1 do a[i + 0.0] = i; end
410a[10e30] = "alo"; a[true] = 10; a[false] = 20
411assert(a[10e30] == 'alo' and a[not 1] == 20 and a[10<20] == 10)
412for i=3000,-3000,-1 do assert(a[i] == i); end
413a[print] = assert
414a[f] = print
415a[a] = a
416assert(a[a][a][a][a][print] == assert)
417a[print](a[a[f]] == a[print])
418assert(not pcall(function () local a = {}; a[nil] = 10 end))
419assert(not pcall(function () local a = {[nil] = 10} end))
420assert(a[nil] == undef)
421a = nil
422
423local a, b, c
424a = {10,9,8,7,6,5,4,3,2; [-3]='a', [f]=print, a='a', b='ab'}
425a, a.x, a.y = a, a[-3]
426assert(a[1]==10 and a[-3]==a.a and a[f]==print and a.x=='a' and not a.y)
427a[1], f(a)[2], b, c = {['alo']=assert}, 10, a[1], a[f], 6, 10, 23, f(a), 2
428a[1].alo(a[2]==10 and b==10 and c==print)
429
430a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 = 10
431local function foo ()
432 return a.aVeryLongName012345678901234567890123456789012345678901234567890123456789
433end
434assert(foo() == 10 and
435a.aVeryLongName012345678901234567890123456789012345678901234567890123456789 ==
43610)
437
438
439do
440 -- _ENV constant
441 local function foo ()
442 local _ENV <const> = 11
443 X = "hi"
444 end
445 local st, msg = pcall(foo)
446 assert(not st and string.find(msg, "number"))
447end
448
449
450-- test of large float/integer indices
451
452-- compute maximum integer where all bits fit in a float
453local maxint = math.maxinteger
454
455-- trim (if needed) to fit in a float
456while maxint ~= (maxint + 0.0) or (maxint - 1) ~= (maxint - 1.0) do
457 maxint = maxint // 2
458end
459
460local maxintF = maxint + 0.0 -- float version
461
462assert(maxintF == maxint and math.type(maxintF) == "float" and
463 maxintF >= 2.0^14)
464
465-- floats and integers must index the same places
466a[maxintF] = 10; a[maxintF - 1.0] = 11;
467a[-maxintF] = 12; a[-maxintF + 1.0] = 13;
468
469assert(a[maxint] == 10 and a[maxint - 1] == 11 and
470 a[-maxint] == 12 and a[-maxint + 1] == 13)
471
472a[maxint] = 20
473a[-maxint] = 22
474
475assert(a[maxintF] == 20 and a[maxintF - 1.0] == 11 and
476 a[-maxintF] == 22 and a[-maxintF + 1.0] == 13)
477
478a = nil
479
480
481-- test conflicts in multiple assignment
482do
483 local a,i,j,b
484 a = {'a', 'b'}; i=1; j=2; b=a
485 i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i
486 assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and
487 b[3] == 1)
488 a = {}
489 local function foo () -- assigining to upvalues
490 b, a.x, a = a, 10, 20
491 end
492 foo()
493 assert(a == 20 and b.x == 10)
494end
495
496-- repeat test with upvalues
497do
498 local a,i,j,b
499 a = {'a', 'b'}; i=1; j=2; b=a
500 local function foo ()
501 i, a[i], a, j, a[j], a[i+j] = j, i, i, b, j, i
502 end
503 foo()
504 assert(i == 2 and b[1] == 1 and a == 1 and j == b and b[2] == 2 and
505 b[3] == 1)
506 local t = {}
507 (function (a) t[a], a = 10, 20 end)(1);
508 assert(t[1] == 10)
509end
510
511-- bug in 5.2 beta
512local function foo ()
513 local a
514 return function ()
515 local b
516 a, b = 3, 14 -- local and upvalue have same index
517 return a, b
518 end
519end
520
521local a, b = foo()()
522assert(a == 3 and b == 14)
523
524print('OK')
525
526return res
527
diff --git a/zig-lua/lua-5.4.7/testes/big.lua b/zig-lua/lua-5.4.7/testes/big.lua
new file mode 100644
index 0000000..46fd846
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/big.lua
@@ -0,0 +1,82 @@
1-- $Id: testes/big.lua $
2-- See Copyright Notice in file all.lua
3
4if _soft then
5 return 'a'
6end
7
8print "testing large tables"
9
10local debug = require"debug"
11
12local lim = 2^18 + 1000
13local prog = { "local y = {0" }
14for i = 1, lim do prog[#prog + 1] = i end
15prog[#prog + 1] = "}\n"
16prog[#prog + 1] = "X = y\n"
17prog[#prog + 1] = ("assert(X[%d] == %d)"):format(lim - 1, lim - 2)
18prog[#prog + 1] = "return 0"
19prog = table.concat(prog, ";")
20
21local env = {string = string, assert = assert}
22local f = assert(load(prog, nil, nil, env))
23
24f()
25assert(env.X[lim] == lim - 1 and env.X[lim + 1] == lim)
26for k in pairs(env) do env[k] = undef end
27
28-- yields during accesses larger than K (in RK)
29setmetatable(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
34X = nil
35local co = coroutine.wrap(f)
36assert(co() == 's')
37assert(co() == 'g')
38assert(co() == 'g')
39assert(co() == 0)
40
41assert(X[lim] == lim - 1 and X[lim + 1] == lim)
42
43-- errors in accesses larger than K (in RK)
44getmetatable(env).__index = function () end
45getmetatable(env).__newindex = function () end
46local e, m = pcall(f)
47assert(not e and m:find("global 'X'"))
48
49-- errors in metamethods
50getmetatable(env).__newindex = function () error("hi") end
51local e, m = xpcall(f, debug.traceback)
52assert(not e and m:find("'newindex'"))
53
54f, X = nil
55
56coroutine.yield'b'
57
58if 2^32 == 0 then -- (small integers) {
59
60print "testing string length overflow"
61
62local repstrings = 192 -- number of strings to be concatenated
63local ssize = math.ceil(2.0^32 / repstrings) + 1 -- size of each string
64
65assert(repstrings * ssize > 2.0^32) -- it should be larger than maximum size
66
67local longs = string.rep("\0", ssize) -- create one long string
68
69-- create function to concatenate 'repstrings' copies of its argument
70local rep = assert(load(
71 "local a = ...; return " .. string.rep("a", repstrings, "..")))
72
73local a, b = pcall(rep, longs) -- call that function
74
75-- it should fail without creating string (result would be too large)
76assert(not a and string.find(b, "overflow"))
77
78end -- }
79
80print'OK'
81
82return 'a'
diff --git a/zig-lua/lua-5.4.7/testes/bitwise.lua b/zig-lua/lua-5.4.7/testes/bitwise.lua
new file mode 100644
index 0000000..dd0a1a9
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/bitwise.lua
@@ -0,0 +1,363 @@
1-- $Id: testes/bitwise.lua $
2-- See Copyright Notice in file all.lua
3
4print("testing bitwise operations")
5
6require "bwcoercion"
7
8local numbits = string.packsize('j') * 8
9
10assert(~0 == -1)
11
12assert((1 << (numbits - 1)) == math.mininteger)
13
14-- basic tests for bitwise operators;
15-- use variables to avoid constant folding
16local a, b, c, d
17a = 0xFFFFFFFFFFFFFFFF
18assert(a == -1 and a & -1 == a and a & 35 == 35)
19a = 0xF0F0F0F0F0F0F0F0
20assert(a | -1 == -1)
21assert(a ~ a == 0 and a ~ 0 == a and a ~ ~a == -1)
22assert(a >> 4 == ~a)
23a = 0xF0; b = 0xCC; c = 0xAA; d = 0xFD
24assert(a | b ~ c & d == 0xF4)
25
26a = 0xF0.0; b = 0xCC.0; c = "0xAA.0"; d = "0xFD.0"
27assert(a | b ~ c & d == 0xF4)
28
29a = 0xF0000000; b = 0xCC000000;
30c = 0xAA000000; d = 0xFD000000
31assert(a | b ~ c & d == 0xF4000000)
32assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
33
34a = a << 32
35b = b << 32
36c = c << 32
37d = d << 32
38assert(a | b ~ c & d == 0xF4000000 << 32)
39assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
40
41
42do -- constant folding
43 local code = string.format("return -1 >> %d", math.maxinteger)
44 assert(load(code)() == 0)
45 local code = string.format("return -1 >> %d", math.mininteger)
46 assert(load(code)() == 0)
47 local code = string.format("return -1 << %d", math.maxinteger)
48 assert(load(code)() == 0)
49 local code = string.format("return -1 << %d", math.mininteger)
50 assert(load(code)() == 0)
51end
52
53assert(-1 >> 1 == (1 << (numbits - 1)) - 1 and 1 << 31 == 0x80000000)
54assert(-1 >> (numbits - 1) == 1)
55assert(-1 >> numbits == 0 and
56 -1 >> -numbits == 0 and
57 -1 << numbits == 0 and
58 -1 << -numbits == 0)
59
60assert(1 >> math.mininteger == 0)
61assert(1 >> math.maxinteger == 0)
62assert(1 << math.mininteger == 0)
63assert(1 << math.maxinteger == 0)
64
65assert((2^30 - 1) << 2^30 == 0)
66assert((2^30 - 1) >> 2^30 == 0)
67
68assert(1 >> -3 == 1 << 3 and 1000 >> 5 == 1000 << -5)
69
70
71-- coercion from strings to integers
72assert("0xffffffffffffffff" | 0 == -1)
73assert("0xfffffffffffffffe" & "-1" == -2)
74assert(" \t-0xfffffffffffffffe\n\t" & "-1" == 2)
75assert(" \n -45 \t " >> " -2 " == -45 * 4)
76assert("1234.0" << "5.0" == 1234 * 32)
77assert("0xffff.0" ~ "0xAAAA" == 0x5555)
78assert(~"0x0.000p4" == -1)
79
80assert(("7" .. 3) << 1 == 146)
81assert(0xffffffff >> (1 .. "9") == 0x1fff)
82assert(10 | (1 .. "9") == 27)
83
84do
85 local st, msg = pcall(function () return 4 & "a" end)
86 assert(string.find(msg, "'band'"))
87
88 local st, msg = pcall(function () return ~"a" end)
89 assert(string.find(msg, "'bnot'"))
90end
91
92
93-- out of range number
94assert(not pcall(function () return "0xffffffffffffffff.0" | 0 end))
95
96-- embedded zeros
97assert(not pcall(function () return "0xffffffffffffffff\0" | 0 end))
98
99print'+'
100
101
102package.preload.bit32 = function () --{
103
104-- no built-in 'bit32' library: implement it using bitwise operators
105
106local bit = {}
107
108function bit.bnot (a)
109 return ~a & 0xFFFFFFFF
110end
111
112
113--
114-- in all vararg functions, avoid creating 'arg' table when there are
115-- only 2 (or less) parameters, as 2 parameters is the common case
116--
117
118function bit.band (x, y, z, ...)
119 if not z then
120 return ((x or -1) & (y or -1)) & 0xFFFFFFFF
121 else
122 local arg = {...}
123 local res = x & y & z
124 for i = 1, #arg do res = res & arg[i] end
125 return res & 0xFFFFFFFF
126 end
127end
128
129function bit.bor (x, y, z, ...)
130 if not z then
131 return ((x or 0) | (y or 0)) & 0xFFFFFFFF
132 else
133 local arg = {...}
134 local res = x | y | z
135 for i = 1, #arg do res = res | arg[i] end
136 return res & 0xFFFFFFFF
137 end
138end
139
140function bit.bxor (x, y, z, ...)
141 if not z then
142 return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
143 else
144 local arg = {...}
145 local res = x ~ y ~ z
146 for i = 1, #arg do res = res ~ arg[i] end
147 return res & 0xFFFFFFFF
148 end
149end
150
151function bit.btest (...)
152 return bit.band(...) ~= 0
153end
154
155function bit.lshift (a, b)
156 return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
157end
158
159function bit.rshift (a, b)
160 return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
161end
162
163function bit.arshift (a, b)
164 a = a & 0xFFFFFFFF
165 if b <= 0 or (a & 0x80000000) == 0 then
166 return (a >> b) & 0xFFFFFFFF
167 else
168 return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
169 end
170end
171
172function bit.lrotate (a ,b)
173 b = b & 31
174 a = a & 0xFFFFFFFF
175 a = (a << b) | (a >> (32 - b))
176 return a & 0xFFFFFFFF
177end
178
179function bit.rrotate (a, b)
180 return bit.lrotate(a, -b)
181end
182
183local function checkfield (f, w)
184 w = w or 1
185 assert(f >= 0, "field cannot be negative")
186 assert(w > 0, "width must be positive")
187 assert(f + w <= 32, "trying to access non-existent bits")
188 return f, ~(-1 << w)
189end
190
191function bit.extract (a, f, w)
192 local f, mask = checkfield(f, w)
193 return (a >> f) & mask
194end
195
196function bit.replace (a, v, f, w)
197 local f, mask = checkfield(f, w)
198 v = v & mask
199 a = (a & ~(mask << f)) | (v << f)
200 return a & 0xFFFFFFFF
201end
202
203return bit
204
205end --}
206
207
208print("testing bitwise library")
209
210local bit32 = require'bit32'
211
212assert(bit32.band() == bit32.bnot(0))
213assert(bit32.btest() == true)
214assert(bit32.bor() == 0)
215assert(bit32.bxor() == 0)
216
217assert(bit32.band() == bit32.band(0xffffffff))
218assert(bit32.band(1,2) == 0)
219
220
221-- out-of-range numbers
222assert(bit32.band(-1) == 0xffffffff)
223assert(bit32.band((1 << 33) - 1) == 0xffffffff)
224assert(bit32.band(-(1 << 33) - 1) == 0xffffffff)
225assert(bit32.band((1 << 33) + 1) == 1)
226assert(bit32.band(-(1 << 33) + 1) == 1)
227assert(bit32.band(-(1 << 40)) == 0)
228assert(bit32.band(1 << 40) == 0)
229assert(bit32.band(-(1 << 40) - 2) == 0xfffffffe)
230assert(bit32.band((1 << 40) - 4) == 0xfffffffc)
231
232assert(bit32.lrotate(0, -1) == 0)
233assert(bit32.lrotate(0, 7) == 0)
234assert(bit32.lrotate(0x12345678, 0) == 0x12345678)
235assert(bit32.lrotate(0x12345678, 32) == 0x12345678)
236assert(bit32.lrotate(0x12345678, 4) == 0x23456781)
237assert(bit32.rrotate(0x12345678, -4) == 0x23456781)
238assert(bit32.lrotate(0x12345678, -8) == 0x78123456)
239assert(bit32.rrotate(0x12345678, 8) == 0x78123456)
240assert(bit32.lrotate(0xaaaaaaaa, 2) == 0xaaaaaaaa)
241assert(bit32.lrotate(0xaaaaaaaa, -2) == 0xaaaaaaaa)
242for i = -50, 50 do
243 assert(bit32.lrotate(0x89abcdef, i) == bit32.lrotate(0x89abcdef, i%32))
244end
245
246assert(bit32.lshift(0x12345678, 4) == 0x23456780)
247assert(bit32.lshift(0x12345678, 8) == 0x34567800)
248assert(bit32.lshift(0x12345678, -4) == 0x01234567)
249assert(bit32.lshift(0x12345678, -8) == 0x00123456)
250assert(bit32.lshift(0x12345678, 32) == 0)
251assert(bit32.lshift(0x12345678, -32) == 0)
252assert(bit32.rshift(0x12345678, 4) == 0x01234567)
253assert(bit32.rshift(0x12345678, 8) == 0x00123456)
254assert(bit32.rshift(0x12345678, 32) == 0)
255assert(bit32.rshift(0x12345678, -32) == 0)
256assert(bit32.arshift(0x12345678, 0) == 0x12345678)
257assert(bit32.arshift(0x12345678, 1) == 0x12345678 // 2)
258assert(bit32.arshift(0x12345678, -1) == 0x12345678 * 2)
259assert(bit32.arshift(-1, 1) == 0xffffffff)
260assert(bit32.arshift(-1, 24) == 0xffffffff)
261assert(bit32.arshift(-1, 32) == 0xffffffff)
262assert(bit32.arshift(-1, -1) == bit32.band(-1 * 2, 0xffffffff))
263
264assert(0x12345678 << 4 == 0x123456780)
265assert(0x12345678 << 8 == 0x1234567800)
266assert(0x12345678 << -4 == 0x01234567)
267assert(0x12345678 << -8 == 0x00123456)
268assert(0x12345678 << 32 == 0x1234567800000000)
269assert(0x12345678 << -32 == 0)
270assert(0x12345678 >> 4 == 0x01234567)
271assert(0x12345678 >> 8 == 0x00123456)
272assert(0x12345678 >> 32 == 0)
273assert(0x12345678 >> -32 == 0x1234567800000000)
274
275print("+")
276-- some special cases
277local c = {0, 1, 2, 3, 10, 0x80000000, 0xaaaaaaaa, 0x55555555,
278 0xffffffff, 0x7fffffff}
279
280for _, b in pairs(c) do
281 assert(bit32.band(b) == b)
282 assert(bit32.band(b, b) == b)
283 assert(bit32.band(b, b, b, b) == b)
284 assert(bit32.btest(b, b) == (b ~= 0))
285 assert(bit32.band(b, b, b) == b)
286 assert(bit32.band(b, b, b, ~b) == 0)
287 assert(bit32.btest(b, b, b) == (b ~= 0))
288 assert(bit32.band(b, bit32.bnot(b)) == 0)
289 assert(bit32.bor(b, bit32.bnot(b)) == bit32.bnot(0))
290 assert(bit32.bor(b) == b)
291 assert(bit32.bor(b, b) == b)
292 assert(bit32.bor(b, b, b) == b)
293 assert(bit32.bor(b, b, 0, ~b) == 0xffffffff)
294 assert(bit32.bxor(b) == b)
295 assert(bit32.bxor(b, b) == 0)
296 assert(bit32.bxor(b, b, b) == b)
297 assert(bit32.bxor(b, b, b, b) == 0)
298 assert(bit32.bxor(b, 0) == b)
299 assert(bit32.bnot(b) ~= b)
300 assert(bit32.bnot(bit32.bnot(b)) == b)
301 assert(bit32.bnot(b) == (1 << 32) - 1 - b)
302 assert(bit32.lrotate(b, 32) == b)
303 assert(bit32.rrotate(b, 32) == b)
304 assert(bit32.lshift(bit32.lshift(b, -4), 4) == bit32.band(b, bit32.bnot(0xf)))
305 assert(bit32.rshift(bit32.rshift(b, 4), -4) == bit32.band(b, bit32.bnot(0xf)))
306end
307
308-- for this test, use at most 24 bits (mantissa of a single float)
309c = {0, 1, 2, 3, 10, 0x800000, 0xaaaaaa, 0x555555, 0xffffff, 0x7fffff}
310for _, b in pairs(c) do
311 for i = -40, 40 do
312 local x = bit32.lshift(b, i)
313 local y = math.floor(math.fmod(b * 2.0^i, 2.0^32))
314 assert(math.fmod(x - y, 2.0^32) == 0)
315 end
316end
317
318assert(not pcall(bit32.band, {}))
319assert(not pcall(bit32.bnot, "a"))
320assert(not pcall(bit32.lshift, 45))
321assert(not pcall(bit32.lshift, 45, print))
322assert(not pcall(bit32.rshift, 45, print))
323
324print("+")
325
326
327-- testing extract/replace
328
329assert(bit32.extract(0x12345678, 0, 4) == 8)
330assert(bit32.extract(0x12345678, 4, 4) == 7)
331assert(bit32.extract(0xa0001111, 28, 4) == 0xa)
332assert(bit32.extract(0xa0001111, 31, 1) == 1)
333assert(bit32.extract(0x50000111, 31, 1) == 0)
334assert(bit32.extract(0xf2345679, 0, 32) == 0xf2345679)
335
336assert(not pcall(bit32.extract, 0, -1))
337assert(not pcall(bit32.extract, 0, 32))
338assert(not pcall(bit32.extract, 0, 0, 33))
339assert(not pcall(bit32.extract, 0, 31, 2))
340
341assert(bit32.replace(0x12345678, 5, 28, 4) == 0x52345678)
342assert(bit32.replace(0x12345678, 0x87654321, 0, 32) == 0x87654321)
343assert(bit32.replace(0, 1, 2) == 2^2)
344assert(bit32.replace(0, -1, 4) == 2^4)
345assert(bit32.replace(-1, 0, 31) == (1 << 31) - 1)
346assert(bit32.replace(-1, 0, 1, 2) == (1 << 32) - 7)
347
348
349-- testing conversion of floats
350
351assert(bit32.bor(3.0) == 3)
352assert(bit32.bor(-4.0) == 0xfffffffc)
353
354-- large floats and large-enough integers?
355if 2.0^50 < 2.0^50 + 1.0 and 2.0^50 < (-1 >> 1) then
356 assert(bit32.bor(2.0^32 - 5.0) == 0xfffffffb)
357 assert(bit32.bor(-2.0^32 - 6.0) == 0xfffffffa)
358 assert(bit32.bor(2.0^48 - 5.0) == 0xfffffffb)
359 assert(bit32.bor(-2.0^48 - 6.0) == 0xfffffffa)
360end
361
362print'OK'
363
diff --git a/zig-lua/lua-5.4.7/testes/bwcoercion.lua b/zig-lua/lua-5.4.7/testes/bwcoercion.lua
new file mode 100644
index 0000000..cd735ab
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/bwcoercion.lua
@@ -0,0 +1,78 @@
1local tonumber, tointeger = tonumber, math.tointeger
2local type, getmetatable, rawget, error = type, getmetatable, rawget, error
3local strsub = string.sub
4
5local print = print
6
7_ENV = nil
8
9-- Try to convert a value to an integer, without assuming any coercion.
10local 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)
16end
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.
22local 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)
33end
34
35
36local 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
44end
45
46
47local smt = getmetatable("")
48
49smt.__band = function (x, y)
50 local x, y = checkargs(x, y, "__band")
51 return y and x & y or x
52end
53
54smt.__bor = function (x, y)
55 local x, y = checkargs(x, y, "__bor")
56 return y and x | y or x
57end
58
59smt.__bxor = function (x, y)
60 local x, y = checkargs(x, y, "__bxor")
61 return y and x ~ y or x
62end
63
64smt.__shl = function (x, y)
65 local x, y = checkargs(x, y, "__shl")
66 return y and x << y or x
67end
68
69smt.__shr = function (x, y)
70 local x, y = checkargs(x, y, "__shr")
71 return y and x >> y or x
72end
73
74smt.__bnot = function (x)
75 local x, y = checkargs(x, x, "__bnot")
76 return y and ~x or x
77end
78
diff --git a/zig-lua/lua-5.4.7/testes/calls.lua b/zig-lua/lua-5.4.7/testes/calls.lua
new file mode 100644
index 0000000..a193858
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/calls.lua
@@ -0,0 +1,497 @@
1-- $Id: testes/calls.lua $
2-- See Copyright Notice in file all.lua
3
4print("testing functions and calls")
5
6local debug = require "debug"
7
8-- get the opportunity to test 'type' too ;)
9
10assert(type(1<2) == 'boolean')
11assert(type(true) == 'boolean' and type(false) == 'boolean')
12assert(type(nil) == 'nil'
13 and type(-3) == 'number'
14 and type'x' == 'string'
15 and type{} == 'table'
16 and type(type) == 'function')
17
18assert(type(assert) == type(print))
19local function f (x) return a:x (x) end
20assert(type(f) == 'function')
21assert(not pcall(type))
22
23
24-- testing local-function recursion
25fact = false
26do
27 local res = 1
28 local function fact (n)
29 if n==0 then return res
30 else return n*fact(n-1)
31 end
32 end
33 assert(fact(5) == 120)
34end
35assert(fact == false)
36fact = nil
37
38-- testing declarations
39local a = {i = 10}
40local self = 20
41function a:x (x) return x+self.i end
42function a.y (x) return x+self end
43
44assert(a:x(1)+10 == a.y(1))
45
46a.t = {i=-100}
47a["t"].x = function (self, a,b) return self.i+a+b end
48
49assert(a.t:x(2,3) == -95)
50
51do
52 local a = {x=0}
53 function a:add (x) self.x, a.y = self.x+x, 20; return self end
54 assert(a:add(10):add(20):add(30).x == 60 and a.y == 20)
55end
56
57local a = {b={c={}}}
58
59function a.b.c.f1 (x) return x+1 end
60function a.b.c:f2 (x,y) self[x] = y end
61assert(a.b.c.f1(4) == 5)
62a.b.c:f2('k', 12); assert(a.b.c.k == 12)
63
64print('+')
65
66t = nil -- 'declare' t
67function f(a,b,c) local d = 'a'; t={a,b,c,d} end
68
69f( -- this line change must be valid
70 1,2)
71assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a')
72f(1,2, -- this one too
73 3,4)
74assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a')
75
76t = nil -- delete 't'
77
78function fat(x)
79 if x <= 1 then return 1
80 else return x*load("return fat(" .. x-1 .. ")", "")()
81 end
82end
83
84assert(load "load 'assert(fat(6)==720)' () ")()
85a = load('return fat(5), 3')
86local a,b = a()
87assert(a == 120 and b == 3)
88fat = nil
89print('+')
90
91local function err_on_n (n)
92 if n==0 then error(); exit(1);
93 else err_on_n (n-1); exit(1);
94 end
95end
96
97do
98 local function dummy (n)
99 if n > 0 then
100 assert(not pcall(err_on_n, n))
101 dummy(n-1)
102 end
103 end
104
105 dummy(10)
106end
107
108_G.deep = nil -- "declaration" (used by 'all.lua')
109
110function deep (n)
111 if n>0 then deep(n-1) end
112end
113deep(10)
114deep(180)
115
116
117print"testing tail calls"
118
119function deep (n) if n>0 then return deep(n-1) else return 101 end end
120assert(deep(30000) == 101)
121a = {}
122function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end
123assert(a:deep(30000) == 101)
124
125do -- tail calls x varargs
126 local function foo (x, ...) local a = {...}; return x, a[1], a[2] end
127
128 local function foo1 (x) return foo(10, x, x + 1) end
129
130 local a, b, c = foo1(-2)
131 assert(a == 10 and b == -2 and c == -1)
132
133 -- tail calls x metamethods
134 local t = setmetatable({}, {__call = foo})
135 local function foo2 (x) return t(10, x) end
136 a, b, c = foo2(100)
137 assert(a == t and b == 10 and c == 100)
138
139 a, b = (function () return foo() end)()
140 assert(a == nil and b == nil)
141
142 local X, Y, A
143 local function foo (x, y, ...) X = x; Y = y; A = {...} end
144 local function foo1 (...) return foo(...) end
145
146 local a, b, c = foo1()
147 assert(X == nil and Y == nil and #A == 0)
148
149 a, b, c = foo1(10)
150 assert(X == 10 and Y == nil and #A == 0)
151
152 a, b, c = foo1(10, 20)
153 assert(X == 10 and Y == 20 and #A == 0)
154
155 a, b, c = foo1(10, 20, 30)
156 assert(X == 10 and Y == 20 and #A == 1 and A[1] == 30)
157end
158
159
160do -- C-stack overflow while handling C-stack overflow
161 local function loop ()
162 assert(pcall(loop))
163 end
164
165 local err, msg = xpcall(loop, loop)
166 assert(not err and string.find(msg, "error"))
167end
168
169
170
171do -- tail calls x chain of __call
172 local n = 10000 -- depth
173
174 local function foo ()
175 if n == 0 then return 1023
176 else n = n - 1; return foo()
177 end
178 end
179
180 -- build a chain of __call metamethods ending in function 'foo'
181 for i = 1, 100 do
182 foo = setmetatable({}, {__call = foo})
183 end
184
185 -- call the first one as a tail call in a new coroutine
186 -- (to ensure stack is not preallocated)
187 assert(coroutine.wrap(function() return foo() end)() == 1023)
188end
189
190print('+')
191
192
193do -- testing chains of '__call'
194 local N = 20
195 local u = table.pack
196 for i = 1, N do
197 u = setmetatable({i}, {__call = u})
198 end
199
200 local Res = u("a", "b", "c")
201
202 assert(Res.n == N + 3)
203 for i = 1, N do
204 assert(Res[i][1] == i)
205 end
206 assert(Res[N + 1] == "a" and Res[N + 2] == "b" and Res[N + 3] == "c")
207end
208
209
210a = nil
211(function (x) a=x end)(23)
212assert(a == 23 and (function (x) return x*2 end)(20) == 40)
213
214
215-- testing closures
216
217-- fixed-point operator
218local Z = function (le)
219 local function a (f)
220 return le(function (x) return f(f)(x) end)
221 end
222 return a(a)
223 end
224
225
226-- non-recursive factorial
227
228local F = function (f)
229 return function (n)
230 if n == 0 then return 1
231 else return n*f(n-1) end
232 end
233 end
234
235local fat = Z(F)
236
237assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4))
238
239local function g (z)
240 local function f (a,b,c,d)
241 return function (x,y) return a+b+c+d+a+x+y+z end
242 end
243 return f(z,z+1,z+2,z+3)
244end
245
246local f = g(10)
247assert(f(9, 16) == 10+11+12+13+10+9+16+10)
248
249print('+')
250
251-- testing multiple returns
252
253local function unlpack (t, i)
254 i = i or 1
255 if (i <= #t) then
256 return t[i], unlpack(t, i+1)
257 end
258end
259
260local function equaltab (t1, t2)
261 assert(#t1 == #t2)
262 for i = 1, #t1 do
263 assert(t1[i] == t2[i])
264 end
265end
266
267local pack = function (...) return (table.pack(...)) end
268
269local function f() return 1,2,30,4 end
270local function ret2 (a,b) return a,b end
271
272local a,b,c,d = unlpack{1,2,3}
273assert(a==1 and b==2 and c==3 and d==nil)
274a = {1,2,3,4,false,10,'alo',false,assert}
275equaltab(pack(unlpack(a)), a)
276equaltab(pack(unlpack(a), -1), {1,-1})
277a,b,c,d = ret2(f()), ret2(f())
278assert(a==1 and b==1 and c==2 and d==nil)
279a,b,c,d = unlpack(pack(ret2(f()), ret2(f())))
280assert(a==1 and b==1 and c==2 and d==nil)
281a,b,c,d = unlpack(pack(ret2(f()), (ret2(f()))))
282assert(a==1 and b==1 and c==nil and d==nil)
283
284a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}}
285assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b")
286
287
288-- testing calls with 'incorrect' arguments
289rawget({}, "x", 1)
290rawset({}, "x", 1, 2)
291assert(math.sin(1,2) == math.sin(1))
292table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg")
293
294
295-- test for generic load
296local x = "-- a comment\0\0\0\n x = 10 + \n23; \
297 local a = function () x = 'hi' end; \
298 return '\0'"
299local function read1 (x)
300 local i = 0
301 return function ()
302 collectgarbage()
303 i=i+1
304 return string.sub(x, i, i)
305 end
306end
307
308local function cannotload (msg, a,b)
309 assert(not a and string.find(b, msg))
310end
311
312a = assert(load(read1(x), "modname", "t", _G))
313assert(a() == "\0" and _G.x == 33)
314assert(debug.getinfo(a).source == "modname")
315-- cannot read text in binary mode
316cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {}))
317cannotload("attempt to load a text chunk", load(x, "modname", "b"))
318
319a = assert(load(function () return nil end))
320a() -- empty chunk
321
322assert(not load(function () return true end))
323
324
325-- small bug
326local t = {nil, "return ", "3"}
327f, msg = load(function () return table.remove(t, 1) end)
328assert(f() == nil) -- should read the empty chunk
329
330-- another small bug (in 5.2.1)
331f = load(string.dump(function () return 1 end), nil, "b", {})
332assert(type(f) == "function" and f() == 1)
333
334
335do -- another bug (in 5.4.0)
336 -- loading a binary long string interrupted by GC cycles
337 local f = string.dump(function ()
338 return '01234567890123456789012345678901234567890123456789'
339 end)
340 f = load(read1(f))
341 assert(f() == '01234567890123456789012345678901234567890123456789')
342end
343
344
345x = string.dump(load("x = 1; return x"))
346a = assert(load(read1(x), nil, "b"))
347assert(a() == 1 and _G.x == 1)
348cannotload("attempt to load a binary chunk", load(read1(x), nil, "t"))
349cannotload("attempt to load a binary chunk", load(x, nil, "t"))
350_G.x = nil
351
352assert(not pcall(string.dump, print)) -- no dump of C functions
353
354cannotload("unexpected symbol", load(read1("*a = 123")))
355cannotload("unexpected symbol", load("*a = 123"))
356cannotload("hhi", load(function () error("hhi") end))
357
358-- any value is valid for _ENV
359assert(load("return _ENV", nil, nil, 123)() == 123)
360
361
362-- load when _ENV is not first upvalue
363local x; XX = 123
364local function h ()
365 local y=x -- use 'x', so that it becomes 1st upvalue
366 return XX -- global name
367end
368local d = string.dump(h)
369x = load(d, "", "b")
370assert(debug.getupvalue(x, 2) == '_ENV')
371debug.setupvalue(x, 2, _G)
372assert(x() == 123)
373
374assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17)
375XX = nil
376
377-- test generic load with nested functions
378x = [[
379 return function (x)
380 return function (y)
381 return function (z)
382 return x+y+z
383 end
384 end
385 end
386]]
387a = assert(load(read1(x), "read", "t"))
388assert(a()(2)(3)(10) == 15)
389
390-- repeat the test loading a binary chunk
391x = string.dump(a)
392a = assert(load(read1(x), "read", "b"))
393assert(a()(2)(3)(10) == 15)
394
395
396-- test for dump/undump with upvalues
397local a, b = 20, 30
398x = load(string.dump(function (x)
399 if x == "set" then a = 10+b; b = b+1 else
400 return a
401 end
402end), "", "b", nil)
403assert(x() == nil)
404assert(debug.setupvalue(x, 1, "hi") == "a")
405assert(x() == "hi")
406assert(debug.setupvalue(x, 2, 13) == "b")
407assert(not debug.setupvalue(x, 3, 10)) -- only 2 upvalues
408x("set")
409assert(x() == 23)
410x("set")
411assert(x() == 24)
412
413-- test for dump/undump with many upvalues
414do
415 local nup = 200 -- maximum number of local variables
416 local prog = {"local a1"}
417 for i = 2, nup do prog[#prog + 1] = ", a" .. i end
418 prog[#prog + 1] = " = 1"
419 for i = 2, nup do prog[#prog + 1] = ", " .. i end
420 local sum = 1
421 prog[#prog + 1] = "; return function () return a1"
422 for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end
423 prog[#prog + 1] = " end"
424 prog = table.concat(prog)
425 local f = assert(load(prog))()
426 assert(f() == sum)
427
428 f = load(string.dump(f)) -- main chunk now has many upvalues
429 local a = 10
430 local h = function () return a end
431 for i = 1, nup do
432 debug.upvaluejoin(f, i, h, 1)
433 end
434 assert(f() == 10 * nup)
435end
436
437-- test for long method names
438do
439 local t = {x = 1}
440 function t:_012345678901234567890123456789012345678901234567890123456789 ()
441 return self.x
442 end
443 assert(t:_012345678901234567890123456789012345678901234567890123456789() == 1)
444end
445
446
447-- test for bug in parameter adjustment
448assert((function () return nil end)(4) == nil)
449assert((function () local a; return a end)(4) == nil)
450assert((function (a) return a end)() == nil)
451
452
453print("testing binary chunks")
454do
455 local header = string.pack("c4BBc6BBB",
456 "\27Lua", -- signature
457 0x54, -- version 5.4 (0x54)
458 0, -- format
459 "\x19\x93\r\n\x1a\n", -- data
460 4, -- size of instruction
461 string.packsize("j"), -- sizeof(lua integer)
462 string.packsize("n") -- sizeof(lua number)
463 )
464 local c = string.dump(function ()
465 local a = 1; local b = 3;
466 local f = function () return a + b + _ENV.c; end -- upvalues
467 local s1 = "a constant"
468 local s2 = "another constant"
469 return a + b * 3
470 end)
471
472 assert(assert(load(c))() == 10)
473
474 -- check header
475 assert(string.sub(c, 1, #header) == header)
476 -- check LUAC_INT and LUAC_NUM
477 local ci, cn = string.unpack("jn", c, #header + 1)
478 assert(ci == 0x5678 and cn == 370.5)
479
480 -- corrupted header
481 for i = 1, #header do
482 local s = string.sub(c, 1, i - 1) ..
483 string.char(string.byte(string.sub(c, i, i)) + 1) ..
484 string.sub(c, i + 1, -1)
485 assert(#s == #c)
486 assert(not load(s))
487 end
488
489 -- loading truncated binary chunks
490 for i = 1, #c - 1 do
491 local st, msg = load(string.sub(c, 1, i))
492 assert(not st and string.find(msg, "truncated"))
493 end
494end
495
496print('OK')
497return deep
diff --git a/zig-lua/lua-5.4.7/testes/closure.lua b/zig-lua/lua-5.4.7/testes/closure.lua
new file mode 100644
index 0000000..ea038e8
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/closure.lua
@@ -0,0 +1,272 @@
1-- $Id: testes/closure.lua $
2-- See Copyright Notice in file all.lua
3
4print "testing closures"
5
6local A,B = 0,{g=10}
7local 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
23end
24
25local a = f(10)
26-- force a GC in this level
27local x = {[1] = {}} -- to detect a GC
28setmetatable(x, {__mode = 'kv'})
29while x[1] do -- repeat until GC
30 local a = A..A..A..A -- create garbage
31 A = A+1
32end
33assert(a[1]() == 20+A)
34assert(a[1]() == 30+A)
35assert(a[2]() == 10+A)
36collectgarbage()
37assert(a[2]() == 20+A)
38assert(a[2]() == 30+A)
39assert(a[3]() == 20+A)
40assert(a[8]() == 10+A)
41assert(getmetatable(x).__mode == 'kv')
42assert(B.g == 19)
43
44
45-- testing equality
46a = {}
47
48for i = 1, 5 do a[i] = function (x) return i + a + _ENV end end
49assert(a[3] ~= a[4] and a[4] ~= a[5])
50
51do
52 local a = function (x) return math.sin(_ENV[x]) end
53 local function f()
54 return a
55 end
56 assert(f() == f())
57end
58
59
60-- testing closures with 'for' control variable
61a = {}
62for i=1,10 do
63 a[i] = {set = function(x) i=x end, get = function () return i end}
64 if i == 3 then break end
65end
66assert(a[4] == undef)
67a[1].set(10)
68assert(a[2].get() == 2)
69a[2].set('a')
70assert(a[3].get() == 3)
71assert(a[2].get() == 'a')
72
73a = {}
74local t = {"a", "b"}
75for i = 1, #t do
76 local k = t[i]
77 a[i] = {set = function(x, y) i=x; k=y end,
78 get = function () return i, k end}
79 if i == 2 then break end
80end
81a[1].set(10, 20)
82local r,s = a[2].get()
83assert(r == 2 and s == 'b')
84r,s = a[1].get()
85assert(r == 10 and s == 20)
86a[2].set('a', 'b')
87r,s = a[2].get()
88assert(r == "a" and s == "b")
89
90
91-- testing closures with 'for' control variable x break
92local f
93for i=1,3 do
94 f = function () return i end
95 break
96end
97assert(f() == 1)
98
99for k = 1, #t do
100 local v = t[k]
101 f = function () return k, v end
102 break
103end
104assert(({f()})[1] == 1)
105assert(({f()})[2] == "a")
106
107
108-- testing closure x break x return x errors
109
110local b
111function 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
129end
130
131for i=1,3 do
132 f(i)
133 assert(b('get') == 'xuxu')
134 b('set', 10); assert(b('get') == 10+i)
135 b = nil
136end
137
138pcall(f, 4);
139assert(b('get') == 'xuxu')
140b('set', 10); assert(b('get') == 14)
141
142
143local y, w
144-- testing multi-level closure
145function f(x)
146 return function (y)
147 return function (z) return w+x+y+z end
148 end
149end
150
151y = f(10)
152w = 1.345
153assert(y(20)(30) == 60+w)
154
155
156-- testing closures x break
157do
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)
174end
175
176
177-- testing closures x repeat-until
178
179local a = {}
180local i = 1
181repeat
182 local x = i
183 a[i] = function () i = x+1; return x end
184until i > 10 or a[i]() ~= x
185assert(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
189a = {}
190for 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
212end
213
214for i = 1, 10 do
215 assert(a[i](i * 10) == i % 3 and a[i]() == i * 10)
216end
217
218print'+'
219
220
221-- test for correctly closing upvalues in tail calls of vararg functions
222local 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)
227end
228t()
229
230
231-- test for debug manipulation of upvalues
232local debug = require'debug'
233
234local foo1, foo2, foo3
235do
236 local a , b, c = 3, 5, 7
237 foo1 = function () return a+b end;
238 foo2 = function () return b+a end;
239 do
240 local a = 10
241 foo3 = function () return a+b end;
242 end
243end
244
245assert(debug.upvalueid(foo1, 1))
246assert(debug.upvalueid(foo1, 2))
247assert(not debug.upvalueid(foo1, 3))
248assert(debug.upvalueid(foo1, 1) == debug.upvalueid(foo2, 2))
249assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo2, 1))
250assert(debug.upvalueid(foo3, 1))
251assert(debug.upvalueid(foo1, 1) ~= debug.upvalueid(foo3, 1))
252assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo3, 2))
253
254assert(debug.upvalueid(string.gmatch("x", "x"), 1) ~= nil)
255
256assert(foo1() == 3 + 5 and foo2() == 5 + 3)
257debug.upvaluejoin(foo1, 2, foo2, 2)
258assert(foo1() == 3 + 3 and foo2() == 5 + 3)
259assert(foo3() == 10 + 5)
260debug.upvaluejoin(foo3, 2, foo2, 1)
261assert(foo3() == 10 + 5)
262debug.upvaluejoin(foo3, 2, foo2, 2)
263assert(foo3() == 10 + 3)
264
265assert(not pcall(debug.upvaluejoin, foo1, 3, foo2, 1))
266assert(not pcall(debug.upvaluejoin, foo1, 1, foo2, 3))
267assert(not pcall(debug.upvaluejoin, foo1, 0, foo2, 1))
268assert(not pcall(debug.upvaluejoin, print, 1, foo2, 1))
269assert(not pcall(debug.upvaluejoin, {}, 1, foo2, 1))
270assert(not pcall(debug.upvaluejoin, foo1, 1, print, 1))
271
272print'OK'
diff --git a/zig-lua/lua-5.4.7/testes/code.lua b/zig-lua/lua-5.4.7/testes/code.lua
new file mode 100644
index 0000000..bd4b10d
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/code.lua
@@ -0,0 +1,449 @@
1-- $Id: testes/code.lua $
2-- See Copyright Notice in file all.lua
3
4if T==nil then
5 (Message or print)('\n >>> testC not active: skipping opcode tests <<<\n')
6 return
7end
8print "testing code generation and optimizations"
9
10-- to test constant propagation
11local k0aux <const> = 0
12local k0 <const> = k0aux
13local k1 <const> = 1
14local k3 <const> = 3
15local k6 <const> = k3 + (k3 << k0)
16local kFF0 <const> = 0xFF0
17local k3_78 <const> = 3.78
18local x, k3_78_4 <const> = 10, k3_78 / 4
19assert(x == 10)
20
21local kx <const> = "x"
22
23local kTrue <const> = true
24local kFalse <const> = false
25
26local kNil <const> = nil
27
28-- this code gave an error for the code checker
29do
30 local function f (a)
31 for k,v,w in a do end
32 end
33end
34
35
36-- testing reuse in constant table
37local function checkKlist (func, list)
38 local k = T.listk(func)
39 assert(#k == #list)
40 for i = 1, #k do
41 assert(k[i] == list[i] and math.type(k[i]) == math.type(list[i]))
42 end
43end
44
45local function foo ()
46 local a
47 a = k3;
48 a = 0; a = 0.0; a = -7 + 7
49 a = k3_78/4; a = k3_78_4
50 a = -k3_78/4; a = k3_78/4; a = -3.78/4
51 a = -3.79/4; a = 0.0; a = -0;
52 a = k3; a = 3.0; a = 3; a = 3.0
53end
54
55checkKlist(foo, {3.78/4, -3.78/4, -3.79/4})
56
57
58foo = function (f, a)
59 f(100 * 1000)
60 f(100.0 * 1000)
61 f(-100 * 1000)
62 f(-100 * 1000.0)
63 f(100000)
64 f(100000.0)
65 f(-100000)
66 f(-100000.0)
67 end
68
69checkKlist(foo, {100000, 100000.0, -100000, -100000.0})
70
71
72-- floats x integers
73foo = function (t, a)
74 t[a] = 1; t[a] = 1.0
75 t[a] = 1; t[a] = 1.0
76 t[a] = 2; t[a] = 2.0
77 t[a] = 0; t[a] = 0.0
78 t[a] = 1; t[a] = 1.0
79 t[a] = 2; t[a] = 2.0
80 t[a] = 0; t[a] = 0.0
81end
82
83checkKlist(foo, {1, 1.0, 2, 2.0, 0, 0.0})
84
85
86-- testing opcodes
87
88-- check that 'f' opcodes match '...'
89local function check (f, ...)
90 local arg = {...}
91 local c = T.listcode(f)
92 for i=1, #arg do
93 local opcode = string.match(c[i], "%u%w+")
94 -- print(arg[i], opcode)
95 assert(arg[i] == opcode)
96 end
97 assert(c[#arg+2] == undef)
98end
99
100
101-- check that 'f' opcodes match '...' and that 'f(p) == r'.
102local function checkR (f, p, r, ...)
103 local r1 = f(p)
104 assert(r == r1 and math.type(r) == math.type(r1))
105 check(f, ...)
106end
107
108
109-- check that 'a' and 'b' has the same opcodes
110local function checkequal (a, b)
111 a = T.listcode(a)
112 b = T.listcode(b)
113 assert(#a == #b)
114 for i = 1, #a do
115 a[i] = string.gsub(a[i], '%b()', '') -- remove line number
116 b[i] = string.gsub(b[i], '%b()', '') -- remove line number
117 assert(a[i] == b[i])
118 end
119end
120
121
122-- some basic instructions
123check(function () -- function does not create upvalues
124 (function () end){f()}
125end, 'CLOSURE', 'NEWTABLE', 'EXTRAARG', 'GETTABUP', 'CALL',
126 'SETLIST', 'CALL', 'RETURN0')
127
128check(function (x) -- function creates upvalues
129 (function () return x end){f()}
130end, 'CLOSURE', 'NEWTABLE', 'EXTRAARG', 'GETTABUP', 'CALL',
131 'SETLIST', 'CALL', 'RETURN')
132
133
134-- sequence of LOADNILs
135check(function ()
136 local kNil <const> = nil
137 local a,b,c
138 local d; local e;
139 local f,g,h;
140 d = nil; d=nil; b=nil; a=kNil; c=nil;
141end, 'LOADNIL', 'RETURN0')
142
143check(function ()
144 local a,b,c,d = 1,1,1,1
145 d=nil;c=nil;b=nil;a=nil
146end, 'LOADI', 'LOADI', 'LOADI', 'LOADI', 'LOADNIL', 'RETURN0')
147
148do
149 local a,b,c,d = 1,1,1,1
150 d=nil;c=nil;b=nil;a=nil
151 assert(a == nil and b == nil and c == nil and d == nil)
152end
153
154
155-- single return
156check (function (a,b,c) return a end, 'RETURN1')
157
158
159-- infinite loops
160check(function () while kTrue do local a = -1 end end,
161'LOADI', 'JMP', 'RETURN0')
162
163check(function () while 1 do local a = -1 end end,
164'LOADI', 'JMP', 'RETURN0')
165
166check(function () repeat local x = 1 until true end,
167'LOADI', 'RETURN0')
168
169
170-- concat optimization
171check(function (a,b,c,d) return a..b..c..d end,
172 'MOVE', 'MOVE', 'MOVE', 'MOVE', 'CONCAT', 'RETURN1')
173
174-- not
175check(function () return not not nil end, 'LOADFALSE', 'RETURN1')
176check(function () return not not kFalse end, 'LOADFALSE', 'RETURN1')
177check(function () return not not true end, 'LOADTRUE', 'RETURN1')
178check(function () return not not k3 end, 'LOADTRUE', 'RETURN1')
179
180-- direct access to locals
181check(function ()
182 local a,b,c,d
183 a = b*a
184 c.x, a[b] = -((a + d/b - a[b]) ^ a.x), b
185end,
186 'LOADNIL',
187 'MUL', 'MMBIN',
188 'DIV', 'MMBIN', 'ADD', 'MMBIN', 'GETTABLE', 'SUB', 'MMBIN',
189 'GETFIELD', 'POW', 'MMBIN', 'UNM', 'SETTABLE', 'SETFIELD', 'RETURN0')
190
191
192-- direct access to constants
193check(function ()
194 local a,b
195 local c = kNil
196 a[kx] = 3.2
197 a.x = b
198 a[b] = 'x'
199end,
200 'LOADNIL', 'SETFIELD', 'SETFIELD', 'SETTABLE', 'RETURN0')
201
202-- "get/set table" with numeric indices
203check(function (a)
204 local k255 <const> = 255
205 a[1] = a[100]
206 a[k255] = a[256]
207 a[256] = 5
208end,
209 'GETI', 'SETI',
210 'LOADI', 'GETTABLE', 'SETI',
211 'LOADI', 'SETTABLE', 'RETURN0')
212
213check(function ()
214 local a,b
215 a = a - a
216 b = a/a
217 b = 5-4
218end,
219 'LOADNIL', 'SUB', 'MMBIN', 'DIV', 'MMBIN', 'LOADI', 'RETURN0')
220
221check(function ()
222 local a,b
223 a[kTrue] = false
224end,
225 'LOADNIL', 'LOADTRUE', 'SETTABLE', 'RETURN0')
226
227
228-- equalities
229checkR(function (a) if a == 1 then return 2 end end, 1, 2,
230 'EQI', 'JMP', 'LOADI', 'RETURN1')
231
232checkR(function (a) if -4.0 == a then return 2 end end, -4, 2,
233 'EQI', 'JMP', 'LOADI', 'RETURN1')
234
235checkR(function (a) if a == "hi" then return 2 end end, 10, nil,
236 'EQK', 'JMP', 'LOADI', 'RETURN1')
237
238checkR(function (a) if a == 10000 then return 2 end end, 1, nil,
239 'EQK', 'JMP', 'LOADI', 'RETURN1') -- number too large
240
241checkR(function (a) if -10000 == a then return 2 end end, -10000, 2,
242 'EQK', 'JMP', 'LOADI', 'RETURN1') -- number too large
243
244-- comparisons
245
246checkR(function (a) if -10 <= a then return 2 end end, -10, 2,
247 'GEI', 'JMP', 'LOADI', 'RETURN1')
248
249checkR(function (a) if 128.0 > a then return 2 end end, 129, nil,
250 'LTI', 'JMP', 'LOADI', 'RETURN1')
251
252checkR(function (a) if -127.0 < a then return 2 end end, -127, nil,
253 'GTI', 'JMP', 'LOADI', 'RETURN1')
254
255checkR(function (a) if 10 < a then return 2 end end, 11, 2,
256 'GTI', 'JMP', 'LOADI', 'RETURN1')
257
258checkR(function (a) if 129 < a then return 2 end end, 130, 2,
259 'LOADI', 'LT', 'JMP', 'LOADI', 'RETURN1')
260
261checkR(function (a) if a >= 23.0 then return 2 end end, 25, 2,
262 'GEI', 'JMP', 'LOADI', 'RETURN1')
263
264checkR(function (a) if a >= 23.1 then return 2 end end, 0, nil,
265 'LOADK', 'LE', 'JMP', 'LOADI', 'RETURN1')
266
267checkR(function (a) if a > 2300.0 then return 2 end end, 0, nil,
268 'LOADF', 'LT', 'JMP', 'LOADI', 'RETURN1')
269
270
271-- constant folding
272local function checkK (func, val)
273 check(func, 'LOADK', 'RETURN1')
274 checkKlist(func, {val})
275 assert(func() == val)
276end
277
278local function checkI (func, val)
279 check(func, 'LOADI', 'RETURN1')
280 checkKlist(func, {})
281 assert(func() == val)
282end
283
284local function checkF (func, val)
285 check(func, 'LOADF', 'RETURN1')
286 checkKlist(func, {})
287 assert(func() == val)
288end
289
290checkF(function () return 0.0 end, 0.0)
291checkI(function () return k0 end, 0)
292checkI(function () return -k0//1 end, 0)
293checkK(function () return 3^-1 end, 1/3)
294checkK(function () return (1 + 1)^(50 + 50) end, 2^100)
295checkK(function () return (-2)^(31 - 2) end, -0x20000000 + 0.0)
296checkF(function () return (-k3^0 + 5) // 3.0 end, 1.0)
297checkI(function () return -k3 % 5 end, 2)
298checkF(function () return -((2.0^8 + -(-1)) % 8)/2 * 4 - 3 end, -5.0)
299checkF(function () return -((2^8 + -(-1)) % 8)//2 * 4 - 3 end, -7.0)
300checkI(function () return 0xF0.0 | 0xCC.0 ~ 0xAA & 0xFD end, 0xF4)
301checkI(function () return ~(~kFF0 | kFF0) end, 0)
302checkI(function () return ~~-1024.0 end, -1024)
303checkI(function () return ((100 << k6) << -4) >> 2 end, 100)
304
305-- borders around MAXARG_sBx ((((1 << 17) - 1) >> 1) == 65535)
306local a = 17; local sbx = ((1 << a) - 1) >> 1 -- avoid folding
307local border <const> = 65535
308checkI(function () return border end, sbx)
309checkI(function () return -border end, -sbx)
310checkI(function () return border + 1 end, sbx + 1)
311checkK(function () return border + 2 end, sbx + 2)
312checkK(function () return -(border + 1) end, -(sbx + 1))
313
314local border <const> = 65535.0
315checkF(function () return border end, sbx + 0.0)
316checkF(function () return -border end, -sbx + 0.0)
317checkF(function () return border + 1 end, (sbx + 1.0))
318checkK(function () return border + 2 end, (sbx + 2.0))
319checkK(function () return -(border + 1) end, -(sbx + 1.0))
320
321
322-- immediate operands
323checkR(function (x) return x + k1 end, 10, 11, 'ADDI', 'MMBINI', 'RETURN1')
324checkR(function (x) return x - 127 end, 10, -117, 'ADDI', 'MMBINI', 'RETURN1')
325checkR(function (x) return 128 + x end, 0.0, 128.0,
326 'ADDI', 'MMBINI', 'RETURN1')
327checkR(function (x) return x * -127 end, -1.0, 127.0,
328 'MULK', 'MMBINK', 'RETURN1')
329checkR(function (x) return 20 * x end, 2, 40, 'MULK', 'MMBINK', 'RETURN1')
330checkR(function (x) return x ^ -2 end, 2, 0.25, 'POWK', 'MMBINK', 'RETURN1')
331checkR(function (x) return x / 40 end, 40, 1.0, 'DIVK', 'MMBINK', 'RETURN1')
332checkR(function (x) return x // 1 end, 10.0, 10.0,
333 'IDIVK', 'MMBINK', 'RETURN1')
334checkR(function (x) return x % (100 - 10) end, 91, 1,
335 'MODK', 'MMBINK', 'RETURN1')
336checkR(function (x) return k1 << x end, 3, 8, 'SHLI', 'MMBINI', 'RETURN1')
337checkR(function (x) return x << 127 end, 10, 0, 'SHRI', 'MMBINI', 'RETURN1')
338checkR(function (x) return x << -127 end, 10, 0, 'SHRI', 'MMBINI', 'RETURN1')
339checkR(function (x) return x >> 128 end, 8, 0, 'SHRI', 'MMBINI', 'RETURN1')
340checkR(function (x) return x >> -127 end, 8, 0, 'SHRI', 'MMBINI', 'RETURN1')
341checkR(function (x) return x & 1 end, 9, 1, 'BANDK', 'MMBINK', 'RETURN1')
342checkR(function (x) return 10 | x end, 1, 11, 'BORK', 'MMBINK', 'RETURN1')
343checkR(function (x) return -10 ~ x end, -1, 9, 'BXORK', 'MMBINK', 'RETURN1')
344
345-- K operands in arithmetic operations
346checkR(function (x) return x + 0.0 end, 1, 1.0, 'ADDK', 'MMBINK', 'RETURN1')
347-- check(function (x) return 128 + x end, 'ADDK', 'MMBINK', 'RETURN1')
348checkR(function (x) return x * -10000 end, 2, -20000,
349 'MULK', 'MMBINK', 'RETURN1')
350-- check(function (x) return 20 * x end, 'MULK', 'MMBINK', 'RETURN1')
351checkR(function (x) return x ^ 0.5 end, 4, 2.0, 'POWK', 'MMBINK', 'RETURN1')
352checkR(function (x) return x / 2.0 end, 4, 2.0, 'DIVK', 'MMBINK', 'RETURN1')
353checkR(function (x) return x // 10000 end, 10000, 1,
354 'IDIVK', 'MMBINK', 'RETURN1')
355checkR(function (x) return x % (100.0 - 10) end, 91, 1.0,
356 'MODK', 'MMBINK', 'RETURN1')
357
358-- no foldings (and immediate operands)
359check(function () return -0.0 end, 'LOADF', 'UNM', 'RETURN1')
360check(function () return k3/0 end, 'LOADI', 'DIVK', 'MMBINK', 'RETURN1')
361check(function () return 0%0 end, 'LOADI', 'MODK', 'MMBINK', 'RETURN1')
362check(function () return -4//0 end, 'LOADI', 'IDIVK', 'MMBINK', 'RETURN1')
363check(function (x) return x >> 2.0 end, 'LOADF', 'SHR', 'MMBIN', 'RETURN1')
364check(function (x) return x << 128 end, 'LOADI', 'SHL', 'MMBIN', 'RETURN1')
365check(function (x) return x & 2.0 end, 'LOADF', 'BAND', 'MMBIN', 'RETURN1')
366
367-- basic 'for' loops
368check(function () for i = -10, 10.5 do end end,
369'LOADI', 'LOADK', 'LOADI', 'FORPREP', 'FORLOOP', 'RETURN0')
370check(function () for i = 0xfffffff, 10.0, 1 do end end,
371'LOADK', 'LOADF', 'LOADI', 'FORPREP', 'FORLOOP', 'RETURN0')
372
373-- bug in constant folding for 5.1
374check(function () return -nil end, 'LOADNIL', 'UNM', 'RETURN1')
375
376
377check(function ()
378 local a,b,c
379 b[c], a = c, b
380 b[a], a = c, b
381 a, b = c, a
382 a = a
383end,
384 'LOADNIL',
385 'MOVE', 'MOVE', 'SETTABLE',
386 'MOVE', 'MOVE', 'MOVE', 'SETTABLE',
387 'MOVE', 'MOVE', 'MOVE',
388 -- no code for a = a
389 'RETURN0')
390
391
392-- x == nil , x ~= nil
393-- checkequal(function (b) if (a==nil) then a=1 end; if a~=nil then a=1 end end,
394-- function () if (a==9) then a=1 end; if a~=9 then a=1 end end)
395
396-- check(function () if a==nil then a='a' end end,
397-- 'GETTABUP', 'EQ', 'JMP', 'SETTABUP', 'RETURN')
398
399do -- tests for table access in upvalues
400 local t
401 check(function () t[kx] = t.y end, 'GETTABUP', 'SETTABUP')
402 check(function (a) t[a()] = t[a()] end,
403 'MOVE', 'CALL', 'GETUPVAL', 'MOVE', 'CALL',
404 'GETUPVAL', 'GETTABLE', 'SETTABLE')
405end
406
407-- de morgan
408checkequal(function () local a; if not (a or b) then b=a end end,
409 function () local a; if (not a and not b) then b=a end end)
410
411checkequal(function (l) local a; return 0 <= a and a <= l end,
412 function (l) local a; return not (not(a >= 0) or not(a <= l)) end)
413
414
415-- if-break optimizations
416check(function (a, b)
417 while a do
418 if b then break else a = a + 1 end
419 end
420 end,
421'TEST', 'JMP', 'TEST', 'JMP', 'ADDI', 'MMBINI', 'JMP', 'RETURN0')
422
423checkequal(function () return 6 or true or nil end,
424 function () return k6 or kTrue or kNil end)
425
426checkequal(function () return 6 and true or nil end,
427 function () return k6 and kTrue or kNil end)
428
429
430do -- string constants
431 local k0 <const> = "00000000000000000000000000000000000000000000000000"
432 local function f1 ()
433 local k <const> = k0
434 return function ()
435 return function () return k end
436 end
437 end
438
439 local f2 = f1()
440 local f3 = f2()
441 assert(f3() == k0)
442 checkK(f3, k0)
443 -- string is not needed by other functions
444 assert(T.listk(f1)[1] == nil)
445 assert(T.listk(f2)[1] == nil)
446end
447
448print 'OK'
449
diff --git a/zig-lua/lua-5.4.7/testes/constructs.lua b/zig-lua/lua-5.4.7/testes/constructs.lua
new file mode 100644
index 0000000..6ac6816
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/constructs.lua
@@ -0,0 +1,406 @@
1-- $Id: testes/constructs.lua $
2-- See Copyright Notice in file all.lua
3
4;;print "testing syntax";;
5
6local debug = require "debug"
7
8
9local function checkload (s, msg)
10 assert(string.find(select(2, load(s)), msg))
11end
12
13-- testing semicollons
14local a
15do ;;; end
16; do ; a = 3; assert(a == 3) end;
17;
18
19
20-- invalid operations should not raise errors when not executed
21if false then a = 3 // 0; a = 0 % 0 end
22
23
24-- testing priorities
25
26assert(2^3^2 == 2^(3^2));
27assert(2^3*4 == (2^3)*4);
28assert(2.0^-2 == 1/4 and -2^- -2 == - - -4);
29assert(not nil and 2 and not(2>3 or 3<2));
30assert(-3-1-5 == 0+0-9);
31assert(-2^2 == -4 and (-2)^2 == 4 and 2*2-3-1 == 0);
32assert(-3%5 == 2 and -3+5 == 2)
33assert(2*1+3/3 == 3 and 1+2 .. 3*1 == "33");
34assert(not(2+1 > 3*1) and "a".."b" > "a");
35
36assert(0xF0 | 0xCC ~ 0xAA & 0xFD == 0xF4)
37assert(0xFD & 0xAA ~ 0xCC | 0xF0 == 0xF4)
38assert(0xF0 & 0x0F + 1 == 0x10)
39
40assert(3^4//2^3//5 == 2)
41
42assert(-3+4*5//2^3^2//9+4%10/3 == (-3)+(((4*5)//(2^(3^2)))//9)+((4%10)/3))
43
44assert(not ((true or false) and nil))
45assert( true or false and nil)
46
47-- old bug
48assert((((1 or false) and true) or false) == true)
49assert((((nil and true) or false) and true) == false)
50
51local a,b = 1,nil;
52assert(-(1 or 2) == -1 and (1 and 2)+(-1.25 or -4) == 0.75);
53local x = ((b or a)+1 == 2 and (10 or a)+1 == 11); assert(x);
54x = (((2<3) or 1) == true and (2<3 and 4) == 4); assert(x);
55
56local x, y = 1, 2;
57assert((x>y) and x or y == 2);
58x,y=2,1;
59assert((x>y) and x or y == 2);
60
61assert(1234567890 == tonumber('1234567890') and 1234567890+1 == 1234567891)
62
63do -- testing operators with diffent kinds of constants
64 -- operands to consider:
65 -- * fit in register
66 -- * constant doesn't fit in register
67 -- * floats with integral values
68 local operand = {3, 100, 5.0, -10, -5.0, 10000, -10000}
69 local operator = {"+", "-", "*", "/", "//", "%", "^",
70 "&", "|", "^", "<<", ">>",
71 "==", "~=", "<", ">", "<=", ">=",}
72 for _, op in ipairs(operator) do
73 local f = assert(load(string.format([[return function (x,y)
74 return x %s y
75 end]], op)))();
76 for _, o1 in ipairs(operand) do
77 for _, o2 in ipairs(operand) do
78 local gab = f(o1, o2)
79
80 _ENV.XX = o1
81 local code = string.format("return XX %s %s", op, o2)
82 local res = assert(load(code))()
83 assert(res == gab)
84
85 _ENV.XX = o2
86 code = string.format("return (%s) %s XX", o1, op)
87 res = assert(load(code))()
88 assert(res == gab)
89
90 code = string.format("return (%s) %s %s", o1, op, o2)
91 res = assert(load(code))()
92 assert(res == gab)
93 end
94 end
95 end
96 _ENV.XX = nil
97end
98
99
100-- silly loops
101repeat until 1; repeat until true;
102while false do end; while nil do end;
103
104do -- test old bug (first name could not be an `upvalue')
105 local a; local function f(x) x={a=1}; x={x=1}; x={G=1} end
106end
107
108
109do -- bug since 5.4.0
110 -- create code with a table using more than 256 constants
111 local code = {"local x = {"}
112 for i = 1, 257 do
113 code[#code + 1] = i .. ".1,"
114 end
115 code[#code + 1] = "};"
116 code = table.concat(code)
117
118 -- add "ret" to the end of that code and checks that
119 -- it produces the expected value "val"
120 local function check (ret, val)
121 local code = code .. ret
122 code = load(code)
123 assert(code() == val)
124 end
125
126 check("return (1 ~ (2 or 3))", 1 ~ 2)
127 check("return (1 | (2 or 3))", 1 | 2)
128 check("return (1 + (2 or 3))", 1 + 2)
129 check("return (1 << (2 or 3))", 1 << 2)
130end
131
132
133local function f (i)
134 if type(i) ~= 'number' then return i,'jojo'; end;
135 if i > 0 then return i, f(i-1); end;
136end
137
138x = {f(3), f(5), f(10);};
139assert(x[1] == 3 and x[2] == 5 and x[3] == 10 and x[4] == 9 and x[12] == 1);
140assert(x[nil] == nil)
141x = {f'alo', f'xixi', nil};
142assert(x[1] == 'alo' and x[2] == 'xixi' and x[3] == nil);
143x = {f'alo'..'xixi'};
144assert(x[1] == 'aloxixi')
145x = {f{}}
146assert(x[2] == 'jojo' and type(x[1]) == 'table')
147
148
149local f = function (i)
150 if i < 10 then return 'a';
151 elseif i < 20 then return 'b';
152 elseif i < 30 then return 'c';
153 end;
154end
155
156assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == nil)
157
158for i=1,1000 do break; end;
159local n=100;
160local i=3;
161local t = {};
162local a=nil
163while not a do
164 a=0; for i=1,n do for i=i,1,-1 do a=a+1; t[i]=1; end; end;
165end
166assert(a == n*(n+1)/2 and i==3);
167assert(t[1] and t[n] and not t[0] and not t[n+1])
168
169function f(b)
170 local x = 1;
171 repeat
172 local a;
173 if b==1 then local b=1; x=10; break
174 elseif b==2 then x=20; break;
175 elseif b==3 then x=30;
176 else local a,b,c,d=math.sin(1); x=x+1;
177 end
178 until x>=12;
179 return x;
180end;
181
182assert(f(1) == 10 and f(2) == 20 and f(3) == 30 and f(4)==12)
183
184
185local f = function (i)
186 if i < 10 then return 'a'
187 elseif i < 20 then return 'b'
188 elseif i < 30 then return 'c'
189 else return 8
190 end
191end
192
193assert(f(3) == 'a' and f(12) == 'b' and f(26) == 'c' and f(100) == 8)
194
195local a, b = nil, 23
196x = {f(100)*2+3 or a, a or b+2}
197assert(x[1] == 19 and x[2] == 25)
198x = {f=2+3 or a, a = b+2}
199assert(x.f == 5 and x.a == 25)
200
201a={y=1}
202x = {a.y}
203assert(x[1] == 1)
204
205local function f (i)
206 while 1 do
207 if i>0 then i=i-1;
208 else return; end;
209 end;
210end;
211
212local function g(i)
213 while 1 do
214 if i>0 then i=i-1
215 else return end
216 end
217end
218
219f(10); g(10);
220
221do
222 function f () return 1,2,3; end
223 local a, b, c = f();
224 assert(a==1 and b==2 and c==3)
225 a, b, c = (f());
226 assert(a==1 and b==nil and c==nil)
227end
228
229local a,b = 3 and f();
230assert(a==1 and b==nil)
231
232function g() f(); return; end;
233assert(g() == nil)
234function g() return nil or f() end
235a,b = g()
236assert(a==1 and b==nil)
237
238print'+';
239
240do -- testing constants
241 local prog <const> = [[local x <XXX> = 10]]
242 checkload(prog, "unknown attribute 'XXX'")
243
244 checkload([[local xxx <const> = 20; xxx = 10]],
245 ":1: attempt to assign to const variable 'xxx'")
246
247 checkload([[
248 local xx;
249 local xxx <const> = 20;
250 local yyy;
251 local function foo ()
252 local abc = xx + yyy + xxx;
253 return function () return function () xxx = yyy end end
254 end
255 ]], ":6: attempt to assign to const variable 'xxx'")
256
257 checkload([[
258 local x <close> = nil
259 x = io.open()
260 ]], ":2: attempt to assign to const variable 'x'")
261end
262
263f = [[
264return function ( a , b , c , d , e )
265 local x = a >= b or c or ( d and e ) or nil
266 return x
267end , { a = 1 , b = 2 >= 1 , } or { 1 };
268]]
269f = string.gsub(f, "%s+", "\n"); -- force a SETLINE between opcodes
270f,a = load(f)();
271assert(a.a == 1 and a.b)
272
273function g (a,b,c,d,e)
274 if not (a>=b or c or d and e or nil) then return 0; else return 1; end;
275end
276
277local function h (a,b,c,d,e)
278 while (a>=b or c or (d and e) or nil) do return 1; end;
279 return 0;
280end;
281
282assert(f(2,1) == true and g(2,1) == 1 and h(2,1) == 1)
283assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1)
284assert(f(1,2,'a')
285~= -- force SETLINE before nil
286nil, "")
287assert(f(1,2,'a') == 'a' and g(1,2,'a') == 1 and h(1,2,'a') == 1)
288assert(f(1,2,nil,1,'x') == 'x' and g(1,2,nil,1,'x') == 1 and
289 h(1,2,nil,1,'x') == 1)
290assert(f(1,2,nil,nil,'x') == nil and g(1,2,nil,nil,'x') == 0 and
291 h(1,2,nil,nil,'x') == 0)
292assert(f(1,2,nil,1,nil) == nil and g(1,2,nil,1,nil) == 0 and
293 h(1,2,nil,1,nil) == 0)
294
295assert(1 and 2<3 == true and 2<3 and 'a'<'b' == true)
296x = 2<3 and not 3; assert(x==false)
297x = 2<1 or (2>1 and 'a'); assert(x=='a')
298
299
300do
301 local a; if nil then a=1; else a=2; end; -- this nil comes as PUSHNIL 2
302 assert(a==2)
303end
304
305local function F (a)
306 assert(debug.getinfo(1, "n").name == 'F')
307 return a,2,3
308end
309
310a,b = F(1)~=nil; assert(a == true and b == nil);
311a,b = F(nil)==nil; assert(a == true and b == nil)
312
313----------------------------------------------------------------
314------------------------------------------------------------------
315
316-- sometimes will be 0, sometimes will not...
317_ENV.GLOB1 = math.random(0, 1)
318
319-- basic expressions with their respective values
320local basiccases = {
321 {"nil", nil},
322 {"false", false},
323 {"true", true},
324 {"10", 10},
325 {"(0==_ENV.GLOB1)", 0 == _ENV.GLOB1},
326}
327
328local prog
329
330if _ENV.GLOB1 == 0 then
331 basiccases[2][1] = "F" -- constant false
332
333 prog = [[
334 local F <const> = false
335 if %s then IX = true end
336 return %s
337]]
338else
339 basiccases[4][1] = "k10" -- constant 10
340
341 prog = [[
342 local k10 <const> = 10
343 if %s then IX = true end
344 return %s
345 ]]
346end
347
348print('testing short-circuit optimizations (' .. _ENV.GLOB1 .. ')')
349
350
351-- operators with their respective values
352local binops <const> = {
353 {" and ", function (a,b) if not a then return a else return b end end},
354 {" or ", function (a,b) if a then return a else return b end end},
355}
356
357local cases <const> = {}
358
359-- creates all combinations of '(cases[i] op cases[n-i])' plus
360-- 'not(cases[i] op cases[n-i])' (syntax + value)
361local function createcases (n)
362 local res = {}
363 for i = 1, n - 1 do
364 for _, v1 in ipairs(cases[i]) do
365 for _, v2 in ipairs(cases[n - i]) do
366 for _, op in ipairs(binops) do
367 local t = {
368 "(" .. v1[1] .. op[1] .. v2[1] .. ")",
369 op[2](v1[2], v2[2])
370 }
371 res[#res + 1] = t
372 res[#res + 1] = {"not" .. t[1], not t[2]}
373 end
374 end
375 end
376 end
377 return res
378end
379
380-- do not do too many combinations for soft tests
381local level = _soft and 3 or 4
382
383cases[1] = basiccases
384for i = 2, level do cases[i] = createcases(i) end
385print("+")
386
387local i = 0
388for n = 1, level do
389 for _, v in pairs(cases[n]) do
390 local s = v[1]
391 local p = load(string.format(prog, s, s), "")
392 IX = false
393 assert(p() == v[2] and IX == not not v[2])
394 i = i + 1
395 if i % 60000 == 0 then print('+') end
396 end
397end
398IX = nil
399_G.GLOB1 = nil
400------------------------------------------------------------------
401
402-- testing some syntax errors (chosen through 'gcov')
403checkload("for x do", "expected")
404checkload("x:call", "expected")
405
406print'OK'
diff --git a/zig-lua/lua-5.4.7/testes/coroutine.lua b/zig-lua/lua-5.4.7/testes/coroutine.lua
new file mode 100644
index 0000000..e566c86
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/coroutine.lua
@@ -0,0 +1,1156 @@
1-- $Id: testes/coroutine.lua $
2-- See Copyright Notice in file all.lua
3
4print "testing coroutines"
5
6local debug = require'debug'
7
8local f
9
10local main, ismain = coroutine.running()
11assert(type(main) == "thread" and ismain)
12assert(not coroutine.resume(main))
13assert(not coroutine.isyieldable(main) and not coroutine.isyieldable())
14assert(not pcall(coroutine.yield))
15
16
17-- trivial errors
18assert(not pcall(coroutine.resume, 0))
19assert(not pcall(coroutine.status, 0))
20
21
22-- tests for multiple yield/resume arguments
23
24local 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
30end
31
32_G.x = nil -- declare x
33_G.f = nil -- declare f
34local function foo (a, ...)
35 local x, y = coroutine.running()
36 assert(x == f and y == false)
37 -- next call should not corrupt coroutine (but must fail,
38 -- as it attempts to resume the running coroutine)
39 assert(coroutine.resume(f) == false)
40 assert(coroutine.status(f) == "running")
41 local arg = {...}
42 assert(coroutine.isyieldable(x))
43 for i=1,#arg do
44 _G.x = {coroutine.yield(table.unpack(arg[i]))}
45 end
46 return table.unpack(a)
47end
48
49f = coroutine.create(foo)
50assert(coroutine.isyieldable(f))
51assert(type(f) == "thread" and coroutine.status(f) == "suspended")
52assert(string.find(tostring(f), "thread"))
53local s,a,b,c,d
54s,a,b,c,d = coroutine.resume(f, {1,2,3}, {}, {1}, {'a', 'b', 'c'})
55assert(coroutine.isyieldable(f))
56assert(s and a == nil and coroutine.status(f) == "suspended")
57s,a,b,c,d = coroutine.resume(f)
58eqtab(_G.x, {})
59assert(s and a == 1 and b == nil)
60assert(coroutine.isyieldable(f))
61s,a,b,c,d = coroutine.resume(f, 1, 2, 3)
62eqtab(_G.x, {1, 2, 3})
63assert(s and a == 'a' and b == 'b' and c == 'c' and d == nil)
64s,a,b,c,d = coroutine.resume(f, "xuxu")
65eqtab(_G.x, {"xuxu"})
66assert(s and a == 1 and b == 2 and c == 3 and d == nil)
67assert(coroutine.status(f) == "dead")
68s, a = coroutine.resume(f, "xuxu")
69assert(not s and string.find(a, "dead") and coroutine.status(f) == "dead")
70
71_G.f = nil
72
73-- yields in tail calls
74local function foo (i) return coroutine.yield(i) end
75local f = coroutine.wrap(function ()
76 for i=1,10 do
77 assert(foo(i) == _G.x)
78 end
79 return 'a'
80end)
81for i=1,10 do _G.x = i; assert(f(i) == i) end
82_G.x = 'xuxu'; assert(f('xuxu') == 'a')
83
84_G.x = nil
85
86-- recursive
87local function pf (n, i)
88 coroutine.yield(n)
89 pf(n*i, i+1)
90end
91
92f = coroutine.wrap(pf)
93local s=1
94for i=1,10 do
95 assert(f(1, 1) == s)
96 s = s*i
97end
98
99-- sieve
100local function gen (n)
101 return coroutine.wrap(function ()
102 for i=2,n do coroutine.yield(i) end
103 end)
104end
105
106
107local function filter (p, g)
108 return coroutine.wrap(function ()
109 while 1 do
110 local n = g()
111 if n == nil then return end
112 if math.fmod(n, p) ~= 0 then coroutine.yield(n) end
113 end
114 end)
115end
116
117local x = gen(80)
118local a = {}
119while 1 do
120 local n = x()
121 if n == nil then break end
122 table.insert(a, n)
123 x = filter(n, x)
124end
125
126assert(#a == 22 and a[#a] == 79)
127x, a = nil
128
129
130print("to-be-closed variables in coroutines")
131
132local function func2close (f)
133 return setmetatable({}, {__close = f})
134end
135
136do
137 -- ok to close a dead coroutine
138 local co = coroutine.create(print)
139 assert(coroutine.resume(co, "testing 'coroutine.close'"))
140 assert(coroutine.status(co) == "dead")
141 local st, msg = coroutine.close(co)
142 assert(st and msg == nil)
143 -- also ok to close it again
144 st, msg = coroutine.close(co)
145 assert(st and msg == nil)
146
147
148 -- cannot close the running coroutine
149 local st, msg = pcall(coroutine.close, coroutine.running())
150 assert(not st and string.find(msg, "running"))
151
152 local main = coroutine.running()
153
154 -- cannot close a "normal" coroutine
155 ;(coroutine.wrap(function ()
156 local st, msg = pcall(coroutine.close, main)
157 assert(not st and string.find(msg, "normal"))
158 end))()
159
160 -- cannot close a coroutine while closing it
161 do
162 local co
163 co = coroutine.create(
164 function()
165 local x <close> = func2close(function()
166 coroutine.close(co) -- try to close it again
167 end)
168 coroutine.yield(20)
169 end)
170 local st, msg = coroutine.resume(co)
171 assert(st and msg == 20)
172 st, msg = coroutine.close(co)
173 assert(not st and string.find(msg, "running coroutine"))
174 end
175
176 -- to-be-closed variables in coroutines
177 local X
178
179 -- closing a coroutine after an error
180 local co = coroutine.create(error)
181 local st, msg = coroutine.resume(co, 100)
182 assert(not st and msg == 100)
183 st, msg = coroutine.close(co)
184 assert(not st and msg == 100)
185 -- after closing, no more errors
186 st, msg = coroutine.close(co)
187 assert(st and msg == nil)
188
189 co = coroutine.create(function ()
190 local x <close> = func2close(function (self, err)
191 assert(err == nil); X = false
192 end)
193 X = true
194 coroutine.yield()
195 end)
196 coroutine.resume(co)
197 assert(X)
198 assert(coroutine.close(co))
199 assert(not X and coroutine.status(co) == "dead")
200
201 -- error closing a coroutine
202 local x = 0
203 co = coroutine.create(function()
204 local y <close> = func2close(function (self,err)
205 assert(err == 111)
206 x = 200
207 error(200)
208 end)
209 local x <close> = func2close(function (self, err)
210 assert(err == nil); error(111)
211 end)
212 coroutine.yield()
213 end)
214 coroutine.resume(co)
215 assert(x == 0)
216 local st, msg = coroutine.close(co)
217 assert(st == false and coroutine.status(co) == "dead" and msg == 200)
218 assert(x == 200)
219 -- after closing, no more errors
220 st, msg = coroutine.close(co)
221 assert(st and msg == nil)
222end
223
224do
225 -- <close> versus pcall in coroutines
226 local X = false
227 local Y = false
228 local function foo ()
229 local x <close> = func2close(function (self, err)
230 Y = debug.getinfo(2)
231 X = err
232 end)
233 error(43)
234 end
235 local co = coroutine.create(function () return pcall(foo) end)
236 local st1, st2, err = coroutine.resume(co)
237 assert(st1 and not st2 and err == 43)
238 assert(X == 43 and Y.what == "C")
239
240 -- recovering from errors in __close metamethods
241 local track = {}
242
243 local function h (o)
244 local hv <close> = o
245 return 1
246 end
247
248 local function foo ()
249 local x <close> = func2close(function(_,msg)
250 track[#track + 1] = msg or false
251 error(20)
252 end)
253 local y <close> = func2close(function(_,msg)
254 track[#track + 1] = msg or false
255 return 1000
256 end)
257 local z <close> = func2close(function(_,msg)
258 track[#track + 1] = msg or false
259 error(10)
260 end)
261 coroutine.yield(1)
262 h(func2close(function(_,msg)
263 track[#track + 1] = msg or false
264 error(2)
265 end))
266 end
267
268 local co = coroutine.create(pcall)
269
270 local st, res = coroutine.resume(co, foo) -- call 'foo' protected
271 assert(st and res == 1) -- yield 1
272 local st, res1, res2 = coroutine.resume(co) -- continue
273 assert(coroutine.status(co) == "dead")
274 assert(st and not res1 and res2 == 20) -- last error (20)
275 assert(track[1] == false and track[2] == 2 and track[3] == 10 and
276 track[4] == 10)
277end
278
279
280-- yielding across C boundaries
281
282local co = coroutine.wrap(function()
283 assert(not pcall(table.sort,{1,2,3}, coroutine.yield))
284 assert(coroutine.isyieldable())
285 coroutine.yield(20)
286 return 30
287 end)
288
289assert(co() == 20)
290assert(co() == 30)
291
292
293local f = function (s, i) return coroutine.yield(i) end
294
295local f1 = coroutine.wrap(function ()
296 return xpcall(pcall, function (...) return ... end,
297 function ()
298 local s = 0
299 for i in f, nil, 1 do pcall(function () s = s + i end) end
300 error({s})
301 end)
302 end)
303
304f1()
305for i = 1, 10 do assert(f1(i) == i) end
306local r1, r2, v = f1(nil)
307assert(r1 and not r2 and v[1] == (10 + 1)*10/2)
308
309
310local function f (a, b) a = coroutine.yield(a); error{a + b} end
311local function g(x) return x[1]*2 end
312
313co = coroutine.wrap(function ()
314 coroutine.yield(xpcall(f, g, 10, 20))
315 end)
316
317assert(co() == 10)
318local r, msg = co(100)
319assert(not r and msg == 240)
320
321
322-- unyieldable C call
323do
324 local function f (c)
325 assert(not coroutine.isyieldable())
326 return c .. c
327 end
328
329 local co = coroutine.wrap(function (c)
330 assert(coroutine.isyieldable())
331 local s = string.gsub("a", ".", f)
332 return s
333 end)
334 assert(co() == "aa")
335end
336
337
338
339do -- testing single trace of coroutines
340 local X
341 local co = coroutine.create(function ()
342 coroutine.yield(10)
343 return 20;
344 end)
345 local trace = {}
346 local function dotrace (event)
347 trace[#trace + 1] = event
348 end
349 debug.sethook(co, dotrace, "clr")
350 repeat until not coroutine.resume(co)
351 local correcttrace = {"call", "line", "call", "return", "line", "return"}
352 assert(#trace == #correcttrace)
353 for k, v in pairs(trace) do
354 assert(v == correcttrace[k])
355 end
356end
357
358-- errors in coroutines
359function foo ()
360 assert(debug.getinfo(1).currentline == debug.getinfo(foo).linedefined + 1)
361 assert(debug.getinfo(2).currentline == debug.getinfo(goo).linedefined)
362 coroutine.yield(3)
363 error(foo)
364end
365
366function goo() foo() end
367x = coroutine.wrap(goo)
368assert(x() == 3)
369local a,b = pcall(x)
370assert(not a and b == foo)
371
372x = coroutine.create(goo)
373a,b = coroutine.resume(x)
374assert(a and b == 3)
375a,b = coroutine.resume(x)
376assert(not a and b == foo and coroutine.status(x) == "dead")
377a,b = coroutine.resume(x)
378assert(not a and string.find(b, "dead") and coroutine.status(x) == "dead")
379
380goo = nil
381
382-- co-routines x for loop
383local function all (a, n, k)
384 if k == 0 then coroutine.yield(a)
385 else
386 for i=1,n do
387 a[k] = i
388 all(a, n, k-1)
389 end
390 end
391end
392
393local a = 0
394for t in coroutine.wrap(function () all({}, 5, 4) end) do
395 a = a+1
396end
397assert(a == 5^4)
398
399
400-- access to locals of collected corroutines
401local C = {}; setmetatable(C, {__mode = "kv"})
402local x = coroutine.wrap (function ()
403 local a = 10
404 local function f () a = a+10; return a end
405 while true do
406 a = a+1
407 coroutine.yield(f)
408 end
409 end)
410
411C[1] = x;
412
413local f = x()
414assert(f() == 21 and x()() == 32 and x() == f)
415x = nil
416collectgarbage()
417assert(C[1] == undef)
418assert(f() == 43 and f() == 53)
419
420
421-- old bug: attempt to resume itself
422
423local function co_func (current_co)
424 assert(coroutine.running() == current_co)
425 assert(coroutine.resume(current_co) == false)
426 coroutine.yield(10, 20)
427 assert(coroutine.resume(current_co) == false)
428 coroutine.yield(23)
429 return 10
430end
431
432local co = coroutine.create(co_func)
433local a,b,c = coroutine.resume(co, co)
434assert(a == true and b == 10 and c == 20)
435a,b = coroutine.resume(co, co)
436assert(a == true and b == 23)
437a,b = coroutine.resume(co, co)
438assert(a == true and b == 10)
439assert(coroutine.resume(co, co) == false)
440assert(coroutine.resume(co, co) == false)
441
442
443-- other old bug when attempting to resume itself
444-- (trigger C-code assertions)
445do
446 local A = coroutine.running()
447 local B = coroutine.create(function() return coroutine.resume(A) end)
448 local st, res = coroutine.resume(B)
449 assert(st == true and res == false)
450
451 local X = false
452 A = coroutine.wrap(function()
453 local _ <close> = func2close(function () X = true end)
454 return pcall(A, 1)
455 end)
456 st, res = A()
457 assert(not st and string.find(res, "non%-suspended") and X == true)
458end
459
460
461-- bug in 5.4.1
462do
463 -- coroutine ran close metamethods with invalid status during a
464 -- reset.
465 local co
466 co = coroutine.wrap(function()
467 local x <close> = func2close(function() return pcall(co) end)
468 error(111)
469 end)
470 local st, errobj = pcall(co)
471 assert(not st and errobj == 111)
472 st, errobj = pcall(co)
473 assert(not st and string.find(errobj, "dead coroutine"))
474end
475
476
477-- attempt to resume 'normal' coroutine
478local co1, co2
479co1 = coroutine.create(function () return co2() end)
480co2 = coroutine.wrap(function ()
481 assert(coroutine.status(co1) == 'normal')
482 assert(not coroutine.resume(co1))
483 coroutine.yield(3)
484 end)
485
486a,b = coroutine.resume(co1)
487assert(a and b == 3)
488assert(coroutine.status(co1) == 'dead')
489
490-- infinite recursion of coroutines
491a = function(a) coroutine.wrap(a)(a) end
492assert(not pcall(a, a))
493a = nil
494
495
496-- access to locals of erroneous coroutines
497local x = coroutine.create (function ()
498 local a = 10
499 _G.F = function () a=a+1; return a end
500 error('x')
501 end)
502
503assert(not coroutine.resume(x))
504-- overwrite previous position of local `a'
505assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1))
506assert(_G.F() == 11)
507assert(_G.F() == 12)
508_G.F = nil
509
510
511if not T then
512 (Message or print)
513 ('\n >>> testC not active: skipping coroutine API tests <<<\n')
514else
515 print "testing yields inside hooks"
516
517 local turn
518
519 local function fact (t, x)
520 assert(turn == t)
521 if x == 0 then return 1
522 else return x*fact(t, x-1)
523 end
524 end
525
526 local A, B = 0, 0
527
528 local x = coroutine.create(function ()
529 T.sethook("yield 0", "", 2)
530 A = fact("A", 6)
531 end)
532
533 local y = coroutine.create(function ()
534 T.sethook("yield 0", "", 3)
535 B = fact("B", 7)
536 end)
537
538 while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y')
539 if A==0 then turn = "A"; assert(T.resume(x)) end
540 if B==0 then turn = "B"; assert(T.resume(y)) end
541
542 -- check that traceback works correctly after yields inside hooks
543 debug.traceback(x)
544 debug.traceback(y)
545 end
546
547 assert(B // A == 7) -- fact(7) // fact(6)
548
549 do -- hooks vs. multiple values
550 local done
551 local function test (n)
552 done = false
553 return coroutine.wrap(function ()
554 local a = {}
555 for i = 1, n do a[i] = i end
556 -- 'pushint' just to perturb the stack
557 T.sethook("pushint 10; yield 0", "", 1) -- yield at each op.
558 local a1 = {table.unpack(a)} -- must keep top between ops.
559 assert(#a1 == n)
560 for i = 1, n do assert(a[i] == i) end
561 done = true
562 end)
563 end
564 -- arguments to the coroutine are just to perturb its stack
565 local co = test(0); while not done do co(30) end
566 co = test(1); while not done do co(20, 10) end
567 co = test(3); while not done do co() end
568 co = test(100); while not done do co() end
569 end
570
571 local line = debug.getinfo(1, "l").currentline + 2 -- get line number
572 local function foo ()
573 local x = 10 --<< this line is 'line'
574 x = x + 10
575 _G.XX = x
576 end
577
578 -- testing yields in line hook
579 local co = coroutine.wrap(function ()
580 T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end)
581
582 _G.XX = nil;
583 _G.X = nil; co(); assert(_G.X == line)
584 _G.X = nil; co(); assert(_G.X == line + 1)
585 _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil)
586 _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20)
587 assert(co() == 10)
588 _G.X = nil
589
590 -- testing yields in count hook
591 co = coroutine.wrap(function ()
592 T.sethook("yield 0", "", 1); foo(); return 10 end)
593
594 _G.XX = nil;
595 local c = 0
596 repeat c = c + 1; local a = co() until a == 10
597 assert(_G.XX == 20 and c >= 5)
598
599 co = coroutine.wrap(function ()
600 T.sethook("yield 0", "", 2); foo(); return 10 end)
601
602 _G.XX = nil;
603 local c = 0
604 repeat c = c + 1; local a = co() until a == 10
605 assert(_G.XX == 20 and c >= 5)
606 _G.X = nil; _G.XX = nil
607
608 do
609 -- testing debug library on a coroutine suspended inside a hook
610 -- (bug in 5.2/5.3)
611 c = coroutine.create(function (a, ...)
612 T.sethook("yield 0", "l") -- will yield on next two lines
613 local b = a
614 return ...
615 end)
616
617 assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine
618 local n,v = debug.getlocal(c, 0, 1) -- check its local
619 assert(n == "a" and v == 1 and debug.getlocal(c, 0, 2) ~= "b")
620 assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal'
621 local t = debug.getinfo(c, 0) -- test 'getinfo'
622 assert(t.currentline == t.linedefined + 2)
623 assert(not debug.getinfo(c, 1)) -- no other level
624 assert(coroutine.resume(c)) -- run next line
625 local n,v = debug.getlocal(c, 0, 2) -- check next local
626 assert(n == "b" and v == 10)
627 v = {coroutine.resume(c)} -- finish coroutine
628 assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef)
629 assert(not coroutine.resume(c))
630 end
631
632 do
633 -- testing debug library on last function in a suspended coroutine
634 -- (bug in 5.2/5.3)
635 local c = coroutine.create(function () T.testC("yield 1", 10, 20) end)
636 local a, b = coroutine.resume(c)
637 assert(a and b == 20)
638 assert(debug.getinfo(c, 0).linedefined == -1)
639 a, b = debug.getlocal(c, 0, 2)
640 assert(b == 10)
641 end
642
643
644 print "testing coroutine API"
645
646 -- reusing a thread
647 assert(T.testC([[
648 newthread # create thread
649 pushvalue 2 # push body
650 pushstring 'a a a' # push argument
651 xmove 0 3 2 # move values to new thread
652 resume -1, 1 # call it first time
653 pushstatus
654 xmove 3 0 0 # move results back to stack
655 setglobal X # result
656 setglobal Y # status
657 pushvalue 2 # push body (to call it again)
658 pushstring 'b b b'
659 xmove 0 3 2
660 resume -1, 1 # call it again
661 pushstatus
662 xmove 3 0 0
663 return 1 # return result
664 ]], function (...) return ... end) == 'b b b')
665
666 assert(X == 'a a a' and Y == 'OK')
667
668 X, Y = nil
669
670
671 -- resuming running coroutine
672 C = coroutine.create(function ()
673 return T.testC([[
674 pushnum 10;
675 pushnum 20;
676 resume -3 2;
677 pushstatus
678 gettop;
679 return 3]], C)
680 end)
681 local a, b, c, d = coroutine.resume(C)
682 assert(a == true and string.find(b, "non%-suspended") and
683 c == "ERRRUN" and d == 4)
684
685 a, b, c, d = T.testC([[
686 rawgeti R 1 # get main thread
687 pushnum 10;
688 pushnum 20;
689 resume -3 2;
690 pushstatus
691 gettop;
692 return 4]])
693 assert(a == coroutine.running() and string.find(b, "non%-suspended") and
694 c == "ERRRUN" and d == 4)
695
696
697 -- using a main thread as a coroutine (dubious use!)
698 local state = T.newstate()
699
700 -- check that yielddable is working correctly
701 assert(T.testC(state, "newthread; isyieldable -1; remove 1; return 1"))
702
703 -- main thread is not yieldable
704 assert(not T.testC(state, "rawgeti R 1; isyieldable -1; remove 1; return 1"))
705
706 T.testC(state, "settop 0")
707
708 T.loadlib(state)
709
710 assert(T.doremote(state, [[
711 coroutine = require'coroutine';
712 X = function (x) coroutine.yield(x, 'BB'); return 'CC' end;
713 return 'ok']]))
714
715 local t = table.pack(T.testC(state, [[
716 rawgeti R 1 # get main thread
717 pushstring 'XX'
718 getglobal X # get function for body
719 pushstring AA # arg
720 resume 1 1 # 'resume' shadows previous stack!
721 gettop
722 setglobal T # top
723 setglobal B # second yielded value
724 setglobal A # fist yielded value
725 rawgeti R 1 # get main thread
726 pushnum 5 # arg (noise)
727 resume 1 1 # after coroutine ends, previous stack is back
728 pushstatus
729 return *
730 ]]))
731 assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK')
732 assert(T.doremote(state, "return T") == '2')
733 assert(T.doremote(state, "return A") == 'AA')
734 assert(T.doremote(state, "return B") == 'BB')
735
736 T.closestate(state)
737
738 print'+'
739
740end
741
742
743-- leaving a pending coroutine open
744_G.TO_SURVIVE = coroutine.wrap(function ()
745 local a = 10
746 local x = function () a = a+1 end
747 coroutine.yield()
748 end)
749
750_G.TO_SURVIVE()
751
752
753if not _soft then
754 -- bug (stack overflow)
755 local lim = 1000000 -- stack limit; assume 32-bit machine
756 local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1, lim + 5}
757 for i = 1, #t do
758 local j = t[i]
759 local co = coroutine.create(function()
760 return table.unpack({}, 1, j)
761 end)
762 local r, msg = coroutine.resume(co)
763 -- must fail for unpacking larger than stack limit
764 assert(j < lim or not r)
765 end
766end
767
768
769assert(coroutine.running() == main)
770
771print"+"
772
773
774print"testing yields inside metamethods"
775
776local function val(x)
777 if type(x) == "table" then return x.x else return x end
778end
779
780local mt = {
781 __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end,
782 __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end,
783 __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end,
784 __add = function(a,b) coroutine.yield(nil, "add");
785 return val(a) + val(b) end,
786 __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end,
787 __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end,
788 __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end,
789 __idiv = function(a,b) coroutine.yield(nil, "idiv");
790 return val(a) // val(b) end,
791 __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end,
792 __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end,
793 __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end,
794 __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end,
795 __shl = function(a,b) coroutine.yield(nil, "shl");
796 return val(a) << val(b) end,
797 __shr = function(a,b) coroutine.yield(nil, "shr");
798 return val(a) >> val(b) end,
799 __band = function(a,b)
800 coroutine.yield(nil, "band")
801 return val(a) & val(b)
802 end,
803 __bor = function(a,b) coroutine.yield(nil, "bor");
804 return val(a) | val(b) end,
805 __bxor = function(a,b) coroutine.yield(nil, "bxor");
806 return val(a) ~ val(b) end,
807
808 __concat = function(a,b)
809 coroutine.yield(nil, "concat");
810 return val(a) .. val(b)
811 end,
812 __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end,
813 __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end,
814}
815
816
817local function new (x)
818 return setmetatable({x = x, k = {}}, mt)
819end
820
821
822local a = new(10)
823local b = new(12)
824local c = new"hello"
825
826local function run (f, t)
827 local i = 1
828 local c = coroutine.wrap(f)
829 while true do
830 local res, stat = c()
831 if res then assert(t[i] == undef); return res, t end
832 assert(stat == t[i])
833 i = i + 1
834 end
835end
836
837
838assert(run(function () if (a>=b) then return '>=' else return '<' end end,
839 {"le", "sub"}) == "<")
840assert(run(function () if (a<=b) then return '<=' else return '>' end end,
841 {"le", "sub"}) == "<=")
842assert(run(function () if (a==b) then return '==' else return '~=' end end,
843 {"eq"}) == "~=")
844
845assert(run(function () return a & b + a end, {"add", "band"}) == 2)
846
847assert(run(function () return 1 + a end, {"add"}) == 11)
848assert(run(function () return a - 25 end, {"sub"}) == -15)
849assert(run(function () return 2 * a end, {"mul"}) == 20)
850assert(run(function () return a ^ 2 end, {"pow"}) == 100)
851assert(run(function () return a / 2 end, {"div"}) == 5)
852assert(run(function () return a % 6 end, {"mod"}) == 4)
853assert(run(function () return a // 3 end, {"idiv"}) == 3)
854
855assert(run(function () return a + b end, {"add"}) == 22)
856assert(run(function () return a - b end, {"sub"}) == -2)
857assert(run(function () return a * b end, {"mul"}) == 120)
858assert(run(function () return a ^ b end, {"pow"}) == 10^12)
859assert(run(function () return a / b end, {"div"}) == 10/12)
860assert(run(function () return a % b end, {"mod"}) == 10)
861assert(run(function () return a // b end, {"idiv"}) == 0)
862
863-- repeat tests with larger constants (to use 'K' opcodes)
864local a1000 = new(1000)
865
866assert(run(function () return a1000 + 1000 end, {"add"}) == 2000)
867assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000)
868assert(run(function () return 2000 * a end, {"mul"}) == 20000)
869assert(run(function () return a1000 / 1000 end, {"div"}) == 1)
870assert(run(function () return a1000 % 600 end, {"mod"}) == 400)
871assert(run(function () return a1000 // 500 end, {"idiv"}) == 2)
872
873
874
875assert(run(function () return a % b end, {"mod"}) == 10)
876
877assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12)
878assert(run(function () return a | b end, {"bor"}) == 10 | 12)
879assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12)
880assert(run(function () return a << b end, {"shl"}) == 10 << 12)
881assert(run(function () return a >> b end, {"shr"}) == 10 >> 12)
882
883assert(run(function () return 10 & b end, {"band"}) == 10 & 12)
884assert(run(function () return a | 2 end, {"bor"}) == 10 | 2)
885assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2)
886assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2)
887assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10)
888assert(run(function () return a << 2 end, {"shl"}) == 10 << 2)
889assert(run(function () return 1 << a end, {"shl"}) == 1 << 10)
890assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10)
891
892
893assert(run(function () return a..b end, {"concat"}) == "1012")
894
895assert(run(function() return a .. b .. c .. a end,
896 {"concat", "concat", "concat"}) == "1012hello10")
897
898assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end,
899 {"concat", "concat", "concat"}) == "ab10chello12x")
900
901
902do -- a few more tests for comparison operators
903 local mt1 = {
904 __le = function (a,b)
905 coroutine.yield(10)
906 return (val(a) <= val(b))
907 end,
908 __lt = function (a,b)
909 coroutine.yield(10)
910 return val(a) < val(b)
911 end,
912 }
913 local mt2 = { __lt = mt1.__lt, __le = mt1.__le }
914
915 local function run (f)
916 local co = coroutine.wrap(f)
917 local res
918 repeat
919 res = co()
920 until res ~= 10
921 return res
922 end
923
924 local function test ()
925 local a1 = setmetatable({x=1}, mt1)
926 local a2 = setmetatable({x=2}, mt2)
927 assert(a1 < a2)
928 assert(a1 <= a2)
929 assert(1 < a2)
930 assert(1 <= a2)
931 assert(2 > a1)
932 assert(2 >= a2)
933 return true
934 end
935
936 run(test)
937
938end
939
940assert(run(function ()
941 a.BB = print
942 return a.BB
943 end, {"nidx", "idx"}) == print)
944
945-- getuptable & setuptable
946do local _ENV = _ENV
947 f = function () AAA = BBB + 1; return AAA end
948end
949local g = new(10); g.k.BBB = 10;
950debug.setupvalue(f, 1, g)
951assert(run(f, {"idx", "nidx", "idx"}) == 11)
952assert(g.k.AAA == 11)
953
954print"+"
955
956print"testing yields inside 'for' iterators"
957
958local f = function (s, i)
959 if i%2 == 0 then coroutine.yield(nil, "for") end
960 if i < s then return i + 1 end
961 end
962
963assert(run(function ()
964 local s = 0
965 for i in f, 4, 0 do s = s + i end
966 return s
967 end, {"for", "for", "for"}) == 10)
968
969
970
971-- tests for coroutine API
972if T==nil then
973 (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n')
974 print "OK"; return
975end
976
977print('testing coroutine API')
978
979local function apico (...)
980 local x = {...}
981 return coroutine.wrap(function ()
982 return T.testC(table.unpack(x))
983 end)
984end
985
986local a = {apico(
987[[
988 pushstring errorcode
989 pcallk 1 0 2;
990 invalid command (should not arrive here)
991]],
992[[return *]],
993"stackmark",
994error
995)()}
996assert(#a == 4 and
997 a[3] == "stackmark" and
998 a[4] == "errorcode" and
999 _G.status == "ERRRUN" and
1000 _G.ctx == 2) -- 'ctx' to pcallk
1001
1002local co = apico(
1003 "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;",
1004 coroutine.yield,
1005 "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command",
1006 "getglobal status; getglobal ctx; return *")
1007
1008assert(co() == 10)
1009assert(co(20, 30) == 'a')
1010a = {co()}
1011assert(#a == 10 and
1012 a[2] == coroutine.yield and
1013 a[5] == 20 and a[6] == 30 and
1014 a[7] == "YIELD" and a[8] == 3 and
1015 a[9] == "YIELD" and a[10] == 4)
1016assert(not pcall(co)) -- coroutine is dead now
1017
1018
1019f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;")
1020co = coroutine.wrap(function ()
1021 assert(f() == 23); assert(f() == 23); return 10
1022end)
1023assert(co(23,16) == 5)
1024assert(co(23,16) == 5)
1025assert(co(23,16) == 10)
1026
1027
1028-- testing coroutines with C bodies
1029f = T.makeCfunc([[
1030 pushnum 102
1031 yieldk 1 U2
1032 cannot be here!
1033]],
1034[[ # continuation
1035 pushvalue U3 # accessing upvalues inside a continuation
1036 pushvalue U4
1037 return *
1038]], 23, "huu")
1039
1040x = coroutine.wrap(f)
1041assert(x() == 102)
1042eqtab({x()}, {23, "huu"})
1043
1044
1045f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]]
1046
1047a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0;
1048 pushstatus; xmove 3 0 0; resume 3 0; pushstatus;
1049 return 4; ]], f)
1050
1051assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK')
1052
1053
1054-- testing chain of suspendable C calls
1055
1056local count = 3 -- number of levels
1057
1058f = T.makeCfunc([[
1059 remove 1; # remove argument
1060 pushvalue U3; # get selection function
1061 call 0 1; # call it (result is 'f' or 'yield')
1062 pushstring hello # single argument for selected function
1063 pushupvalueindex 2; # index of continuation program
1064 callk 1 -1 .; # call selected function
1065 errorerror # should never arrive here
1066]],
1067[[
1068 # continuation program
1069 pushnum 34 # return value
1070 return * # return all results
1071]],
1072function () -- selection function
1073 count = count - 1
1074 if count == 0 then return coroutine.yield
1075 else return f
1076 end
1077end
1078)
1079
1080co = coroutine.wrap(function () return f(nil) end)
1081assert(co() == "hello") -- argument to 'yield'
1082a = {co()}
1083-- three '34's (one from each pending C call)
1084assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34)
1085
1086
1087-- testing yields with continuations
1088
1089local y
1090
1091co = coroutine.wrap(function (...) return
1092 T.testC([[ # initial function
1093 yieldk 1 2
1094 cannot be here!
1095 ]],
1096 [[ # 1st continuation
1097 yieldk 0 3
1098 cannot be here!
1099 ]],
1100 [[ # 2nd continuation
1101 yieldk 0 4
1102 cannot be here!
1103 ]],
1104 [[ # 3th continuation
1105 pushvalue 6 # function which is last arg. to 'testC' here
1106 pushnum 10; pushnum 20;
1107 pcall 2 0 0 # call should throw an error and return to next line
1108 pop 1 # remove error message
1109 pushvalue 6
1110 getglobal status; getglobal ctx
1111 pcallk 2 2 5 # call should throw an error and jump to continuation
1112 cannot be here!
1113 ]],
1114 [[ # 4th (and last) continuation
1115 return *
1116 ]],
1117 -- function called by 3th continuation
1118 function (a,b) x=a; y=b; error("errmsg") end,
1119 ...
1120)
1121end)
1122
1123local a = {co(3,4,6)}
1124assert(a[1] == 6 and a[2] == undef)
1125a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2)
1126a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3)
1127a = {co(7,8)};
1128-- original arguments
1129assert(type(a[1]) == 'string' and type(a[2]) == 'string' and
1130 type(a[3]) == 'string' and type(a[4]) == 'string' and
1131 type(a[5]) == 'string' and type(a[6]) == 'function')
1132-- arguments left from fist resume
1133assert(a[7] == 3 and a[8] == 4)
1134-- arguments to last resume
1135assert(a[9] == 7 and a[10] == 8)
1136-- error message and nothing more
1137assert(a[11]:find("errmsg") and #a == 11)
1138-- check arguments to pcallk
1139assert(x == "YIELD" and y == 4)
1140
1141assert(not pcall(co)) -- coroutine should be dead
1142
1143_G.ctx = nil
1144_G.status = nil
1145
1146
1147-- bug in nCcalls
1148local co = coroutine.wrap(function ()
1149 local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")}
1150 return pcall(assert, table.unpack(a))
1151end)
1152
1153local a = {co()}
1154assert(a[10] == "hi")
1155
1156print'OK'
diff --git a/zig-lua/lua-5.4.7/testes/cstack.lua b/zig-lua/lua-5.4.7/testes/cstack.lua
new file mode 100644
index 0000000..97afe9f
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/cstack.lua
@@ -0,0 +1,197 @@
1-- $Id: testes/cstack.lua $
2-- See Copyright Notice in file all.lua
3
4
5local tracegc = require"tracegc"
6
7print"testing stack overflow detection"
8
9-- Segmentation faults in these tests probably result from a C-stack
10-- overflow. To avoid these errors, you should set a smaller limit for
11-- the use of C stack by Lua, by changing the constant 'LUAI_MAXCCALLS'.
12-- Alternatively, you can ensure a larger stack for the program.
13
14
15local function checkerror (msg, f, ...)
16 local s, err = pcall(f, ...)
17 assert(not s and string.find(err, msg))
18end
19
20do print("testing stack overflow in message handling")
21 local count = 0
22 local function loop (x, y, z)
23 count = count + 1
24 return 1 + loop(x, y, z)
25 end
26 tracegc.stop() -- __gc should not be called with a full stack
27 local res, msg = xpcall(loop, loop)
28 tracegc.start()
29 assert(msg == "error in error handling")
30 print("final count: ", count)
31end
32
33
34-- bug since 2.5 (C-stack overflow in recursion inside pattern matching)
35do print("testing recursion inside pattern matching")
36 local function f (size)
37 local s = string.rep("a", size)
38 local p = string.rep(".?", size)
39 return string.match(s, p)
40 end
41 local m = f(80)
42 assert(#m == 80)
43 checkerror("too complex", f, 2000)
44end
45
46
47do print("testing stack-overflow in recursive 'gsub'")
48 local count = 0
49 local function foo ()
50 count = count + 1
51 string.gsub("a", ".", foo)
52 end
53 checkerror("stack overflow", foo)
54 print("final count: ", count)
55
56 print("testing stack-overflow in recursive 'gsub' with metatables")
57 local count = 0
58 local t = setmetatable({}, {__index = foo})
59 foo = function ()
60 count = count + 1
61 string.gsub("a", ".", t)
62 end
63 checkerror("stack overflow", foo)
64 print("final count: ", count)
65end
66
67
68do -- bug in 5.4.0
69 print("testing limits in coroutines inside deep calls")
70 local count = 0
71 local lim = 1000
72 local function stack (n)
73 if n > 0 then return stack(n - 1) + 1
74 else coroutine.wrap(function ()
75 count = count + 1
76 stack(lim)
77 end)()
78 end
79 end
80
81 local st, msg = xpcall(stack, function () return "ok" end, lim)
82 assert(not st and msg == "ok")
83 print("final count: ", count)
84end
85
86
87do -- bug since 5.4.0
88 local count = 0
89 print("chain of 'coroutine.close'")
90 -- create N coroutines forming a list so that each one, when closed,
91 -- closes the previous one. (With a large enough N, previous Lua
92 -- versions crash in this test.)
93 local coro = false
94 for i = 1, 1000 do
95 local previous = coro
96 coro = coroutine.create(function()
97 local cc <close> = setmetatable({}, {__close=function()
98 count = count + 1
99 if previous then
100 assert(coroutine.close(previous))
101 end
102 end})
103 coroutine.yield() -- leaves 'cc' pending to be closed
104 end)
105 assert(coroutine.resume(coro)) -- start it and run until it yields
106 end
107 local st, msg = coroutine.close(coro)
108 assert(not st and string.find(msg, "C stack overflow"))
109 print("final count: ", count)
110end
111
112
113do
114 print("nesting of resuming yielded coroutines")
115 local count = 0
116
117 local function body ()
118 coroutine.yield()
119 local f = coroutine.wrap(body)
120 f(); -- start new coroutine (will stop in previous yield)
121 count = count + 1
122 f() -- call it recursively
123 end
124
125 local f = coroutine.wrap(body)
126 f()
127 assert(not pcall(f))
128 print("final count: ", count)
129end
130
131
132do -- bug in 5.4.2
133 print("nesting coroutines running after recoverable errors")
134 local count = 0
135 local function foo()
136 count = count + 1
137 pcall(1) -- create an error
138 -- running now inside 'precover' ("protected recover")
139 coroutine.wrap(foo)() -- call another coroutine
140 end
141 checkerror("C stack overflow", foo)
142 print("final count: ", count)
143end
144
145
146if T then
147 print("testing stack recovery")
148 local N = 0 -- trace number of calls
149 local LIM = -1 -- will store N just before stack overflow
150
151 -- trace stack size; after stack overflow, it should be
152 -- the maximum allowed stack size.
153 local stack1
154 local dummy
155
156 local function err(msg)
157 assert(string.find(msg, "stack overflow"))
158 local _, stacknow = T.stacklevel()
159 assert(stacknow == stack1 + 200)
160 end
161
162 -- When LIM==-1, the 'if' is not executed, so this function only
163 -- counts and stores the stack limits up to overflow. Then, LIM
164 -- becomes N, and then the 'if' code is run when the stack is
165 -- full. Then, there is a stack overflow inside 'xpcall', after which
166 -- the stack must have been restored back to its maximum normal size.
167 local function f()
168 dummy, stack1 = T.stacklevel()
169 if N == LIM then
170 xpcall(f, err)
171 local _, stacknow = T.stacklevel()
172 assert(stacknow == stack1)
173 return
174 end
175 N = N + 1
176 f()
177 end
178
179 local topB, sizeB -- top and size Before overflow
180 local topA, sizeA -- top and size After overflow
181 topB, sizeB = T.stacklevel()
182 tracegc.stop() -- __gc should not be called with a full stack
183 xpcall(f, err)
184 tracegc.start()
185 topA, sizeA = T.stacklevel()
186 -- sizes should be comparable
187 assert(topA == topB and sizeA < sizeB * 2)
188 print(string.format("maximum stack size: %d", stack1))
189 LIM = N -- will stop recursion at maximum level
190 N = 0 -- to count again
191 tracegc.stop() -- __gc should not be called with a full stack
192 f()
193 tracegc.start()
194 print"+"
195end
196
197print'OK'
diff --git a/zig-lua/lua-5.4.7/testes/db.lua b/zig-lua/lua-5.4.7/testes/db.lua
new file mode 100644
index 0000000..49ff8e3
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/db.lua
@@ -0,0 +1,1054 @@
1-- $Id: testes/db.lua $
2-- See Copyright Notice in file all.lua
3
4-- testing debug library
5
6local debug = require "debug"
7
8local function dostring(s) return assert(load(s))() end
9
10print"testing debug library and debug information"
11
12do
13local a=1
14end
15
16assert(not debug.gethook())
17
18local testline = 19 -- line where 'test' is defined
19local 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)
29end
30
31
32do
33 assert(not pcall(debug.getinfo, print, "X")) -- invalid option
34 assert(not pcall(debug.getinfo, 0, ">")) -- invalid option
35 assert(not debug.getinfo(1000)) -- out of range level
36 assert(not debug.getinfo(-1)) -- out of range level
37 local a = debug.getinfo(print)
38 assert(a.what == "C" and a.short_src == "[C]")
39 a = debug.getinfo(print, "L")
40 assert(a.activelines == nil)
41 local b = debug.getinfo(test, "SfL")
42 assert(b.name == nil and b.what == "Lua" and b.linedefined == testline and
43 b.lastlinedefined == b.linedefined + 10 and
44 b.func == test and not string.find(b.short_src, "%["))
45 assert(b.activelines[b.linedefined + 1] and
46 b.activelines[b.lastlinedefined])
47 assert(not b.activelines[b.linedefined] and
48 not b.activelines[b.lastlinedefined + 1])
49end
50
51
52-- bug in 5.4.4-5.4.6: activelines in vararg functions
53-- without debug information
54do
55 local func = load(string.dump(load("print(10)"), true))
56 local actl = debug.getinfo(func, "L").activelines
57 assert(#actl == 0) -- no line info
58end
59
60
61-- test file and string names truncation
62local a = "function f () end"
63local function dostring (s, x) return load(s, x)() end
64dostring(a)
65assert(debug.getinfo(f).short_src == string.format('[string "%s"]', a))
66dostring(a..string.format("; %s\n=1", string.rep('p', 400)))
67assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$'))
68dostring(a..string.format("; %s=1", string.rep('p', 400)))
69assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$'))
70dostring("\n"..a)
71assert(debug.getinfo(f).short_src == '[string "..."]')
72dostring(a, "")
73assert(debug.getinfo(f).short_src == '[string ""]')
74dostring(a, "@xuxu")
75assert(debug.getinfo(f).short_src == "xuxu")
76dostring(a, "@"..string.rep('p', 1000)..'t')
77assert(string.find(debug.getinfo(f).short_src, "^%.%.%.p*t$"))
78dostring(a, "=xuxu")
79assert(debug.getinfo(f).short_src == "xuxu")
80dostring(a, string.format("=%s", string.rep('x', 500)))
81assert(string.find(debug.getinfo(f).short_src, "^x*$"))
82dostring(a, "=")
83assert(debug.getinfo(f).short_src == "")
84_G.a = nil; _G.f = nil;
85_G[string.rep("p", 400)] = nil
86
87
88repeat
89 local g = {x = function ()
90 local a = debug.getinfo(2)
91 assert(a.name == 'f' and a.namewhat == 'local')
92 a = debug.getinfo(1)
93 assert(a.name == 'x' and a.namewhat == 'field')
94 return 'xixi'
95 end}
96 local f = function () return 1+1 and (not 1 or g.x()) end
97 assert(f() == 'xixi')
98 g = debug.getinfo(f)
99 assert(g.what == "Lua" and g.func == f and g.namewhat == "" and not g.name)
100
101 function f (x, name) -- local!
102 name = name or 'f'
103 local a = debug.getinfo(1)
104 assert(a.name == name and a.namewhat == 'local')
105 return x
106 end
107
108 -- breaks in different conditions
109 if 3>4 then break end; f()
110 if 3<4 then a=1 else break end; f()
111 while 1 do local x=10; break end; f()
112 local b = 1
113 if 3>4 then return math.sin(1) end; f()
114 a = 3<4; f()
115 a = 3<4 or 1; f()
116 repeat local x=20; if 4>3 then f() else break end; f() until 1
117 g = {}
118 f(g).x = f(2) and f(10)+f(9)
119 assert(g.x == f(19))
120 function g(x) if not x then return 3 end return (x('a', 'x')) end
121 assert(g(f) == 'a')
122until 1
123
124test([[if
125math.sin(1)
126then
127 a=1
128else
129 a=2
130end
131]], {2,3,4,7})
132
133
134test([[
135local function foo()
136end
137foo()
138A = 1
139A = 2
140A = 3
141]], {2, 3, 2, 4, 5, 6})
142_G.A = nil
143
144
145test([[--
146if nil then
147 a=1
148else
149 a=2
150end
151]], {2,5,6})
152
153test([[a=1
154repeat
155 a=a+1
156until a==3
157]], {1,3,4,3,4})
158
159test([[ do
160 return
161end
162]], {2})
163
164test([[local a
165a=1
166while a<=3 do
167 a=a+1
168end
169]], {1,2,3,4,3,4,3,4,3,5})
170
171test([[while math.sin(1) do
172 if math.sin(1)
173 then break
174 end
175end
176a=1]], {1,2,3,6})
177
178test([[for i=1,3 do
179 a=i
180end
181]], {1,2,1,2,1,2,1,3})
182
183test([[for i,v in pairs{'a','b'} do
184 a=tostring(i) .. v
185end
186]], {1,2,1,2,1,3})
187
188test([[for i=1,4 do a=1 end]], {1,1,1,1})
189
190_G.a = nil
191
192
193do -- testing line info/trace with large gaps in source
194
195 local a = {1, 2, 3, 10, 124, 125, 126, 127, 128, 129, 130,
196 255, 256, 257, 500, 1000}
197 local s = [[
198 local b = {10}
199 a = b[1] X + Y b[1]
200 b = 4
201 ]]
202 for _, i in ipairs(a) do
203 local subs = {X = string.rep("\n", i)}
204 for _, j in ipairs(a) do
205 subs.Y = string.rep("\n", j)
206 local s = string.gsub(s, "[XY]", subs)
207 test(s, {1, 2 + i, 2 + i + j, 2 + i, 2 + i + j, 3 + i + j})
208 end
209 end
210end
211_G.a = nil
212
213
214do -- testing active lines
215 local function checkactivelines (f, lines)
216 local t = debug.getinfo(f, "SL")
217 for _, l in pairs(lines) do
218 l = l + t.linedefined
219 assert(t.activelines[l])
220 t.activelines[l] = undef
221 end
222 assert(next(t.activelines) == nil) -- no extra lines
223 end
224
225 checkactivelines(function (...) -- vararg function
226 -- 1st line is empty
227 -- 2nd line is empty
228 -- 3th line is empty
229 local a = 20
230 -- 5th line is empty
231 local b = 30
232 -- 7th line is empty
233 end, {4, 6, 8})
234
235 checkactivelines(function (a)
236 -- 1st line is empty
237 -- 2nd line is empty
238 local a = 20
239 local b = 30
240 -- 5th line is empty
241 end, {3, 4, 6})
242
243 checkactivelines(function (a, b, ...) end, {0})
244
245 checkactivelines(function (a, b)
246 end, {1})
247
248 for _, n in pairs{0, 1, 2, 10, 50, 100, 1000, 10000} do
249 checkactivelines(
250 load(string.format("%s return 1", string.rep("\n", n))),
251 {n + 1})
252 end
253
254end
255
256print'+'
257
258-- invalid levels in [gs]etlocal
259assert(not pcall(debug.getlocal, 20, 1))
260assert(not pcall(debug.setlocal, -1, 1, 10))
261
262
263-- parameter names
264local function foo (a,b,...) local d, e end
265local co = coroutine.create(foo)
266
267assert(debug.getlocal(foo, 1) == 'a')
268assert(debug.getlocal(foo, 2) == 'b')
269assert(not debug.getlocal(foo, 3))
270assert(debug.getlocal(co, foo, 1) == 'a')
271assert(debug.getlocal(co, foo, 2) == 'b')
272assert(not debug.getlocal(co, foo, 3))
273
274assert(not debug.getlocal(print, 1))
275
276
277local function foo () return (debug.getlocal(1, -1)) end
278assert(not foo(10))
279
280
281-- varargs
282local function foo (a, ...)
283 local t = table.pack(...)
284 for i = 1, t.n do
285 local n, v = debug.getlocal(1, -i)
286 assert(n == "(vararg)" and v == t[i])
287 end
288 assert(not debug.getlocal(1, -(t.n + 1)))
289 assert(not debug.setlocal(1, -(t.n + 1), 30))
290 if t.n > 0 then
291 (function (x)
292 assert(debug.setlocal(2, -1, x) == "(vararg)")
293 assert(debug.setlocal(2, -t.n, x) == "(vararg)")
294 end)(430)
295 assert(... == 430)
296 end
297end
298
299foo()
300foo(print)
301foo(200, 3, 4)
302local a = {}
303for i = 1, (_soft and 100 or 1000) do a[i] = i end
304foo(table.unpack(a))
305
306
307
308do -- test hook presence in debug info
309 assert(not debug.gethook())
310 local count = 0
311 local function f ()
312 assert(debug.getinfo(1).namewhat == "hook")
313 local sndline = string.match(debug.traceback(), "\n(.-)\n")
314 assert(string.find(sndline, "hook"))
315 count = count + 1
316 end
317 debug.sethook(f, "l")
318 local a = 0
319 _ENV.a = a
320 a = 1
321 debug.sethook()
322 assert(count == 4)
323end
324_ENV.a = nil
325
326
327-- hook table has weak keys
328assert(getmetatable(debug.getregistry()._HOOKKEY).__mode == 'k')
329
330
331a = {}; local L = nil
332local glob = 1
333local oldglob = glob
334debug.sethook(function (e,l)
335 collectgarbage() -- force GC during a hook
336 local f, m, c = debug.gethook()
337 assert(m == 'crl' and c == 0)
338 if e == "line" then
339 if glob ~= oldglob then
340 L = l-1 -- get the first line where "glob" has changed
341 oldglob = glob
342 end
343 elseif e == "call" then
344 local f = debug.getinfo(2, "f").func
345 a[f] = 1
346 else assert(e == "return")
347 end
348end, "crl")
349
350
351function f(a,b)
352 collectgarbage()
353 local _, x = debug.getlocal(1, 1)
354 local _, y = debug.getlocal(1, 2)
355 assert(x == a and y == b)
356 assert(debug.setlocal(2, 3, "pera") == "AA".."AA")
357 assert(debug.setlocal(2, 4, "manga") == "B")
358 x = debug.getinfo(2)
359 assert(x.func == g and x.what == "Lua" and x.name == 'g' and
360 x.nups == 2 and string.find(x.source, "^@.*db%.lua$"))
361 glob = glob+1
362 assert(debug.getinfo(1, "l").currentline == L+1)
363 assert(debug.getinfo(1, "l").currentline == L+2)
364end
365
366function foo()
367 glob = glob+1
368 assert(debug.getinfo(1, "l").currentline == L+1)
369end; foo() -- set L
370-- check line counting inside strings and empty lines
371
372local _ = 'alo\
373alo' .. [[
374
375]]
376--[[
377]]
378assert(debug.getinfo(1, "l").currentline == L+11) -- check count of lines
379
380
381function g (...)
382 local arg = {...}
383 do local a,b,c; a=math.sin(40); end
384 local feijao
385 local AAAA,B = "xuxu", "abacate"
386 f(AAAA,B)
387 assert(AAAA == "pera" and B == "manga")
388 do
389 local B = 13
390 local x,y = debug.getlocal(1,5)
391 assert(x == 'B' and y == 13)
392 end
393end
394
395g()
396
397
398assert(a[f] and a[g] and a[assert] and a[debug.getlocal] and not a[print])
399
400
401-- tests for manipulating non-registered locals (C and Lua temporaries)
402
403local n, v = debug.getlocal(0, 1)
404assert(v == 0 and n == "(C temporary)")
405local n, v = debug.getlocal(0, 2)
406assert(v == 2 and n == "(C temporary)")
407assert(not debug.getlocal(0, 3))
408assert(not debug.getlocal(0, 0))
409
410function f()
411 assert(select(2, debug.getlocal(2,3)) == 1)
412 assert(not debug.getlocal(2,4))
413 debug.setlocal(2, 3, 10)
414 return 20
415end
416
417function g(a,b) return (a+1) + f() end
418
419assert(g(0,0) == 30)
420
421_G.f, _G.g = nil
422
423debug.sethook(nil);
424assert(not debug.gethook())
425
426
427-- minimal tests for setuservalue/getuservalue
428do
429 assert(not debug.setuservalue(io.stdin, 10))
430 local a, b = debug.getuservalue(io.stdin, 10)
431 assert(a == nil and not b)
432end
433
434-- testing iteraction between multiple values x hooks
435do
436 local function f(...) return 3, ... end
437 local count = 0
438 local a = {}
439 for i = 1, 100 do a[i] = i end
440 debug.sethook(function () count = count + 1 end, "", 1)
441 local t = {table.unpack(a)}
442 assert(#t == 100)
443 t = {table.unpack(a, 1, 3)}
444 assert(#t == 3)
445 t = {f(table.unpack(a, 1, 30))}
446 assert(#t == 31)
447end
448
449
450-- testing access to function arguments
451
452local function collectlocals (level)
453 local tab = {}
454 for i = 1, math.huge do
455 local n, v = debug.getlocal(level + 1, i)
456 if not (n and string.find(n, "^[a-zA-Z0-9_]+$")) then
457 break -- consider only real variables
458 end
459 tab[n] = v
460 end
461 return tab
462end
463
464
465local X = nil
466a = {}
467function a:f (a, b, ...) local arg = {...}; local c = 13 end
468debug.sethook(function (e)
469 assert(e == "call")
470 dostring("XX = 12") -- test dostring inside hooks
471 -- testing errors inside hooks
472 assert(not pcall(load("a='joao'+1")))
473 debug.sethook(function (e, l)
474 assert(debug.getinfo(2, "l").currentline == l)
475 local f,m,c = debug.gethook()
476 assert(e == "line")
477 assert(m == 'l' and c == 0)
478 debug.sethook(nil) -- hook is called only once
479 assert(not X) -- check that
480 X = collectlocals(2)
481 end, "l")
482end, "c")
483
484a:f(1,2,3,4,5)
485assert(X.self == a and X.a == 1 and X.b == 2 and X.c == nil)
486assert(XX == 12)
487assert(not debug.gethook())
488_G.XX = nil
489
490
491-- testing access to local variables in return hook (bug in 5.2)
492do
493 local X = false
494
495 local function foo (a, b, ...)
496 do local x,y,z end
497 local c, d = 10, 20
498 return
499 end
500
501 local function aux ()
502 if debug.getinfo(2).name == "foo" then
503 X = true -- to signal that it found 'foo'
504 local tab = {a = 100, b = 200, c = 10, d = 20}
505 for n, v in pairs(collectlocals(2)) do
506 assert(tab[n] == v)
507 tab[n] = undef
508 end
509 assert(next(tab) == nil) -- 'tab' must be empty
510 end
511 end
512
513 debug.sethook(aux, "r"); foo(100, 200); debug.sethook()
514 assert(X)
515
516end
517
518
519local function eqseq (t1, t2)
520 assert(#t1 == #t2)
521 for i = 1, #t1 do
522 assert(t1[i] == t2[i])
523 end
524end
525
526
527do print("testing inspection of parameters/returned values")
528 local on = false
529 local inp, out
530
531 local function hook (event)
532 if not on then return end
533 local ar = debug.getinfo(2, "ruS")
534 local t = {}
535 for i = ar.ftransfer, ar.ftransfer + ar.ntransfer - 1 do
536 local _, v = debug.getlocal(2, i)
537 t[#t + 1] = v
538 end
539 if event == "return" then
540 out = t
541 else
542 inp = t
543 end
544 end
545
546 debug.sethook(hook, "cr")
547
548 on = true; math.sin(3); on = false
549 eqseq(inp, {3}); eqseq(out, {math.sin(3)})
550
551 on = true; select(2, 10, 20, 30, 40); on = false
552 eqseq(inp, {2, 10, 20, 30, 40}); eqseq(out, {20, 30, 40})
553
554 local function foo (a, ...) return ... end
555 local function foo1 () on = not on; return foo(20, 10, 0) end
556 foo1(); on = false
557 eqseq(inp, {20}); eqseq(out, {10, 0})
558
559 debug.sethook()
560end
561
562
563
564-- testing upvalue access
565local function getupvalues (f)
566 local t = {}
567 local i = 1
568 while true do
569 local name, value = debug.getupvalue(f, i)
570 if not name then break end
571 assert(not t[name])
572 t[name] = value
573 i = i + 1
574 end
575 return t
576end
577
578local a,b,c = 1,2,3
579local function foo1 (a) b = a; return c end
580local function foo2 (x) a = x; return c+b end
581assert(not debug.getupvalue(foo1, 3))
582assert(not debug.getupvalue(foo1, 0))
583assert(not debug.setupvalue(foo1, 3, "xuxu"))
584local t = getupvalues(foo1)
585assert(t.a == nil and t.b == 2 and t.c == 3)
586t = getupvalues(foo2)
587assert(t.a == 1 and t.b == 2 and t.c == 3)
588assert(debug.setupvalue(foo1, 1, "xuxu") == "b")
589assert(({debug.getupvalue(foo2, 3)})[2] == "xuxu")
590-- upvalues of C functions are allways "called" "" (the empty string)
591assert(debug.getupvalue(string.gmatch("x", "x"), 1) == "")
592
593
594-- testing count hooks
595local a=0
596debug.sethook(function (e) a=a+1 end, "", 1)
597a=0; for i=1,1000 do end; assert(1000 < a and a < 1012)
598debug.sethook(function (e) a=a+1 end, "", 4)
599a=0; for i=1,1000 do end; assert(250 < a and a < 255)
600local f,m,c = debug.gethook()
601assert(m == "" and c == 4)
602debug.sethook(function (e) a=a+1 end, "", 4000)
603a=0; for i=1,1000 do end; assert(a == 0)
604
605do
606 debug.sethook(print, "", 2^24 - 1) -- count upperbound
607 local f,m,c = debug.gethook()
608 assert(({debug.gethook()})[3] == 2^24 - 1)
609end
610
611debug.sethook()
612
613local g, g1
614
615-- tests for tail calls
616local function f (x)
617 if x then
618 assert(debug.getinfo(1, "S").what == "Lua")
619 assert(debug.getinfo(1, "t").istailcall == true)
620 local tail = debug.getinfo(2)
621 assert(tail.func == g1 and tail.istailcall == true)
622 assert(debug.getinfo(3, "S").what == "main")
623 print"+"
624 end
625end
626
627function g(x) return f(x) end
628
629function g1(x) g(x) end
630
631local function h (x) local f=g1; return f(x) end
632
633h(true)
634
635local b = {}
636debug.sethook(function (e) table.insert(b, e) end, "cr")
637h(false)
638debug.sethook()
639local res = {"return", -- first return (from sethook)
640 "call", "tail call", "call", "tail call",
641 "return", "return",
642 "call", -- last call (to sethook)
643}
644for i = 1, #res do assert(res[i] == table.remove(b, 1)) end
645
646b = 0
647debug.sethook(function (e)
648 if e == "tail call" then
649 b = b + 1
650 assert(debug.getinfo(2, "t").istailcall == true)
651 else
652 assert(debug.getinfo(2, "t").istailcall == false)
653 end
654 end, "c")
655h(false)
656debug.sethook()
657assert(b == 2) -- two tail calls
658
659local lim = _soft and 3000 or 30000
660local function foo (x)
661 if x==0 then
662 assert(debug.getinfo(2).what == "main")
663 local info = debug.getinfo(1)
664 assert(info.istailcall == true and info.func == foo)
665 else return foo(x-1)
666 end
667end
668
669foo(lim)
670
671
672print"+"
673
674
675-- testing local function information
676co = load[[
677 local A = function ()
678 return x
679 end
680 return
681]]
682
683local a = 0
684-- 'A' should be visible to debugger only after its complete definition
685debug.sethook(function (e, l)
686 if l == 3 then a = a + 1; assert(debug.getlocal(2, 1) == "(temporary)")
687 elseif l == 4 then a = a + 1; assert(debug.getlocal(2, 1) == "A")
688 end
689end, "l")
690co() -- run local function definition
691debug.sethook() -- turn off hook
692assert(a == 2) -- ensure all two lines where hooked
693
694-- testing traceback
695
696assert(debug.traceback(print) == print)
697assert(debug.traceback(print, 4) == print)
698assert(string.find(debug.traceback("hi", 4), "^hi\n"))
699assert(string.find(debug.traceback("hi"), "^hi\n"))
700assert(not string.find(debug.traceback("hi"), "'debug.traceback'"))
701assert(string.find(debug.traceback("hi", 0), "'debug.traceback'"))
702assert(string.find(debug.traceback(), "^stack traceback:\n"))
703
704do -- C-function names in traceback
705 local st, msg = (function () return pcall end)()(debug.traceback)
706 assert(st == true and string.find(msg, "pcall"))
707end
708
709
710-- testing nparams, nups e isvararg
711local t = debug.getinfo(print, "u")
712assert(t.isvararg == true and t.nparams == 0 and t.nups == 0)
713
714t = debug.getinfo(function (a,b,c) end, "u")
715assert(t.isvararg == false and t.nparams == 3 and t.nups == 0)
716
717t = debug.getinfo(function (a,b,...) return t[a] end, "u")
718assert(t.isvararg == true and t.nparams == 2 and t.nups == 1)
719
720t = debug.getinfo(1) -- main
721assert(t.isvararg == true and t.nparams == 0 and t.nups == 1 and
722 debug.getupvalue(t.func, 1) == "_ENV")
723
724t = debug.getinfo(math.sin) -- C function
725assert(t.isvararg == true and t.nparams == 0 and t.nups == 0)
726
727t = debug.getinfo(string.gmatch("abc", "a")) -- C closure
728assert(t.isvararg == true and t.nparams == 0 and t.nups > 0)
729
730
731
732-- testing debugging of coroutines
733
734local function checktraceback (co, p, level)
735 local tb = debug.traceback(co, nil, level)
736 local i = 0
737 for l in string.gmatch(tb, "[^\n]+\n?") do
738 assert(i == 0 or string.find(l, p[i]))
739 i = i+1
740 end
741 assert(p[i] == undef)
742end
743
744
745local function f (n)
746 if n > 0 then f(n-1)
747 else coroutine.yield() end
748end
749
750local co = coroutine.create(f)
751coroutine.resume(co, 3)
752checktraceback(co, {"yield", "db.lua", "db.lua", "db.lua", "db.lua"})
753checktraceback(co, {"db.lua", "db.lua", "db.lua", "db.lua"}, 1)
754checktraceback(co, {"db.lua", "db.lua", "db.lua"}, 2)
755checktraceback(co, {"db.lua"}, 4)
756checktraceback(co, {}, 40)
757
758
759co = coroutine.create(function (x)
760 local a = 1
761 coroutine.yield(debug.getinfo(1, "l"))
762 coroutine.yield(debug.getinfo(1, "l").currentline)
763 return a
764 end)
765
766local tr = {}
767local foo = function (e, l) if l then table.insert(tr, l) end end
768debug.sethook(co, foo, "lcr")
769
770local _, l = coroutine.resume(co, 10)
771local x = debug.getinfo(co, 1, "lfLS")
772assert(x.currentline == l.currentline and x.activelines[x.currentline])
773assert(type(x.func) == "function")
774for i=x.linedefined + 1, x.lastlinedefined do
775 assert(x.activelines[i])
776 x.activelines[i] = undef
777end
778assert(next(x.activelines) == nil) -- no 'extra' elements
779assert(not debug.getinfo(co, 2))
780local a,b = debug.getlocal(co, 1, 1)
781assert(a == "x" and b == 10)
782a,b = debug.getlocal(co, 1, 2)
783assert(a == "a" and b == 1)
784debug.setlocal(co, 1, 2, "hi")
785assert(debug.gethook(co) == foo)
786assert(#tr == 2 and
787 tr[1] == l.currentline-1 and tr[2] == l.currentline)
788
789a,b,c = pcall(coroutine.resume, co)
790assert(a and b and c == l.currentline+1)
791checktraceback(co, {"yield", "in function <"})
792
793a,b = coroutine.resume(co)
794assert(a and b == "hi")
795assert(#tr == 4 and tr[4] == l.currentline+2)
796assert(debug.gethook(co) == foo)
797assert(not debug.gethook())
798checktraceback(co, {})
799
800
801-- check get/setlocal in coroutines
802co = coroutine.create(function (x)
803 local a, b = coroutine.yield(x)
804 assert(a == 100 and b == nil)
805 return x
806end)
807a, b = coroutine.resume(co, 10)
808assert(a and b == 10)
809a, b = debug.getlocal(co, 1, 1)
810assert(a == "x" and b == 10)
811assert(not debug.getlocal(co, 1, 5))
812assert(debug.setlocal(co, 1, 1, 30) == "x")
813assert(not debug.setlocal(co, 1, 5, 40))
814a, b = coroutine.resume(co, 100)
815assert(a and b == 30)
816
817
818-- check traceback of suspended (or dead with error) coroutines
819
820function f(i)
821 if i == 0 then error(i)
822 else coroutine.yield(); f(i-1)
823 end
824end
825
826
827co = coroutine.create(function (x) f(x) end)
828a, b = coroutine.resume(co, 3)
829t = {"'coroutine.yield'", "'f'", "in function <"}
830while coroutine.status(co) == "suspended" do
831 checktraceback(co, t)
832 a, b = coroutine.resume(co)
833 table.insert(t, 2, "'f'") -- one more recursive call to 'f'
834end
835t[1] = "'error'"
836checktraceback(co, t)
837
838
839-- test acessing line numbers of a coroutine from a resume inside
840-- a C function (this is a known bug in Lua 5.0)
841
842local function g(x)
843 coroutine.yield(x)
844end
845
846local function f (i)
847 debug.sethook(function () end, "l")
848 for j=1,1000 do
849 g(i+j)
850 end
851end
852
853local co = coroutine.wrap(f)
854co(10)
855pcall(co)
856pcall(co)
857
858
859assert(type(debug.getregistry()) == "table")
860
861
862-- test tagmethod information
863local a = {}
864local function f (t)
865 local info = debug.getinfo(1);
866 assert(info.namewhat == "metamethod")
867 a.op = info.name
868 return info.name
869end
870setmetatable(a, {
871 __index = f; __add = f; __div = f; __mod = f; __concat = f; __pow = f;
872 __mul = f; __idiv = f; __unm = f; __len = f; __sub = f;
873 __shl = f; __shr = f; __bor = f; __bxor = f;
874 __eq = f; __le = f; __lt = f; __unm = f; __len = f; __band = f;
875 __bnot = f;
876})
877
878local b = setmetatable({}, getmetatable(a))
879
880assert(a[3] == "index" and a^3 == "pow" and a..a == "concat")
881assert(a/3 == "div" and 3%a == "mod")
882assert(a+3 == "add" and 3-a == "sub" and a*3 == "mul" and
883 -a == "unm" and #a == "len" and a&3 == "band")
884assert(a + 30000 == "add" and a - 3.0 == "sub" and a * 3.0 == "mul" and
885 -a == "unm" and #a == "len" and a & 3 == "band")
886assert(a|3 == "bor" and 3~a == "bxor" and a<<3 == "shl" and a>>1 == "shr")
887assert (a==b and a.op == "eq")
888assert (a>=b and a.op == "le")
889assert ("x">=a and a.op == "le")
890assert (a>b and a.op == "lt")
891assert (a>10 and a.op == "lt")
892assert(~a == "bnot")
893
894do -- testing for-iterator name
895 local function f()
896 assert(debug.getinfo(1).name == "for iterator")
897 end
898
899 for i in f do end
900end
901
902
903do -- testing debug info for finalizers
904 local name = nil
905
906 -- create a piece of garbage with a finalizer
907 setmetatable({}, {__gc = function ()
908 local t = debug.getinfo(1) -- get function information
909 assert(t.namewhat == "metamethod")
910 name = t.name
911 end})
912
913 -- repeat until previous finalizer runs (setting 'name')
914 repeat local a = {} until name
915 assert(name == "__gc")
916end
917
918
919do
920 print("testing traceback sizes")
921
922 local function countlines (s)
923 return select(2, string.gsub(s, "\n", ""))
924 end
925
926 local function deep (lvl, n)
927 if lvl == 0 then
928 return (debug.traceback("message", n))
929 else
930 return (deep(lvl-1, n))
931 end
932 end
933
934 local function checkdeep (total, start)
935 local s = deep(total, start)
936 local rest = string.match(s, "^message\nstack traceback:\n(.*)$")
937 local cl = countlines(rest)
938 -- at most 10 lines in first part, 11 in second, plus '...'
939 assert(cl <= 10 + 11 + 1)
940 local brk = string.find(rest, "%.%.%.\t%(skip")
941 if brk then -- does message have '...'?
942 local rest1 = string.sub(rest, 1, brk)
943 local rest2 = string.sub(rest, brk, #rest)
944 assert(countlines(rest1) == 10 and countlines(rest2) == 11)
945 else
946 assert(cl == total - start + 2)
947 end
948 end
949
950 for d = 1, 51, 10 do
951 for l = 1, d do
952 -- use coroutines to ensure complete control of the stack
953 coroutine.wrap(checkdeep)(d, l)
954 end
955 end
956
957end
958
959
960print("testing debug functions on chunk without debug info")
961local prog = [[-- program to be loaded without debug information (strip)
962local debug = require'debug'
963local a = 12 -- a local variable
964
965local n, v = debug.getlocal(1, 1)
966assert(n == "(temporary)" and v == debug) -- unkown name but known value
967n, v = debug.getlocal(1, 2)
968assert(n == "(temporary)" and v == 12) -- unkown name but known value
969
970-- a function with an upvalue
971local f = function () local x; return a end
972n, v = debug.getupvalue(f, 1)
973assert(n == "(no name)" and v == 12)
974assert(debug.setupvalue(f, 1, 13) == "(no name)")
975assert(a == 13)
976
977local t = debug.getinfo(f)
978assert(t.name == nil and t.linedefined > 0 and
979 t.lastlinedefined == t.linedefined and
980 t.short_src == "?")
981assert(debug.getinfo(1).currentline == -1)
982
983t = debug.getinfo(f, "L").activelines
984assert(next(t) == nil) -- active lines are empty
985
986-- dump/load a function without debug info
987f = load(string.dump(f))
988
989t = debug.getinfo(f)
990assert(t.name == nil and t.linedefined > 0 and
991 t.lastlinedefined == t.linedefined and
992 t.short_src == "?")
993assert(debug.getinfo(1).currentline == -1)
994
995return a
996]]
997
998
999-- load 'prog' without debug info
1000local f = assert(load(string.dump(load(prog), true)))
1001
1002assert(f() == 13)
1003
1004do -- bug in 5.4.0: line hooks in stripped code
1005 local function foo ()
1006 local a = 1
1007 local b = 2
1008 return b
1009 end
1010
1011 local s = load(string.dump(foo, true))
1012 local line = true
1013 debug.sethook(function (e, l)
1014 assert(e == "line")
1015 line = l
1016 end, "l")
1017 assert(s() == 2); debug.sethook(nil)
1018 assert(line == nil) -- hook called withoug debug info for 1st instruction
1019end
1020
1021do -- tests for 'source' in binary dumps
1022 local prog = [[
1023 return function (x)
1024 return function (y)
1025 return x + y
1026 end
1027 end
1028 ]]
1029 local name = string.rep("x", 1000)
1030 local p = assert(load(prog, name))
1031 -- load 'p' as a binary chunk with debug information
1032 local c = string.dump(p)
1033 assert(#c > 1000 and #c < 2000) -- no repetition of 'source' in dump
1034 local f = assert(load(c))
1035 local g = f()
1036 local h = g(3)
1037 assert(h(5) == 8)
1038 assert(debug.getinfo(f).source == name and -- all functions have 'source'
1039 debug.getinfo(g).source == name and
1040 debug.getinfo(h).source == name)
1041 -- again, without debug info
1042 local c = string.dump(p, true)
1043 assert(#c < 500) -- no 'source' in dump
1044 local f = assert(load(c))
1045 local g = f()
1046 local h = g(30)
1047 assert(h(50) == 80)
1048 assert(debug.getinfo(f).source == '=?' and -- no function has 'source'
1049 debug.getinfo(g).source == '=?' and
1050 debug.getinfo(h).source == '=?')
1051end
1052
1053print"OK"
1054
diff --git a/zig-lua/lua-5.4.7/testes/errors.lua b/zig-lua/lua-5.4.7/testes/errors.lua
new file mode 100644
index 0000000..80d91a9
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/errors.lua
@@ -0,0 +1,696 @@
1-- $Id: testes/errors.lua $
2-- See Copyright Notice in file all.lua
3
4print("testing errors")
5
6local debug = require"debug"
7
8-- avoid problems with 'strict' module (which may generate other error messages)
9local mt = getmetatable(_G) or {}
10local oldmm = mt.__index
11mt.__index = nil
12
13local function checkerr (msg, f, ...)
14 local st, err = pcall(f, ...)
15 assert(not st and string.find(err, msg))
16end
17
18
19local function doit (s)
20 local f, msg = load(s)
21 if not f then return msg end
22 local cond, msg = pcall(f)
23 return (not cond) and msg
24end
25
26
27local function checkmessage (prog, msg, debug)
28 local m = doit(prog)
29 if debug then print(m, msg) end
30 assert(string.find(m, msg, 1, true))
31end
32
33local function checksyntax (prog, extra, token, line)
34 local msg = doit(prog)
35 if not string.find(token, "^<%a") and not string.find(token, "^char%(")
36 then token = "'"..token.."'" end
37 token = string.gsub(token, "(%p)", "%%%1")
38 local pt = string.format([[^%%[string ".*"%%]:%d: .- near %s$]],
39 line, token)
40 assert(string.find(msg, pt))
41 assert(string.find(msg, msg, 1, true))
42end
43
44
45-- test error message with no extra info
46assert(doit("error('hi', 0)") == 'hi')
47
48-- test error message with no info
49assert(doit("error()") == nil)
50
51
52-- test common errors/errors that crashed in the past
53assert(doit("table.unpack({}, 1, n=2^30)"))
54assert(doit("a=math.sin()"))
55assert(not doit("tostring(1)") and doit("tostring()"))
56assert(doit"tonumber()")
57assert(doit"repeat until 1; a")
58assert(doit"return;;")
59assert(doit"assert(false)")
60assert(doit"assert(nil)")
61assert(doit("function a (... , ...) end"))
62assert(doit("function a (, ...) end"))
63assert(doit("local t={}; t = t[#t] + 1"))
64
65checksyntax([[
66 local a = {4
67
68]], "'}' expected (to close '{' at line 1)", "<eof>", 3)
69
70
71do -- testing errors in goto/break
72 local function checksyntax (prog, msg, line)
73 local st, err = load(prog)
74 assert(string.find(err, "line " .. line))
75 assert(string.find(err, msg, 1, true))
76 end
77
78 checksyntax([[
79 ::A:: a = 1
80 ::A::
81 ]], "label 'A' already defined", 1)
82
83 checksyntax([[
84 a = 1
85 goto A
86 do ::A:: end
87 ]], "no visible label 'A'", 2)
88
89end
90
91
92if not T then
93 (Message or print)
94 ('\n >>> testC not active: skipping tests for messages in C <<<\n')
95else
96 print "testing memory error message"
97 local a = {}
98 for i = 1, 10000 do a[i] = true end -- preallocate array
99 collectgarbage()
100 T.totalmem(T.totalmem() + 10000)
101 -- force a memory error (by a small margin)
102 local st, msg = pcall(function()
103 for i = 1, 100000 do a[i] = tostring(i) end
104 end)
105 T.totalmem(0)
106 assert(not st and msg == "not enough" .. " memory")
107
108 -- stack space for luaL_traceback (bug in 5.4.6)
109 local res = T.testC[[
110 # push 16 elements on the stack
111 pushnum 1; pushnum 1; pushnum 1; pushnum 1; pushnum 1;
112 pushnum 1; pushnum 1; pushnum 1; pushnum 1; pushnum 1;
113 pushnum 1; pushnum 1; pushnum 1; pushnum 1; pushnum 1;
114 pushnum 1;
115 # traceback should work with 4 remaining slots
116 traceback xuxu 1;
117 return 1
118 ]]
119 assert(string.find(res, "xuxu.-main chunk"))
120end
121
122
123-- tests for better error messages
124
125checkmessage("a = {} + 1", "arithmetic")
126checkmessage("a = {} | 1", "bitwise operation")
127checkmessage("a = {} < 1", "attempt to compare")
128checkmessage("a = {} <= 1", "attempt to compare")
129
130checkmessage("aaa=1; bbbb=2; aaa=math.sin(3)+bbbb(3)", "global 'bbbb'")
131checkmessage("aaa={}; do local aaa=1 end aaa:bbbb(3)", "method 'bbbb'")
132checkmessage("local a={}; a.bbbb(3)", "field 'bbbb'")
133assert(not string.find(doit"aaa={13}; local bbbb=1; aaa[bbbb](3)", "'bbbb'"))
134checkmessage("aaa={13}; local bbbb=1; aaa[bbbb](3)", "number")
135checkmessage("aaa=(1)..{}", "a table value")
136
137-- bug in 5.4.6
138checkmessage("a = {_ENV = {}}; print(a._ENV.x + 1)", "field 'x'")
139
140_G.aaa, _G.bbbb = nil
141
142-- calls
143checkmessage("local a; a(13)", "local 'a'")
144checkmessage([[
145 local a = setmetatable({}, {__add = 34})
146 a = a + 1
147]], "metamethod 'add'")
148checkmessage([[
149 local a = setmetatable({}, {__lt = {}})
150 a = a > a
151]], "metamethod 'lt'")
152
153-- tail calls
154checkmessage("local a={}; return a.bbbb(3)", "field 'bbbb'")
155checkmessage("aaa={}; do local aaa=1 end; return aaa:bbbb(3)", "method 'bbbb'")
156
157checkmessage("aaa = #print", "length of a function value")
158checkmessage("aaa = #3", "length of a number value")
159
160_G.aaa = nil
161
162checkmessage("aaa.bbb:ddd(9)", "global 'aaa'")
163checkmessage("local aaa={bbb=1}; aaa.bbb:ddd(9)", "field 'bbb'")
164checkmessage("local aaa={bbb={}}; aaa.bbb:ddd(9)", "method 'ddd'")
165checkmessage("local a,b,c; (function () a = b+1.1 end)()", "upvalue 'b'")
166assert(not doit"local aaa={bbb={ddd=next}}; aaa.bbb:ddd(nil)")
167
168-- upvalues being indexed do not go to the stack
169checkmessage("local a,b,cc; (function () a = cc[1] end)()", "upvalue 'cc'")
170checkmessage("local a,b,cc; (function () a.x = 1 end)()", "upvalue 'a'")
171
172checkmessage("local _ENV = {x={}}; a = a + 1", "global 'a'")
173
174checkmessage("BB=1; local aaa={}; x=aaa+BB", "local 'aaa'")
175checkmessage("aaa={}; x=3.3/aaa", "global 'aaa'")
176checkmessage("aaa=2; BB=nil;x=aaa*BB", "global 'BB'")
177checkmessage("aaa={}; x=-aaa", "global 'aaa'")
178
179-- short circuit
180checkmessage("aaa=1; local aaa,bbbb=2,3; aaa = math.sin(1) and bbbb(3)",
181 "local 'bbbb'")
182checkmessage("aaa=1; local aaa,bbbb=2,3; aaa = bbbb(1) or aaa(3)",
183 "local 'bbbb'")
184checkmessage("local a,b,c,f = 1,1,1; f((a and b) or c)", "local 'f'")
185checkmessage("local a,b,c = 1,1,1; ((a and b) or c)()", "call a number value")
186assert(not string.find(doit"aaa={}; x=(aaa or aaa)+(aaa and aaa)", "'aaa'"))
187assert(not string.find(doit"aaa={}; (aaa or aaa)()", "'aaa'"))
188
189checkmessage("print(print < 10)", "function with number")
190checkmessage("print(print < print)", "two function values")
191checkmessage("print('10' < 10)", "string with number")
192checkmessage("print(10 < '23')", "number with string")
193
194-- float->integer conversions
195checkmessage("local a = 2.0^100; x = a << 2", "local a")
196checkmessage("local a = 1 >> 2.0^100", "has no integer representation")
197checkmessage("local a = 10.1 << 2.0^100", "has no integer representation")
198checkmessage("local a = 2.0^100 & 1", "has no integer representation")
199checkmessage("local a = 2.0^100 & 1e100", "has no integer representation")
200checkmessage("local a = 2.0 | 1e40", "has no integer representation")
201checkmessage("local a = 2e100 ~ 1", "has no integer representation")
202checkmessage("string.sub('a', 2.0^100)", "has no integer representation")
203checkmessage("string.rep('a', 3.3)", "has no integer representation")
204checkmessage("return 6e40 & 7", "has no integer representation")
205checkmessage("return 34 << 7e30", "has no integer representation")
206checkmessage("return ~-3e40", "has no integer representation")
207checkmessage("return ~-3.009", "has no integer representation")
208checkmessage("return 3.009 & 1", "has no integer representation")
209checkmessage("return 34 >> {}", "table value")
210checkmessage("aaa = 24 // 0", "divide by zero")
211checkmessage("aaa = 1 % 0", "'n%0'")
212
213
214-- type error for an object which is neither in an upvalue nor a register.
215-- The following code will try to index the value 10 that is stored in
216-- the metatable, without moving it to a register.
217checkmessage("local a = setmetatable({}, {__index = 10}).x",
218 "attempt to index a number value")
219
220
221-- numeric for loops
222checkmessage("for i = {}, 10 do end", "table")
223checkmessage("for i = io.stdin, 10 do end", "FILE")
224checkmessage("for i = {}, 10 do end", "initial value")
225checkmessage("for i = 1, 'x', 10 do end", "string")
226checkmessage("for i = 1, {}, 10 do end", "limit")
227checkmessage("for i = 1, {} do end", "limit")
228checkmessage("for i = 1, 10, print do end", "step")
229checkmessage("for i = 1, 10, print do end", "function")
230
231-- passing light userdata instead of full userdata
232_G.D = debug
233checkmessage([[
234 -- create light udata
235 local x = D.upvalueid(function () return debug end, 1)
236 D.setuservalue(x, {})
237]], "light userdata")
238_G.D = nil
239
240do -- named objects (field '__name')
241 checkmessage("math.sin(io.input())", "(number expected, got FILE*)")
242 _G.XX = setmetatable({}, {__name = "My Type"})
243 assert(string.find(tostring(XX), "^My Type"))
244 checkmessage("io.input(XX)", "(FILE* expected, got My Type)")
245 checkmessage("return XX + 1", "on a My Type value")
246 checkmessage("return ~io.stdin", "on a FILE* value")
247 checkmessage("return XX < XX", "two My Type values")
248 checkmessage("return {} < XX", "table with My Type")
249 checkmessage("return XX < io.stdin", "My Type with FILE*")
250 _G.XX = nil
251
252 if T then -- extra tests for 'luaL_tolstring'
253 -- bug in 5.4.3; 'luaL_tolstring' with negative indices
254 local x = setmetatable({}, {__name="TABLE"})
255 assert(T.testC("Ltolstring -1; return 1", x) == tostring(x))
256
257 local a, b = T.testC("pushint 10; Ltolstring -2; return 2", x)
258 assert(a == 10 and b == tostring(x))
259
260 setmetatable(x, {__tostring=function (o)
261 assert(o == x)
262 return "ABC"
263 end})
264 local a, b, c = T.testC("pushint 10; Ltolstring -2; return 3", x)
265 assert(a == x and b == 10 and c == "ABC")
266 end
267end
268
269-- global functions
270checkmessage("(io.write or print){}", "io.write")
271checkmessage("(collectgarbage or print){}", "collectgarbage")
272
273-- errors in functions without debug info
274do
275 local f = function (a) return a + 1 end
276 f = assert(load(string.dump(f, true)))
277 assert(f(3) == 4)
278 checkerr("^%?:%-1:", f, {})
279
280 -- code with a move to a local var ('OP_MOV A B' with A<B)
281 f = function () local a; a = {}; return a + 2 end
282 -- no debug info (so that 'a' is unknown)
283 f = assert(load(string.dump(f, true)))
284 -- symbolic execution should not get lost
285 checkerr("^%?:%-1:.*table value", f)
286end
287
288
289-- tests for field accesses after RK limit
290local t = {}
291for i = 1, 1000 do
292 t[i] = "aaa = x" .. i
293end
294local s = table.concat(t, "; ")
295t = nil
296checkmessage(s.."; aaa = bbb + 1", "global 'bbb'")
297checkmessage("local _ENV=_ENV;"..s.."; aaa = bbb + 1", "global 'bbb'")
298checkmessage(s.."; local t = {}; aaa = t.bbb + 1", "field 'bbb'")
299checkmessage(s.."; local t = {}; t:bbb()", "method 'bbb'")
300
301checkmessage([[aaa=9
302repeat until 3==3
303local x=math.sin(math.cos(3))
304if math.sin(1) == x then return math.sin(1) end -- tail call
305local a,b = 1, {
306 {x='a'..'b'..'c', y='b', z=x},
307 {1,2,3,4,5} or 3+3<=3+3,
308 3+1>3+1,
309 {d = x and aaa[x or y]}}
310]], "global 'aaa'")
311
312checkmessage([[
313local x,y = {},1
314if math.sin(1) == 0 then return 3 end -- return
315x.a()]], "field 'a'")
316
317checkmessage([[
318prefix = nil
319insert = nil
320while 1 do
321 local a
322 if nil then break end
323 insert(prefix, a)
324end]], "global 'insert'")
325
326checkmessage([[ -- tail call
327 return math.sin("a")
328]], "sin")
329
330checkmessage([[collectgarbage("nooption")]], "invalid option")
331
332checkmessage([[x = print .. "a"]], "concatenate")
333checkmessage([[x = "a" .. false]], "concatenate")
334checkmessage([[x = {} .. 2]], "concatenate")
335
336checkmessage("getmetatable(io.stdin).__gc()", "no value")
337
338checkmessage([[
339local Var
340local function main()
341 NoSuchName (function() Var=0 end)
342end
343main()
344]], "global 'NoSuchName'")
345print'+'
346
347aaa = {}; setmetatable(aaa, {__index = string})
348checkmessage("aaa:sub()", "bad self")
349checkmessage("string.sub('a', {})", "#2")
350checkmessage("('a'):sub{}", "#1")
351
352checkmessage("table.sort({1,2,3}, table.sort)", "'table.sort'")
353checkmessage("string.gsub('s', 's', setmetatable)", "'setmetatable'")
354
355_G.aaa = nil
356
357
358-- tests for errors in coroutines
359
360local function f (n)
361 local c = coroutine.create(f)
362 local a,b = coroutine.resume(c)
363 return b
364end
365assert(string.find(f(), "C stack overflow"))
366
367checkmessage("coroutine.yield()", "outside a coroutine")
368
369f = coroutine.wrap(function () table.sort({1,2,3}, coroutine.yield) end)
370checkerr("yield across", f)
371
372
373-- testing size of 'source' info; size of buffer for that info is
374-- LUA_IDSIZE, declared as 60 in luaconf. Get one position for '\0'.
375local idsize = 60 - 1
376local function checksize (source)
377 -- syntax error
378 local _, msg = load("x", source)
379 msg = string.match(msg, "^([^:]*):") -- get source (1st part before ':')
380 assert(msg:len() <= idsize)
381end
382
383for i = 60 - 10, 60 + 10 do -- check border cases around 60
384 checksize("@" .. string.rep("x", i)) -- file names
385 checksize(string.rep("x", i - 10)) -- string sources
386 checksize("=" .. string.rep("x", i)) -- exact sources
387end
388
389
390-- testing line error
391
392local function lineerror (s, l)
393 local err,msg = pcall(load(s))
394 local line = tonumber(string.match(msg, ":(%d+):"))
395 assert(line == l or (not line and not l))
396end
397
398lineerror("local a\n for i=1,'a' do \n print(i) \n end", 2)
399lineerror("\n local a \n for k,v in 3 \n do \n print(k) \n end", 3)
400lineerror("\n\n for k,v in \n 3 \n do \n print(k) \n end", 4)
401lineerror("function a.x.y ()\na=a+1\nend", 1)
402
403lineerror("a = \na\n+\n{}", 3)
404lineerror("a = \n3\n+\n(\n4\n/\nprint)", 6)
405lineerror("a = \nprint\n+\n(\n4\n/\n7)", 3)
406
407lineerror("a\n=\n-\n\nprint\n;", 3)
408
409lineerror([[
410a
411( -- <<
41223)
413]], 2)
414
415lineerror([[
416local a = {x = 13}
417a
418.
419x
420( -- <<
42123
422)
423]], 5)
424
425lineerror([[
426local a = {x = 13}
427a
428.
429x
430(
43123 + a
432)
433]], 6)
434
435local p = [[
436 function g() f() end
437 function f(x) error('a', XX) end
438g()
439]]
440XX=3;lineerror((p), 3)
441XX=0;lineerror((p), false)
442XX=1;lineerror((p), 2)
443XX=2;lineerror((p), 1)
444_G.XX, _G.g, _G.f = nil
445
446
447lineerror([[
448local b = false
449if not b then
450 error 'test'
451end]], 3)
452
453lineerror([[
454local b = false
455if not b then
456 if not b then
457 if not b then
458 error 'test'
459 end
460 end
461end]], 5)
462
463
464-- bug in 5.4.0
465lineerror([[
466 local a = 0
467 local b = 1
468 local c = b % a
469]], 3)
470
471do
472 -- Force a negative estimate for base line. Error in instruction 2
473 -- (after VARARGPREP, GETGLOBAL), with first absolute line information
474 -- (forced by too many lines) in instruction 0.
475 local s = string.format("%s return __A.x", string.rep("\n", 300))
476 lineerror(s, 301)
477end
478
479
480if not _soft then
481 -- several tests that exaust the Lua stack
482 collectgarbage()
483 print"testing stack overflow"
484 local C = 0
485 -- get line where stack overflow will happen
486 local l = debug.getinfo(1, "l").currentline + 1
487 local function auxy () C=C+1; auxy() end -- produce a stack overflow
488 function YY ()
489 collectgarbage("stop") -- avoid running finalizers without stack space
490 auxy()
491 collectgarbage("restart")
492 end
493
494 local function checkstackmessage (m)
495 print("(expected stack overflow after " .. C .. " calls)")
496 C = 0 -- prepare next count
497 return (string.find(m, "stack overflow"))
498 end
499 -- repeated stack overflows (to check stack recovery)
500 assert(checkstackmessage(doit('YY()')))
501 assert(checkstackmessage(doit('YY()')))
502 assert(checkstackmessage(doit('YY()')))
503
504 _G.YY = nil
505
506
507 -- error lines in stack overflow
508 local l1
509 local function g(x)
510 l1 = debug.getinfo(x, "l").currentline + 2
511 collectgarbage("stop") -- avoid running finalizers without stack space
512 auxy()
513 collectgarbage("restart")
514 end
515 local _, stackmsg = xpcall(g, debug.traceback, 1)
516 print('+')
517 local stack = {}
518 for line in string.gmatch(stackmsg, "[^\n]*") do
519 local curr = string.match(line, ":(%d+):")
520 if curr then table.insert(stack, tonumber(curr)) end
521 end
522 local i=1
523 while stack[i] ~= l1 do
524 assert(stack[i] == l)
525 i = i+1
526 end
527 assert(i > 15)
528
529
530 -- error in error handling
531 local res, msg = xpcall(error, error)
532 assert(not res and type(msg) == 'string')
533 print('+')
534
535 local function f (x)
536 if x==0 then error('a\n')
537 else
538 local aux = function () return f(x-1) end
539 local a,b = xpcall(aux, aux)
540 return a,b
541 end
542 end
543 f(3)
544
545 local function loop (x,y,z) return 1 + loop(x, y, z) end
546
547 local res, msg = xpcall(loop, function (m)
548 assert(string.find(m, "stack overflow"))
549 checkerr("error handling", loop)
550 assert(math.sin(0) == 0)
551 return 15
552 end)
553 assert(msg == 15)
554
555 local f = function ()
556 for i = 999900, 1000000, 1 do table.unpack({}, 1, i) end
557 end
558 checkerr("too many results", f)
559
560end
561
562
563do
564 -- non string messages
565 local t = {}
566 local res, msg = pcall(function () error(t) end)
567 assert(not res and msg == t)
568
569 res, msg = pcall(function () error(nil) end)
570 assert(not res and msg == nil)
571
572 local function f() error{msg='x'} end
573 res, msg = xpcall(f, function (r) return {msg=r.msg..'y'} end)
574 assert(msg.msg == 'xy')
575
576 -- 'assert' with extra arguments
577 res, msg = pcall(assert, false, "X", t)
578 assert(not res and msg == "X")
579
580 -- 'assert' with no message
581 res, msg = pcall(function () assert(false) end)
582 local line = string.match(msg, "%w+%.lua:(%d+): assertion failed!$")
583 assert(tonumber(line) == debug.getinfo(1, "l").currentline - 2)
584
585 -- 'assert' with non-string messages
586 res, msg = pcall(assert, false, t)
587 assert(not res and msg == t)
588
589 res, msg = pcall(assert, nil, nil)
590 assert(not res and msg == nil)
591
592 -- 'assert' without arguments
593 res, msg = pcall(assert)
594 assert(not res and string.find(msg, "value expected"))
595end
596
597-- xpcall with arguments
598local a, b, c = xpcall(string.find, error, "alo", "al")
599assert(a and b == 1 and c == 2)
600a, b, c = xpcall(string.find, function (x) return {} end, true, "al")
601assert(not a and type(b) == "table" and c == nil)
602
603
604print("testing tokens in error messages")
605checksyntax("syntax error", "", "error", 1)
606checksyntax("1.000", "", "1.000", 1)
607checksyntax("[[a]]", "", "[[a]]", 1)
608checksyntax("'aa'", "", "'aa'", 1)
609checksyntax("while << do end", "", "<<", 1)
610checksyntax("for >> do end", "", ">>", 1)
611
612-- test invalid non-printable char in a chunk
613checksyntax("a\1a = 1", "", "<\\1>", 1)
614
615-- test 255 as first char in a chunk
616checksyntax("\255a = 1", "", "<\\255>", 1)
617
618doit('I = load("a=9+"); aaa=3')
619assert(_G.aaa==3 and not _G.I)
620_G.I,_G.aaa = nil
621print('+')
622
623local lim = 1000
624if _soft then lim = 100 end
625for i=1,lim do
626 doit('a = ')
627 doit('a = 4+nil')
628end
629
630
631-- testing syntax limits
632
633local function testrep (init, rep, close, repc, finalresult)
634 local s = init .. string.rep(rep, 100) .. close .. string.rep(repc, 100)
635 local res, msg = load(s)
636 assert(res) -- 100 levels is OK
637 if (finalresult) then
638 assert(res() == finalresult)
639 end
640 s = init .. string.rep(rep, 500)
641 local res, msg = load(s) -- 500 levels not ok
642 assert(not res and (string.find(msg, "too many") or
643 string.find(msg, "overflow")))
644end
645
646testrep("local a; a", ",a", "= 1", ",1") -- multiple assignment
647testrep("local a; a=", "{", "0", "}")
648testrep("return ", "(", "2", ")", 2)
649testrep("local function a (x) return x end; return ", "a(", "2.2", ")", 2.2)
650testrep("", "do ", "", " end")
651testrep("", "while a do ", "", " end")
652testrep("local a; ", "if a then else ", "", " end")
653testrep("", "function foo () ", "", " end")
654testrep("local a = ''; return ", "a..", "'a'", "", "a")
655testrep("local a = 1; return ", "a^", "a", "", 1)
656
657checkmessage("a = f(x" .. string.rep(",x", 260) .. ")", "too many registers")
658
659
660-- testing other limits
661
662-- upvalues
663local lim = 127
664local s = "local function fooA ()\n local "
665for j = 1,lim do
666 s = s.."a"..j..", "
667end
668s = s.."b,c\n"
669s = s.."local function fooB ()\n local "
670for j = 1,lim do
671 s = s.."b"..j..", "
672end
673s = s.."b\n"
674s = s.."function fooC () return b+c"
675local c = 1+2
676for j = 1,lim do
677 s = s.."+a"..j.."+b"..j
678 c = c + 2
679end
680s = s.."\nend end end"
681local a,b = load(s)
682assert(c > 255 and string.find(b, "too many upvalues") and
683 string.find(b, "line 5"))
684
685-- local variables
686s = "\nfunction foo ()\n local "
687for j = 1,300 do
688 s = s.."a"..j..", "
689end
690s = s.."b\n"
691local a,b = load(s)
692assert(string.find(b, "line 2") and string.find(b, "too many local variables"))
693
694mt.__index = oldmm
695
696print('OK')
diff --git a/zig-lua/lua-5.4.7/testes/events.lua b/zig-lua/lua-5.4.7/testes/events.lua
new file mode 100644
index 0000000..8d8563b
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/events.lua
@@ -0,0 +1,491 @@
1-- $Id: testes/events.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing metatables')
5
6local debug = require'debug'
7
8X = 20; B = 30
9
10_ENV = setmetatable({}, {__index=_G})
11
12collectgarbage()
13
14X = X+10
15assert(X == 30 and _G.X == 20)
16B = false
17assert(B == false)
18_ENV["B"] = undef
19assert(B == 30)
20
21assert(getmetatable{} == nil)
22assert(getmetatable(4) == nil)
23assert(getmetatable(nil) == nil)
24a={name = "NAME"}; setmetatable(a, {__metatable = "xuxu",
25 __tostring=function(x) return x.name end})
26assert(getmetatable(a) == "xuxu")
27assert(tostring(a) == "NAME")
28-- cannot change a protected metatable
29assert(pcall(setmetatable, a, {}) == false)
30a.name = "gororoba"
31assert(tostring(a) == "gororoba")
32
33local a, t = {10,20,30; x="10", y="20"}, {}
34assert(setmetatable(a,t) == a)
35assert(getmetatable(a) == t)
36assert(setmetatable(a,nil) == a)
37assert(getmetatable(a) == nil)
38assert(setmetatable(a,t) == a)
39
40
41function f (t, i, e)
42 assert(not e)
43 local p = rawget(t, "parent")
44 return (p and p[i]+3), "dummy return"
45end
46
47t.__index = f
48
49a.parent = {z=25, x=12, [4] = 24}
50assert(a[1] == 10 and a.z == 28 and a[4] == 27 and a.x == "10")
51
52collectgarbage()
53
54a = setmetatable({}, t)
55function f(t, i, v) rawset(t, i, v-3) end
56setmetatable(t, t) -- causes a bug in 5.1 !
57t.__newindex = f
58a[1] = 30; a.x = "101"; a[5] = 200
59assert(a[1] == 27 and a.x == 98 and a[5] == 197)
60
61do -- 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)
67end
68
69
70local c = {}
71a = setmetatable({}, t)
72t.__newindex = c
73t.__index = c
74a[1] = 10; a[2] = 20; a[3] = 90;
75for i = 4, 20 do a[i] = i * 10 end
76assert(a[1] == 10 and a[2] == 20 and a[3] == 90)
77for i = 4, 20 do assert(a[i] == i * 10) end
78assert(next(a) == nil)
79
80
81do
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
90end
91
92
93do -- 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)
105end
106
107
108setmetatable(t, nil)
109function f (t, ...) return t, {...} end
110t.__call = f
111
112do
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)
117end
118
119
120local b = setmetatable({}, t)
121setmetatable(b,t)
122
123function f(op)
124 return function (...) cap = {[0] = op, ...} ; return (...) end
125end
126t.__add = f("add")
127t.__sub = f("sub")
128t.__mul = f("mul")
129t.__div = f("div")
130t.__idiv = f("idiv")
131t.__mod = f("mod")
132t.__unm = f("unm")
133t.__pow = f("pow")
134t.__len = f("len")
135t.__band = f("band")
136t.__bor = f("bor")
137t.__bxor = f("bxor")
138t.__shl = f("shl")
139t.__shr = f("shr")
140t.__bnot = f("bnot")
141t.__lt = f("lt")
142t.__le = f("le")
143
144
145local function checkcap (t)
146 assert(#cap + 1 == #t)
147 for i = 1, #t do
148 assert(cap[i - 1] == t[i])
149 assert(math.type(cap[i - 1]) == math.type(t[i]))
150 end
151end
152
153-- Some tests are done inside small anonymous functions to ensure
154-- that constants go to constant table even in debug compilation,
155-- when the constant table is very small.
156assert(b+5 == b); checkcap{"add", b, 5}
157assert(5.2 + b == 5.2); checkcap{"add", 5.2, b}
158assert(b+'5' == b); checkcap{"add", b, '5'}
159assert(5+b == 5); checkcap{"add", 5, b}
160assert('5'+b == '5'); checkcap{"add", '5', b}
161b=b-3; assert(getmetatable(b) == t); checkcap{"sub", b, 3}
162assert(5-a == 5); checkcap{"sub", 5, a}
163assert('5'-a == '5'); checkcap{"sub", '5', a}
164assert(a*a == a); checkcap{"mul", a, a}
165assert(a/0 == a); checkcap{"div", a, 0}
166assert(a/0.0 == a); checkcap{"div", a, 0.0}
167assert(a%2 == a); checkcap{"mod", a, 2}
168assert(a // (1/0) == a); checkcap{"idiv", a, 1/0}
169;(function () assert(a & "hi" == a) end)(); checkcap{"band", a, "hi"}
170;(function () assert(10 & a == 10) end)(); checkcap{"band", 10, a}
171;(function () assert(a | 10 == a) end)(); checkcap{"bor", a, 10}
172assert(a | "hi" == a); checkcap{"bor", a, "hi"}
173assert("hi" ~ a == "hi"); checkcap{"bxor", "hi", a}
174;(function () assert(10 ~ a == 10) end)(); checkcap{"bxor", 10, a}
175assert(-a == a); checkcap{"unm", a, a}
176assert(a^4.0 == a); checkcap{"pow", a, 4.0}
177assert(a^'4' == a); checkcap{"pow", a, '4'}
178assert(4^a == 4); checkcap{"pow", 4, a}
179assert('4'^a == '4'); checkcap{"pow", '4', a}
180assert(#a == a); checkcap{"len", a, a}
181assert(~a == a); checkcap{"bnot", a, a}
182assert(a << 3 == a); checkcap{"shl", a, 3}
183assert(1.5 >> a == 1.5); checkcap{"shr", 1.5, a}
184
185-- for comparison operators, all results are true
186assert(5.0 > a); checkcap{"lt", a, 5.0}
187assert(a >= 10); checkcap{"le", 10, a}
188assert(a <= -10.0); checkcap{"le", a, -10.0}
189assert(a < -10); checkcap{"lt", a, -10}
190
191
192-- test for rawlen
193t = setmetatable({1,2,3}, {__len = function () return 10 end})
194assert(#t == 10 and rawlen(t) == 3)
195assert(rawlen"abc" == 3)
196assert(not pcall(rawlen, io.stdin))
197assert(not pcall(rawlen, 34))
198assert(not pcall(rawlen))
199
200-- rawlen for long strings
201assert(rawlen(string.rep('a', 1000)) == 1000)
202
203
204t = {}
205t.__lt = function (a,b,c)
206 collectgarbage()
207 assert(c == nil)
208 if type(a) == 'table' then a = a.x end
209 if type(b) == 'table' then b = b.x end
210 return a<b, "dummy"
211end
212
213t.__le = function (a,b,c)
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"
218end
219
220t.__eq = function (a,b,c)
221 assert(c == nil)
222 if type(a) == 'table' then a = a.x end
223 if type(b) == 'table' then b = b.x end
224 return a == b, "dummy"
225end
226
227function Op(x) return setmetatable({x=x}, t) end
228
229local function test (a, b, c)
230 assert(not(Op(1)<Op(1)) and (Op(1)<Op(2)) and not(Op(2)<Op(1)))
231 assert(not(1 < Op(1)) and (Op(1) < 2) and not(2 < Op(1)))
232 assert(not(Op('a')<Op('a')) and (Op('a')<Op('b')) and not(Op('b')<Op('a')))
233 assert(not('a' < Op('a')) and (Op('a') < 'b') and not(Op('b') < Op('a')))
234 assert((Op(1)<=Op(1)) and (Op(1)<=Op(2)) and not(Op(2)<=Op(1)))
235 assert((Op('a')<=Op('a')) and (Op('a')<=Op('b')) and not(Op('b')<=Op('a')))
236 assert(not(Op(1)>Op(1)) and not(Op(1)>Op(2)) and (Op(2)>Op(1)))
237 assert(not(Op('a')>Op('a')) and not(Op('a')>Op('b')) and (Op('b')>Op('a')))
238 assert((Op(1)>=Op(1)) and not(Op(1)>=Op(2)) and (Op(2)>=Op(1)))
239 assert((1 >= Op(1)) and not(1 >= Op(2)) and (Op(2) >= 1))
240 assert((Op('a')>=Op('a')) and not(Op('a')>=Op('b')) and (Op('b')>=Op('a')))
241 assert(('a' >= Op('a')) and not(Op('a') >= 'b') and (Op('b') >= Op('a')))
242 assert(Op(1) == Op(1) and Op(1) ~= Op(2))
243 assert(Op('a') == Op('a') and Op('a') ~= Op('b'))
244 assert(a == a and a ~= b)
245 assert(Op(3) == c)
246end
247
248test(Op(1), Op(2), Op(3))
249
250
251-- test `partial order'
252
253local function rawSet(x)
254 local y = {}
255 for _,k in pairs(x) do y[k] = 1 end
256 return y
257end
258
259local function Set(x)
260 return setmetatable(rawSet(x), t)
261end
262
263t.__lt = function (a,b)
264 for k in pairs(a) do
265 if not b[k] then return false end
266 b[k] = undef
267 end
268 return next(b) ~= nil
269end
270
271t.__le = function (a,b)
272 for k in pairs(a) do
273 if not b[k] then return false end
274 end
275 return true
276end
277
278assert(Set{1,2,3} < Set{1,2,3,4})
279assert(not(Set{1,2,3,4} < Set{1,2,3,4}))
280assert((Set{1,2,3,4} <= Set{1,2,3,4}))
281assert((Set{1,2,3,4} >= Set{1,2,3,4}))
282assert(not (Set{1,3} <= Set{3,5}))
283assert(not(Set{1,3} <= Set{3,5}))
284assert(not(Set{1,3} >= Set{3,5}))
285
286
287t.__eq = function (a,b)
288 for k in pairs(a) do
289 if not b[k] then return false end
290 b[k] = undef
291 end
292 return next(b) == nil
293end
294
295local s = Set{1,3,5}
296assert(s == Set{3,5,1})
297assert(not rawequal(s, Set{3,5,1}))
298assert(rawequal(s, s))
299assert(Set{1,3,5,1} == rawSet{3,5,1})
300assert(rawSet{1,3,5,1} == Set{3,5,1})
301assert(Set{1,3,5} ~= Set{3,5,1,6})
302
303-- '__eq' is not used for table accesses
304t[Set{1,3,5}] = 1
305assert(t[Set{1,3,5}] == undef)
306
307
308do -- test invalidating flags
309 local mt = {__eq = true}
310 local a = setmetatable({10}, mt)
311 local b = setmetatable({10}, mt)
312 mt.__eq = nil
313 assert(a ~= b) -- no metamethod
314 mt.__eq = function (x,y) return x[1] == y[1] end
315 assert(a == b) -- must use metamethod now
316end
317
318
319if not T then
320 (Message or print)('\n >>> testC not active: skipping tests for \z
321userdata <<<\n')
322else
323 local u1 = T.newuserdata(0, 1)
324 local u2 = T.newuserdata(0, 1)
325 local u3 = T.newuserdata(0, 1)
326 assert(u1 ~= u2 and u1 ~= u3)
327 debug.setuservalue(u1, 1);
328 debug.setuservalue(u2, 2);
329 debug.setuservalue(u3, 1);
330 debug.setmetatable(u1, {__eq = function (a, b)
331 return debug.getuservalue(a) == debug.getuservalue(b)
332 end})
333 debug.setmetatable(u2, {__eq = function (a, b)
334 return true
335 end})
336 assert(u1 == u3 and u3 == u1 and u1 ~= u2)
337 assert(u2 == u1 and u2 == u3 and u3 == u2)
338 assert(u2 ~= {}) -- different types cannot be equal
339 assert(rawequal(u1, u1) and not rawequal(u1, u3))
340
341 local mirror = {}
342 debug.setmetatable(u3, {__index = mirror, __newindex = mirror})
343 for i = 1, 10 do u3[i] = i end
344 for i = 1, 10 do assert(u3[i] == i) end
345end
346
347
348t.__concat = function (a,b,c)
349 assert(c == nil)
350 if type(a) == 'table' then a = a.val end
351 if type(b) == 'table' then b = b.val end
352 if A then return a..b
353 else
354 return setmetatable({val=a..b}, t)
355 end
356end
357
358c = {val="c"}; setmetatable(c, t)
359d = {val="d"}; setmetatable(d, t)
360
361A = true
362assert(c..d == 'cd')
363assert(0 .."a".."b"..c..d.."e".."f"..(5+3).."g" == "0abcdef8g")
364
365A = false
366assert((c..d..c..d).val == 'cdcd')
367x = c..d
368assert(getmetatable(x) == t and x.val == 'cd')
369x = 0 .."a".."b"..c..d.."e".."f".."g"
370assert(x.val == "0abcdefg")
371
372
373-- concat metamethod x numbers (bug in 5.1.1)
374c = {}
375local x
376setmetatable(c, {__concat = function (a,b)
377 assert(type(a) == "number" and b == c or type(b) == "number" and a == c)
378 return c
379end})
380assert(c..5 == c and 5 .. c == c)
381assert(4 .. c .. 5 == c and 4 .. 5 .. 6 .. 7 .. c == c)
382
383
384-- test comparison compatibilities
385local t1, t2, c, d
386t1 = {}; c = {}; setmetatable(c, t1)
387d = {}
388t1.__eq = function () return true end
389t1.__lt = function () return true end
390t1.__le = function () return false end
391setmetatable(d, t1)
392assert(c == d and c < d and not(d <= c))
393t2 = {}
394t2.__eq = t1.__eq
395t2.__lt = t1.__lt
396setmetatable(d, t2)
397assert(c == d and c < d and not(d <= c))
398
399
400
401-- test for several levels of calls
402local i
403local tt = {
404 __call = function (t, ...)
405 i = i+1
406 if t.f then return t.f(...)
407 else return {...}
408 end
409 end
410}
411
412local a = setmetatable({}, tt)
413local b = setmetatable({f=a}, tt)
414local c = setmetatable({f=b}, tt)
415
416i = 0
417x = c(3,4,5)
418assert(i == 3 and x[1] == 3 and x[3] == 5)
419
420
421assert(_G.X == 20)
422
423_G.X, _G.B = nil
424
425
426print'+'
427
428local _g = _G
429_ENV = setmetatable({}, {__index=function (_,k) return _g[k] end})
430
431
432a = {}
433rawset(a, "x", 1, 2, 3)
434assert(a.x == 1 and rawget(a, "x", 3) == 1)
435
436print '+'
437
438-- testing metatables for basic types
439mt = {__index = function (a,b) return a+b end,
440 __len = function (x) return math.floor(x) end}
441debug.setmetatable(10, mt)
442assert(getmetatable(-2) == mt)
443assert((10)[3] == 13)
444assert((10)["3"] == 13)
445assert(#3.45 == 3)
446debug.setmetatable(23, nil)
447assert(getmetatable(-2) == nil)
448
449debug.setmetatable(true, mt)
450assert(getmetatable(false) == mt)
451mt.__index = function (a,b) return a or b end
452assert((true)[false] == true)
453assert((false)[false] == false)
454debug.setmetatable(false, nil)
455assert(getmetatable(true) == nil)
456
457debug.setmetatable(nil, mt)
458assert(getmetatable(nil) == mt)
459mt.__add = function (a,b) return (a or 1) + (b or 2) end
460assert(10 + nil == 12)
461assert(nil + 23 == 24)
462assert(nil + nil == 3)
463debug.setmetatable(nil, nil)
464assert(getmetatable(nil) == nil)
465
466debug.setmetatable(nil, {})
467
468
469-- loops in delegation
470a = {}; setmetatable(a, a); a.__index = a; a.__newindex = a
471assert(not pcall(function (a,b) return a[b] end, a, 10))
472assert(not pcall(function (a,b,c) a[b] = c end, a, 10, true))
473
474-- bug in 5.1
475T, K, V = nil
476grandparent = {}
477grandparent.__newindex = function(t,k,v) T=t; K=k; V=v end
478
479parent = {}
480parent.__newindex = parent
481setmetatable(parent, grandparent)
482
483child = setmetatable({}, parent)
484child.foo = 10 --> CRASH (on some machines)
485assert(T == parent and K == "foo" and V == 10)
486
487print 'OK'
488
489return 12
490
491
diff --git a/zig-lua/lua-5.4.7/testes/files.lua b/zig-lua/lua-5.4.7/testes/files.lua
new file mode 100644
index 0000000..1476006
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/files.lua
@@ -0,0 +1,951 @@
1-- $Id: testes/files.lua $
2-- See Copyright Notice in file all.lua
3
4local debug = require "debug"
5
6local maxint = math.maxinteger
7
8assert(type(os.getenv"PATH") == "string")
9
10assert(io.input(io.stdin) == io.stdin)
11assert(not pcall(io.input, "non-existent-file"))
12assert(io.output(io.stdout) == io.stdout)
13
14
15local function testerr (msg, f, ...)
16 local stat, err = pcall(f, ...)
17 return (not stat and string.find(err, msg, 1, true))
18end
19
20
21local function checkerr (msg, f, ...)
22 assert(testerr(msg, f, ...))
23end
24
25
26-- cannot close standard files
27assert(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)
32checkerr("got no value", io.stdin.close)
33
34
35assert(type(io.input()) == "userdata" and io.type(io.output()) == "file")
36assert(type(io.stdin) == "userdata" and io.type(io.stderr) == "file")
37assert(not io.type(8))
38local a = {}; setmetatable(a, {})
39assert(not io.type(a))
40
41assert(getmetatable(io.input()).__name == "FILE*")
42
43local a,b,c = io.open('xuxu_nao_existe')
44assert(not a and type(b) == "string" and type(c) == "number")
45
46a,b,c = io.open('/a/b/c/d', 'w')
47assert(not a and type(b) == "string" and type(c) == "number")
48
49local file = os.tmpname()
50local f, msg = io.open(file, "w")
51if not f then
52 (Message or print)("'os.tmpname' file cannot be open; skipping file tests")
53
54else --{ most tests here need tmpname
55f:close()
56
57print('testing i/o')
58
59local otherfile = os.tmpname()
60
61checkerr("invalid mode", io.open, file, "rw")
62checkerr("invalid mode", io.open, file, "rb+")
63checkerr("invalid mode", io.open, file, "r+bk")
64checkerr("invalid mode", io.open, file, "")
65checkerr("invalid mode", io.open, file, "+")
66checkerr("invalid mode", io.open, file, "b")
67assert(io.open(file, "r+b")):close()
68assert(io.open(file, "r+")):close()
69assert(io.open(file, "rb")):close()
70
71assert(os.setlocale('C', 'all'))
72
73io.input(io.stdin); io.output(io.stdout);
74
75os.remove(file)
76assert(not loadfile(file))
77checkerr("", dofile, file)
78assert(not io.open(file))
79io.output(file)
80assert(io.output() ~= io.stdout)
81
82if 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")
85end
86
87assert(io.output():seek() == 0)
88assert(io.write("alo alo"):seek() == string.len("alo alo"))
89assert(io.output():seek("cur", -3) == string.len("alo alo")-3)
90assert(io.write("joao"))
91assert(io.output():seek("end") == string.len("alo joao"))
92
93assert(io.output():seek("set") == 0)
94
95assert(io.write('"alo"', "{a}\n", "second line\n", "third line \n"))
96assert(io.write('Xfourth_line'))
97io.output(io.stdout)
98collectgarbage() -- file should be closed by GC
99assert(io.input() == io.stdin and rawequal(io.output(), io.stdout))
100print('+')
101
102-- test GC for files
103collectgarbage()
104for 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()
111end
112
113io.input():close()
114io.close()
115
116assert(os.rename(file, otherfile))
117assert(not os.rename(file, otherfile))
118
119io.output(io.open(otherfile, "ab"))
120assert(io.write("\n\n\t\t ", 3450, "\n"));
121io.close()
122
123
124do
125 -- closing file by scope
126 local F = nil
127 do
128 local f <close> = assert(io.open(file, "w"))
129 F = f
130 end
131 assert(tostring(F) == "file (closed)")
132end
133assert(os.remove(file))
134
135
136do
137 -- test writing/reading numbers
138 local f <close> = assert(io.open(file, "w"))
139 f:write(maxint, '\n')
140 f:write(string.format("0X%x\n", maxint))
141 f:write("0xABCp-3", '\n')
142 f:write(0, '\n')
143 f:write(-maxint, '\n')
144 f:write(string.format("0x%X\n", -maxint))
145 f:write("-0xABCp-3", '\n')
146 assert(f:close())
147 local f <close> = assert(io.open(file, "r"))
148 assert(f:read("n") == maxint)
149 assert(f:read("n") == maxint)
150 assert(f:read("n") == 0xABCp-3)
151 assert(f:read("n") == 0)
152 assert(f:read("*n") == -maxint) -- test old format (with '*')
153 assert(f:read("n") == -maxint)
154 assert(f:read("*n") == -0xABCp-3) -- test old format (with '*')
155end
156assert(os.remove(file))
157
158
159-- testing multiple arguments to io.read
160do
161 local f <close> = assert(io.open(file, "w"))
162 f:write[[
163a line
164another line
1651234
1663.45
167one
168two
169three
170]]
171 local l1, l2, l3, l4, n1, n2, c, dummy
172 assert(f:close())
173 local f <close> = assert(io.open(file, "r"))
174 l1, l2, n1, n2, dummy = f:read("l", "L", "n", "n")
175 assert(l1 == "a line" and l2 == "another line\n" and
176 n1 == 1234 and n2 == 3.45 and dummy == nil)
177 assert(f:close())
178 local f <close> = assert(io.open(file, "r"))
179 l1, l2, n1, n2, c, l3, l4, dummy = f:read(7, "l", "n", "n", 1, "l", "l")
180 assert(l1 == "a line\n" and l2 == "another line" and c == '\n' and
181 n1 == 1234 and n2 == 3.45 and l3 == "one" and l4 == "two"
182 and dummy == nil)
183 assert(f:close())
184 local f <close> = assert(io.open(file, "r"))
185 -- second item failing
186 l1, n1, n2, dummy = f:read("l", "n", "n", "l")
187 assert(l1 == "a line" and not n1)
188end
189assert(os.remove(file))
190
191
192
193-- test yielding during 'dofile'
194f = assert(io.open(file, "w"))
195f:write[[
196local x, z = coroutine.yield(10)
197local y = coroutine.yield(20)
198return x + y * z
199]]
200assert(f:close())
201f = coroutine.wrap(dofile)
202assert(f(file) == 10)
203assert(f(100, 101) == 20)
204assert(f(200) == 100 + 200 * 101)
205assert(os.remove(file))
206
207
208f = assert(io.open(file, "w"))
209-- test number termination
210f:write[[
211-12.3- -0xffff+ .3|5.E-3X +234e+13E 0xDEADBEEFDEADBEEFx
2120x1.13Ap+3e
213]]
214-- very long number
215f:write("1234"); for i = 1, 1000 do f:write("0") end; f:write("\n")
216-- invalid sequences (must read and discard valid prefixes)
217f:write[[
218.e+ 0.e; --; 0xX;
219]]
220assert(f:close())
221f = assert(io.open(file, "r"))
222assert(f:read("n") == -12.3); assert(f:read(1) == "-")
223assert(f:read("n") == -0xffff); assert(f:read(2) == "+ ")
224assert(f:read("n") == 0.3); assert(f:read(1) == "|")
225assert(f:read("n") == 5e-3); assert(f:read(1) == "X")
226assert(f:read("n") == 234e13); assert(f:read(1) == "E")
227assert(f:read("n") == 0Xdeadbeefdeadbeef); assert(f:read(2) == "x\n")
228assert(f:read("n") == 0x1.13aP3); assert(f:read(1) == "e")
229
230do -- attempt to read too long number
231 assert(not f:read("n")) -- fails
232 local s = f:read("L") -- read rest of line
233 assert(string.find(s, "^00*\n$")) -- lots of 0's left
234end
235
236assert(not f:read("n")); assert(f:read(2) == "e+")
237assert(not f:read("n")); assert(f:read(1) == ";")
238assert(not f:read("n")); assert(f:read(2) == "-;")
239assert(not f:read("n")); assert(f:read(1) == "X")
240assert(not f:read("n")); assert(f:read(1) == ";")
241assert(not f:read("n")); assert(not f:read(0)) -- end of file
242assert(f:close())
243assert(os.remove(file))
244
245
246-- test line generators
247assert(not pcall(io.lines, "non-existent-file"))
248assert(os.rename(otherfile, file))
249io.output(otherfile)
250local n = 0
251local f = io.lines(file)
252while f() do n = n + 1 end;
253assert(n == 6) -- number of lines in the file
254checkerr("file is already closed", f)
255checkerr("file is already closed", f)
256-- copy from file to otherfile
257n = 0
258for l in io.lines(file) do io.write(l, "\n"); n = n + 1 end
259io.close()
260assert(n == 6)
261-- copy from otherfile back to file
262local f = assert(io.open(otherfile))
263assert(io.type(f) == "file")
264io.output(file)
265assert(not io.output():read())
266n = 0
267for l in f:lines() do io.write(l, "\n"); n = n + 1 end
268assert(tostring(f):sub(1, 5) == "file ")
269assert(f:close()); io.close()
270assert(n == 6)
271checkerr("closed file", io.close, f)
272assert(tostring(f) == "file (closed)")
273assert(io.type(f) == "closed file")
274io.input(file)
275f = io.open(otherfile):lines()
276n = 0
277for l in io.lines() do assert(l == f()); n = n + 1 end
278f = nil; collectgarbage()
279assert(n == 6)
280assert(os.remove(otherfile))
281
282do -- bug in 5.3.1
283 io.output(otherfile)
284 io.write(string.rep("a", 300), "\n")
285 io.close()
286 local t ={}; for i = 1, 250 do t[i] = 1 end
287 t = {io.lines(otherfile, table.unpack(t))()}
288 -- everything ok here
289 assert(#t == 250 and t[1] == 'a' and t[#t] == 'a')
290 t[#t + 1] = 1 -- one too many
291 checkerr("too many arguments", io.lines, otherfile, table.unpack(t))
292 collectgarbage() -- ensure 'otherfile' is closed
293 assert(os.remove(otherfile))
294end
295
296io.input(file)
297do -- test error returns
298 local a,b,c = io.input():write("xuxu")
299 assert(not a and type(b) == "string" and type(c) == "number")
300end
301checkerr("invalid format", io.read, "x")
302assert(io.read(0) == "") -- not eof
303assert(io.read(5, 'l') == '"alo"')
304assert(io.read(0) == "")
305assert(io.read() == "second line")
306local x = io.input():seek()
307assert(io.read() == "third line ")
308assert(io.input():seek("set", x))
309assert(io.read('L') == "third line \n")
310assert(io.read(1) == "X")
311assert(io.read(string.len"fourth_line") == "fourth_line")
312assert(io.input():seek("cur", -string.len"fourth_line"))
313assert(io.read() == "fourth_line")
314assert(io.read() == "") -- empty line
315assert(io.read('n') == 3450)
316assert(io.read(1) == '\n')
317assert(not io.read(0)) -- end of file
318assert(not io.read(1)) -- end of file
319assert(not io.read(30000)) -- end of file
320assert(({io.read(1)})[2] == undef)
321assert(not io.read()) -- end of file
322assert(({io.read()})[2] == undef)
323assert(not io.read('n')) -- end of file
324assert(({io.read('n')})[2] == undef)
325assert(io.read('a') == '') -- end of file (OK for 'a')
326assert(io.read('a') == '') -- end of file (OK for 'a')
327collectgarbage()
328print('+')
329io.close(io.input())
330checkerr(" input file is closed", io.read)
331
332assert(os.remove(file))
333
334local t = '0123456789'
335for i=1,10 do t = t..t; end
336assert(string.len(t) == 10*2^10)
337
338io.output(file)
339io.write("alo"):write("\n")
340io.close()
341checkerr(" output file is closed", io.write)
342local f = io.open(file, "a+b")
343io.output(f)
344collectgarbage()
345
346assert(io.write(' ' .. t .. ' '))
347assert(io.write(';', 'end of file\n'))
348f:flush(); io.flush()
349f:close()
350print('+')
351
352io.input(file)
353assert(io.read() == "alo")
354assert(io.read(1) == ' ')
355assert(io.read(string.len(t)) == t)
356assert(io.read(1) == ' ')
357assert(io.read(0))
358assert(io.read('a') == ';end of file\n')
359assert(not io.read(0))
360assert(io.close(io.input()))
361
362
363-- test errors in read/write
364do
365 local function ismsg (m)
366 -- error message is not a code number
367 return (type(m) == "string" and not tonumber(m))
368 end
369
370 -- read
371 local f = io.open(file, "w")
372 local r, m, c = f:read()
373 assert(not r and ismsg(m) and type(c) == "number")
374 assert(f:close())
375 -- write
376 f = io.open(file, "r")
377 r, m, c = f:write("whatever")
378 assert(not r and ismsg(m) and type(c) == "number")
379 assert(f:close())
380 -- lines
381 f = io.open(file, "w")
382 r, m = pcall(f:lines())
383 assert(r == false and ismsg(m))
384 assert(f:close())
385end
386
387assert(os.remove(file))
388
389-- test for L format
390io.output(file); io.write"\n\nline\nother":close()
391io.input(file)
392assert(io.read"L" == "\n")
393assert(io.read"L" == "\n")
394assert(io.read"L" == "line\n")
395assert(io.read"L" == "other")
396assert(not io.read"L")
397io.input():close()
398
399local f = assert(io.open(file))
400local s = ""
401for l in f:lines("L") do s = s .. l end
402assert(s == "\n\nline\nother")
403f:close()
404
405io.input(file)
406s = ""
407for l in io.lines(nil, "L") do s = s .. l end
408assert(s == "\n\nline\nother")
409io.input():close()
410
411s = ""
412for l in io.lines(file, "L") do s = s .. l end
413assert(s == "\n\nline\nother")
414
415s = ""
416for l in io.lines(file, "l") do s = s .. l end
417assert(s == "lineother")
418
419io.output(file); io.write"a = 10 + 34\na = 2*a\na = -a\n":close()
420local t = {}
421assert(load(io.lines(file, "L"), nil, nil, t))()
422assert(t.a == -((10 + 34) * 2))
423
424
425do -- testing closing file in line iteration
426
427 -- get the to-be-closed variable from a loop
428 local function gettoclose (lv)
429 lv = lv + 1
430 local stvar = 0 -- to-be-closed is 4th state variable in the loop
431 for i = 1, 1000 do
432 local n, v = debug.getlocal(lv, i)
433 if n == "(for state)" then
434 stvar = stvar + 1
435 if stvar == 4 then return v end
436 end
437 end
438 end
439
440 local f
441 for l in io.lines(file) do
442 f = gettoclose(1)
443 assert(io.type(f) == "file")
444 break
445 end
446 assert(io.type(f) == "closed file")
447
448 f = nil
449 local function foo (name)
450 for l in io.lines(name) do
451 f = gettoclose(1)
452 assert(io.type(f) == "file")
453 error(f) -- exit loop with an error
454 end
455 end
456 local st, msg = pcall(foo, file)
457 assert(st == false and io.type(msg) == "closed file")
458
459end
460
461
462-- test for multipe arguments in 'lines'
463io.output(file); io.write"0123456789\n":close()
464for a,b in io.lines(file, 1, 1) do
465 if a == "\n" then assert(not b)
466 else assert(tonumber(a) == tonumber(b) - 1)
467 end
468end
469
470for a,b,c in io.lines(file, 1, 2, "a") do
471 assert(a == "0" and b == "12" and c == "3456789\n")
472end
473
474for a,b,c in io.lines(file, "a", 0, 1) do
475 if a == "" then break end
476 assert(a == "0123456789\n" and not b and not c)
477end
478collectgarbage() -- to close file in previous iteration
479
480io.output(file); io.write"00\n10\n20\n30\n40\n":close()
481for a, b in io.lines(file, "n", "n") do
482 if a == 40 then assert(not b)
483 else assert(a == b - 10)
484 end
485end
486
487
488-- test load x lines
489io.output(file);
490io.write[[
491local y
492= X
493X =
494X *
4952 +
496X;
497X =
498X
499- y;
500]]:close()
501_G.X = 1
502assert(not load((io.lines(file))))
503collectgarbage() -- to close file in previous iteration
504load((io.lines(file, "L")))()
505assert(_G.X == 2)
506load((io.lines(file, 1)))()
507assert(_G.X == 4)
508load((io.lines(file, 3)))()
509assert(_G.X == 8)
510_G.X = nil
511
512print('+')
513
514local x1 = "string\n\n\\com \"\"''coisas [[estranhas]] ]]'"
515io.output(file)
516assert(io.write(string.format("X2 = %q\n-- comment without ending EOS", x1)))
517io.close()
518assert(loadfile(file))()
519assert(x1 == _G.X2)
520_G.X2 = nil
521print('+')
522assert(os.remove(file))
523assert(not os.remove(file))
524assert(not os.remove(otherfile))
525
526-- testing loadfile
527local function testloadfile (s, expres)
528 io.output(file)
529 if s then io.write(s) end
530 io.close()
531 local res = assert(loadfile(file))()
532 assert(os.remove(file))
533 assert(res == expres)
534end
535
536-- loading empty file
537testloadfile(nil, nil)
538
539-- loading file with initial comment without end of line
540testloadfile("# a non-ending comment", nil)
541
542
543-- checking Unicode BOM in files
544testloadfile("\xEF\xBB\xBF# some comment\nreturn 234", 234)
545testloadfile("\xEF\xBB\xBFreturn 239", 239)
546testloadfile("\xEF\xBB\xBF", nil) -- empty file with a BOM
547
548
549-- checking line numbers in files with initial comments
550testloadfile("# a comment\nreturn require'debug'.getinfo(1).currentline", 2)
551
552
553-- loading binary file
554io.output(io.open(file, "wb"))
555assert(io.write(string.dump(function () return 10, '\0alo\255', 'hi' end)))
556io.close()
557a, b, c = assert(loadfile(file))()
558assert(a == 10 and b == "\0alo\255" and c == "hi")
559assert(os.remove(file))
560
561-- bug in 5.2.1
562do
563 io.output(io.open(file, "wb"))
564 -- save function with no upvalues
565 assert(io.write(string.dump(function () return 1 end)))
566 io.close()
567 f = assert(loadfile(file, "b", {}))
568 assert(type(f) == "function" and f() == 1)
569 assert(os.remove(file))
570end
571
572-- loading binary file with initial comment
573io.output(io.open(file, "wb"))
574assert(io.write("#this is a comment for a binary file\0\n",
575 string.dump(function () return 20, '\0\0\0' end)))
576io.close()
577a, b, c = assert(loadfile(file))()
578assert(a == 20 and b == "\0\0\0" and c == nil)
579assert(os.remove(file))
580
581
582-- 'loadfile' with 'env'
583do
584 local f = io.open(file, 'w')
585 f:write[[
586 if (...) then a = 15; return b, c, d
587 else return _ENV
588 end
589 ]]
590 f:close()
591 local t = {b = 12, c = "xuxu", d = print}
592 local f = assert(loadfile(file, 't', t))
593 local b, c, d = f(1)
594 assert(t.a == 15 and b == 12 and c == t.c and d == print)
595 assert(f() == t)
596 f = assert(loadfile(file, 't', nil))
597 assert(f() == nil)
598 f = assert(loadfile(file))
599 assert(f() == _G)
600 assert(os.remove(file))
601end
602
603
604-- 'loadfile' x modes
605do
606 io.open(file, 'w'):write("return 10"):close()
607 local s, m = loadfile(file, 'b')
608 assert(not s and string.find(m, "a text chunk"))
609 io.open(file, 'w'):write("\27 return 10"):close()
610 local s, m = loadfile(file, 't')
611 assert(not s and string.find(m, "a binary chunk"))
612 assert(os.remove(file))
613end
614
615
616io.output(file)
617assert(io.write("qualquer coisa\n"))
618assert(io.write("mais qualquer coisa"))
619io.close()
620assert(io.output(assert(io.open(otherfile, 'wb')))
621 :write("outra coisa\0\1\3\0\0\0\0\255\0")
622 :close())
623
624local filehandle = assert(io.open(file, 'r+'))
625local otherfilehandle = assert(io.open(otherfile, 'rb'))
626assert(filehandle ~= otherfilehandle)
627assert(type(filehandle) == "userdata")
628assert(filehandle:read('l') == "qualquer coisa")
629io.input(otherfilehandle)
630assert(io.read(string.len"outra coisa") == "outra coisa")
631assert(filehandle:read('l') == "mais qualquer coisa")
632filehandle:close();
633assert(type(filehandle) == "userdata")
634io.input(otherfilehandle)
635assert(io.read(4) == "\0\1\3\0")
636assert(io.read(3) == "\0\0\0")
637assert(io.read(0) == "") -- 255 is not eof
638assert(io.read(1) == "\255")
639assert(io.read('a') == "\0")
640assert(not io.read(0))
641assert(otherfilehandle == io.input())
642otherfilehandle:close()
643assert(os.remove(file))
644assert(os.remove(otherfile))
645collectgarbage()
646
647io.output(file)
648 :write[[
649 123.4 -56e-2 not a number
650second line
651third line
652
653and the rest of the file
654]]
655 :close()
656io.input(file)
657local _,a,b,c,d,e,h,__ = io.read(1, 'n', 'n', 'l', 'l', 'l', 'a', 10)
658assert(io.close(io.input()))
659assert(_ == ' ' and not __)
660assert(type(a) == 'number' and a==123.4 and b==-56e-2)
661assert(d=='second line' and e=='third line')
662assert(h==[[
663
664and the rest of the file
665]])
666assert(os.remove(file))
667collectgarbage()
668
669-- testing buffers
670do
671 local f = assert(io.open(file, "w"))
672 local fr = assert(io.open(file, "r"))
673 assert(f:setvbuf("full", 2000))
674 f:write("x")
675 assert(fr:read("all") == "") -- full buffer; output not written yet
676 f:close()
677 fr:seek("set")
678 assert(fr:read("all") == "x") -- `close' flushes it
679 f = assert(io.open(file), "w")
680 assert(f:setvbuf("no"))
681 f:write("x")
682 fr:seek("set")
683 assert(fr:read("all") == "x") -- no buffer; output is ready
684 f:close()
685 f = assert(io.open(file, "a"))
686 assert(f:setvbuf("line"))
687 f:write("x")
688 fr:seek("set", 1)
689 assert(fr:read("all") == "") -- line buffer; no output without `\n'
690 f:write("a\n"):seek("set", 1)
691 assert(fr:read("all") == "xa\n") -- now we have a whole line
692 f:close(); fr:close()
693 assert(os.remove(file))
694end
695
696
697if not _soft then
698 print("testing large files (> BUFSIZ)")
699 io.output(file)
700 for i=1,5001 do io.write('0123456789123') end
701 io.write('\n12346'):close()
702 io.input(file)
703 local x = io.read('a')
704 io.input():seek('set', 0)
705 local y = io.read(30001)..io.read(1005)..io.read(0)..
706 io.read(1)..io.read(100003)
707 assert(x == y and string.len(x) == 5001*13 + 6)
708 io.input():seek('set', 0)
709 y = io.read() -- huge line
710 assert(x == y..'\n'..io.read())
711 assert(not io.read())
712 io.close(io.input())
713 assert(os.remove(file))
714 x = nil; y = nil
715end
716
717if not _port then
718 local progname
719 do -- get name of running executable
720 local arg = arg or ARG
721 local i = 0
722 while arg[i] do i = i - 1 end
723 progname = '"' .. arg[i + 1] .. '"'
724 end
725 print("testing popen/pclose and execute")
726 -- invalid mode for popen
727 checkerr("invalid mode", io.popen, "cat", "")
728 checkerr("invalid mode", io.popen, "cat", "r+")
729 checkerr("invalid mode", io.popen, "cat", "rw")
730 do -- basic tests for popen
731 local file = os.tmpname()
732 local f = assert(io.popen("cat - > " .. file, "w"))
733 f:write("a line")
734 assert(f:close())
735 local f = assert(io.popen("cat - < " .. file, "r"))
736 assert(f:read("a") == "a line")
737 assert(f:close())
738 assert(os.remove(file))
739 end
740
741 local tests = {
742 -- command, what, code
743 {"ls > /dev/null", "ok"},
744 {"not-to-be-found-command", "exit"},
745 {"exit 3", "exit", 3},
746 {"exit 129", "exit", 129},
747 {"kill -s HUP $$", "signal", 1},
748 {"kill -s KILL $$", "signal", 9},
749 {"sh -c 'kill -s HUP $$'", "exit"},
750 {progname .. ' -e " "', "ok"},
751 {progname .. ' -e "os.exit(0, true)"', "ok"},
752 {progname .. ' -e "os.exit(20, true)"', "exit", 20},
753 }
754 print("\n(some error messages are expected now)")
755 for _, v in ipairs(tests) do
756 local x, y, z = io.popen(v[1]):close()
757 local x1, y1, z1 = os.execute(v[1])
758 assert(x == x1 and y == y1 and z == z1)
759 if v[2] == "ok" then
760 assert(x and y == 'exit' and z == 0)
761 else
762 assert(not x and y == v[2]) -- correct status and 'what'
763 -- correct code if known (but always different from 0)
764 assert((v[3] == nil and z > 0) or v[3] == z)
765 end
766 end
767end
768
769
770-- testing tmpfile
771f = io.tmpfile()
772assert(io.type(f) == "file")
773f:write("alo")
774f:seek("set")
775assert(f:read"a" == "alo")
776
777end --}
778
779print'+'
780
781print("testing date/time")
782
783assert(os.date("") == "")
784assert(os.date("!") == "")
785assert(os.date("\0\0") == "\0\0")
786assert(os.date("!\0\0") == "\0\0")
787local x = string.rep("a", 10000)
788assert(os.date(x) == x)
789local t = os.time()
790D = os.date("*t", t)
791assert(os.date(string.rep("%d", 1000), t) ==
792 string.rep(os.date("%d", t), 1000))
793assert(os.date(string.rep("%", 200)) == string.rep("%", 100))
794
795local function checkDateTable (t)
796 _G.D = os.date("*t", t)
797 assert(os.time(D) == t)
798 load(os.date([[assert(D.year==%Y and D.month==%m and D.day==%d and
799 D.hour==%H and D.min==%M and D.sec==%S and
800 D.wday==%w+1 and D.yday==%j)]], t))()
801 _G.D = nil
802end
803
804checkDateTable(os.time())
805if not _port then
806 -- assume that time_t can represent these values
807 checkDateTable(0)
808 checkDateTable(1)
809 checkDateTable(1000)
810 checkDateTable(0x7fffffff)
811 checkDateTable(0x80000000)
812end
813
814checkerr("invalid conversion specifier", os.date, "%")
815checkerr("invalid conversion specifier", os.date, "%9")
816checkerr("invalid conversion specifier", os.date, "%")
817checkerr("invalid conversion specifier", os.date, "%O")
818checkerr("invalid conversion specifier", os.date, "%E")
819checkerr("invalid conversion specifier", os.date, "%Ea")
820
821checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour='x'})
822checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour=1.5})
823
824checkerr("missing", os.time, {hour = 12}) -- missing date
825
826
827if string.packsize("i") == 4 then -- 4-byte ints
828 checkerr("field 'year' is out-of-bound", os.time,
829 {year = -(1 << 31) + 1899, month = 1, day = 1})
830
831 checkerr("field 'year' is out-of-bound", os.time,
832 {year = -(1 << 31), month = 1, day = 1})
833
834 if math.maxinteger > 2^31 then -- larger lua_integer?
835 checkerr("field 'year' is out-of-bound", os.time,
836 {year = (1 << 31) + 1900, month = 1, day = 1})
837 end
838end
839
840
841if not _port then
842 -- test Posix-specific modifiers
843 assert(type(os.date("%Ex")) == 'string')
844 assert(type(os.date("%Oy")) == 'string')
845
846 -- test large dates (assume at least 4-byte ints and time_t)
847 local t0 = os.time{year = 1970, month = 1, day = 0}
848 local t1 = os.time{year = 1970, month = 1, day = 0, sec = (1 << 31) - 1}
849 assert(t1 - t0 == (1 << 31) - 1)
850 t0 = os.time{year = 1970, month = 1, day = 1}
851 t1 = os.time{year = 1970, month = 1, day = 1, sec = -(1 << 31)}
852 assert(t1 - t0 == -(1 << 31))
853
854 -- test out-of-range dates (at least for Unix)
855 if maxint >= 2^62 then -- cannot do these tests in Small Lua
856 -- no arith overflows
857 checkerr("out-of-bound", os.time, {year = -maxint, month = 1, day = 1})
858 if string.packsize("i") == 4 then -- 4-byte ints
859 if testerr("out-of-bound", os.date, "%Y", 2^40) then
860 -- time_t has 4 bytes and therefore cannot represent year 4000
861 print(" 4-byte time_t")
862 checkerr("cannot be represented", os.time, {year=4000, month=1, day=1})
863 else
864 -- time_t has 8 bytes; an int year cannot represent a huge time
865 print(" 8-byte time_t")
866 checkerr("cannot be represented", os.date, "%Y", 2^60)
867
868 -- this is the maximum year
869 assert(tonumber(os.time
870 {year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=59}))
871
872 -- this is too much
873 checkerr("represented", os.time,
874 {year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=60})
875 end
876
877 -- internal 'int' fields cannot hold these values
878 checkerr("field 'day' is out-of-bound", os.time,
879 {year = 0, month = 1, day = 2^32})
880
881 checkerr("field 'month' is out-of-bound", os.time,
882 {year = 0, month = -((1 << 31) + 1), day = 1})
883
884 checkerr("field 'year' is out-of-bound", os.time,
885 {year = (1 << 31) + 1900, month = 1, day = 1})
886
887 else -- 8-byte ints
888 -- assume time_t has 8 bytes too
889 print(" 8-byte time_t")
890 assert(tonumber(os.date("%Y", 2^60)))
891
892 -- but still cannot represent a huge year
893 checkerr("cannot be represented", os.time, {year=2^60, month=1, day=1})
894 end
895 end
896end
897
898do
899 local D = os.date("*t")
900 local t = os.time(D)
901 if D.isdst == nil then
902 print("no daylight saving information")
903 else
904 assert(type(D.isdst) == 'boolean')
905 end
906 D.isdst = nil
907 local t1 = os.time(D)
908 assert(t == t1) -- if isdst is absent uses correct default
909end
910
911local D = os.date("*t")
912t = os.time(D)
913D.year = D.year-1;
914local t1 = os.time(D)
915-- allow for leap years
916assert(math.abs(os.difftime(t,t1)/(24*3600) - 365) < 2)
917
918-- should not take more than 1 second to execute these two lines
919t = os.time()
920t1 = os.time(os.date("*t"))
921local diff = os.difftime(t1,t)
922assert(0 <= diff and diff <= 1)
923diff = os.difftime(t,t1)
924assert(-1 <= diff and diff <= 0)
925
926local t1 = os.time{year=2000, month=10, day=1, hour=23, min=12}
927local t2 = os.time{year=2000, month=10, day=1, hour=23, min=10, sec=19}
928assert(os.difftime(t1,t2) == 60*2-19)
929
930-- since 5.3.3, 'os.time' normalizes table fields
931t1 = {year = 2005, month = 1, day = 1, hour = 1, min = 0, sec = -3602}
932os.time(t1)
933assert(t1.day == 31 and t1.month == 12 and t1.year == 2004 and
934 t1.hour == 23 and t1.min == 59 and t1.sec == 58 and
935 t1.yday == 366)
936
937io.output(io.stdout)
938local t = os.date('%d %m %Y %H %M %S')
939local d, m, a, h, min, s = string.match(t,
940 "(%d+) (%d+) (%d+) (%d+) (%d+) (%d+)")
941d = tonumber(d)
942m = tonumber(m)
943a = tonumber(a)
944h = tonumber(h)
945min = tonumber(min)
946s = tonumber(s)
947io.write(string.format('test done on %2.2d/%2.2d/%d', d, m, a))
948io.write(string.format(', at %2.2d:%2.2d:%2.2d\n', h, min, s))
949io.write(string.format('%s\n', _VERSION))
950
951
diff --git a/zig-lua/lua-5.4.7/testes/gc.lua b/zig-lua/lua-5.4.7/testes/gc.lua
new file mode 100644
index 0000000..03093e3
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/gc.lua
@@ -0,0 +1,695 @@
1-- $Id: testes/gc.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing incremental garbage collection')
5
6local debug = require"debug"
7
8assert(collectgarbage("isrunning"))
9
10collectgarbage()
11
12local oldmode = collectgarbage("incremental")
13
14-- changing modes should return previous mode
15assert(collectgarbage("generational") == "incremental")
16assert(collectgarbage("generational") == "generational")
17assert(collectgarbage("incremental") == "generational")
18assert(collectgarbage("incremental") == "incremental")
19
20
21local function nop () end
22
23local function gcinfo ()
24 return collectgarbage"count" * 1024
25end
26
27
28-- test weird parameters to 'collectgarbage'
29do
30 -- save original parameters
31 local a = collectgarbage("setpause", 200)
32 local b = collectgarbage("setstepmul", 200)
33 local t = {0, 2, 10, 90, 500, 5000, 30000, 0x7ffffffe}
34 for i = 1, #t do
35 local p = t[i]
36 for j = 1, #t do
37 local m = t[j]
38 collectgarbage("setpause", p)
39 collectgarbage("setstepmul", m)
40 collectgarbage("step", 0)
41 collectgarbage("step", 10000)
42 end
43 end
44 -- restore original parameters
45 collectgarbage("setpause", a)
46 collectgarbage("setstepmul", b)
47 collectgarbage()
48end
49
50
51_G["while"] = 234
52
53
54--
55-- tests for GC activation when creating different kinds of objects
56--
57local function GC1 ()
58 local u
59 local b -- (above 'u' it in the stack)
60 local finish = false
61 u = setmetatable({}, {__gc = function () finish = true end})
62 b = {34}
63 repeat u = {} until finish
64 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
65
66 finish = false; local i = 1
67 u = setmetatable({}, {__gc = function () finish = true end})
68 repeat i = i + 1; u = tostring(i) .. tostring(i) until finish
69 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
70
71 finish = false
72 u = setmetatable({}, {__gc = function () finish = true end})
73 repeat local i; u = function () return i end until finish
74 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
75end
76
77local function GC2 ()
78 local u
79 local finish = false
80 u = {setmetatable({}, {__gc = function () finish = true end})}
81 local b = {34}
82 repeat u = {{}} until finish
83 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
84
85 finish = false; local i = 1
86 u = {setmetatable({}, {__gc = function () finish = true end})}
87 repeat i = i + 1; u = {tostring(i) .. tostring(i)} until finish
88 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
89
90 finish = false
91 u = {setmetatable({}, {__gc = function () finish = true end})}
92 repeat local i; u = {function () return i end} until finish
93 assert(b[1] == 34) -- 'u' was collected, but 'b' was not
94end
95
96local function GC() GC1(); GC2() end
97
98
99do
100 print("creating many objects")
101
102 local limit = 5000
103
104 for i = 1, limit do
105 local a = {}; a = nil
106 end
107
108 local a = "a"
109
110 for i = 1, limit do
111 a = i .. "b";
112 a = string.gsub(a, '(%d%d*)', "%1 %1")
113 a = "a"
114 end
115
116
117
118 a = {}
119
120 function a:test ()
121 for i = 1, limit do
122 load(string.format("function temp(a) return 'a%d' end", i), "")()
123 assert(temp() == string.format('a%d', i))
124 end
125 end
126
127 a:test()
128 _G.temp = nil
129end
130
131
132-- collection of functions without locals, globals, etc.
133do local f = function () end end
134
135
136print("functions with errors")
137local prog = [[
138do
139 a = 10;
140 function foo(x,y)
141 a = sin(a+0.456-0.23e-12);
142 return function (z) return sin(%x+z) end
143 end
144 local x = function (w) a=a+w; end
145end
146]]
147do
148 local step = 1
149 if _soft then step = 13 end
150 for i=1, string.len(prog), step do
151 for j=i, string.len(prog), step do
152 pcall(load(string.sub(prog, i, j), ""))
153 end
154 end
155end
156rawset(_G, "a", nil)
157_G.x = nil
158
159do
160 foo = nil
161 print('long strings')
162 local x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
163 assert(string.len(x)==80)
164 local s = ''
165 local k = math.min(300, (math.maxinteger // 80) // 2)
166 for n = 1, k do s = s..x; local j=tostring(n) end
167 assert(string.len(s) == k*80)
168 s = string.sub(s, 1, 10000)
169 local s, i = string.gsub(s, '(%d%d%d%d)', '')
170 assert(i==10000 // 4)
171
172 assert(_G["while"] == 234)
173 _G["while"] = nil
174end
175
176
177--
178-- test the "size" of basic GC steps (whatever they mean...)
179--
180do
181print("steps")
182
183 print("steps (2)")
184
185 local function dosteps (siz)
186 collectgarbage()
187 local a = {}
188 for i=1,100 do a[i] = {{}}; local b = {} end
189 local x = gcinfo()
190 local i = 0
191 repeat -- do steps until it completes a collection cycle
192 i = i+1
193 until collectgarbage("step", siz)
194 assert(gcinfo() < x)
195 return i -- number of steps
196 end
197
198 collectgarbage"stop"
199
200 if not _port then
201 assert(dosteps(10) < dosteps(2))
202 end
203
204 -- collector should do a full collection with so many steps
205 assert(dosteps(20000) == 1)
206 assert(collectgarbage("step", 20000) == true)
207 assert(collectgarbage("step", 20000) == true)
208
209 assert(not collectgarbage("isrunning"))
210 collectgarbage"restart"
211 assert(collectgarbage("isrunning"))
212
213end
214
215
216if not _port then
217 -- test the pace of the collector
218 collectgarbage(); collectgarbage()
219 local x = gcinfo()
220 collectgarbage"stop"
221 repeat
222 local a = {}
223 until gcinfo() > 3 * x
224 collectgarbage"restart"
225 assert(collectgarbage("isrunning"))
226 repeat
227 local a = {}
228 until gcinfo() <= x * 2
229end
230
231
232print("clearing tables")
233local lim = 15
234local a = {}
235-- fill a with `collectable' indices
236for i=1,lim do a[{}] = i end
237b = {}
238for k,v in pairs(a) do b[k]=v end
239-- remove all indices and collect them
240for n in pairs(b) do
241 a[n] = undef
242 assert(type(n) == 'table' and next(n) == nil)
243 collectgarbage()
244end
245b = nil
246collectgarbage()
247for n in pairs(a) do error'cannot be here' end
248for i=1,lim do a[i] = i end
249for i=1,lim do assert(a[i] == i) end
250
251
252print('weak tables')
253a = {}; setmetatable(a, {__mode = 'k'});
254-- fill a with some `collectable' indices
255for i=1,lim do a[{}] = i end
256-- and some non-collectable ones
257for i=1,lim do a[i] = i end
258for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end
259collectgarbage()
260local i = 0
261for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end
262assert(i == 2*lim)
263
264a = {}; setmetatable(a, {__mode = 'v'});
265a[1] = string.rep('b', 21)
266collectgarbage()
267assert(a[1]) -- strings are *values*
268a[1] = undef
269-- fill a with some `collectable' values (in both parts of the table)
270for i=1,lim do a[i] = {} end
271for i=1,lim do a[i..'x'] = {} end
272-- and some non-collectable ones
273for i=1,lim do local t={}; a[t]=t end
274for i=1,lim do a[i+lim]=i..'x' end
275collectgarbage()
276local i = 0
277for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end
278assert(i == 2*lim)
279
280a = {}; setmetatable(a, {__mode = 'kv'});
281local x, y, z = {}, {}, {}
282-- keep only some items
283a[1], a[2], a[3] = x, y, z
284a[string.rep('$', 11)] = string.rep('$', 11)
285-- fill a with some `collectable' values
286for i=4,lim do a[i] = {} end
287for i=1,lim do a[{}] = i end
288for i=1,lim do local t={}; a[t]=t end
289collectgarbage()
290assert(next(a) ~= nil)
291local i = 0
292for k,v in pairs(a) do
293 assert((k == 1 and v == x) or
294 (k == 2 and v == y) or
295 (k == 3 and v == z) or k==v);
296 i = i+1
297end
298assert(i == 4)
299x,y,z=nil
300collectgarbage()
301assert(next(a) == string.rep('$', 11))
302
303
304-- 'bug' in 5.1
305a = {}
306local t = {x = 10}
307local C = setmetatable({key = t}, {__mode = 'v'})
308local C1 = setmetatable({[t] = 1}, {__mode = 'k'})
309a.x = t -- this should not prevent 't' from being removed from
310 -- weak table 'C' by the time 'a' is finalized
311
312setmetatable(a, {__gc = function (u)
313 assert(C.key == nil)
314 assert(type(next(C1)) == 'table')
315 end})
316
317a, t = nil
318collectgarbage()
319collectgarbage()
320assert(next(C) == nil and next(C1) == nil)
321C, C1 = nil
322
323
324-- ephemerons
325local mt = {__mode = 'k'}
326a = {{10},{20},{30},{40}}; setmetatable(a, mt)
327x = nil
328for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end
329GC()
330local n = x
331local i = 0
332while n do n = a[n].k[1]; i = i + 1 end
333assert(i == 100)
334x = nil
335GC()
336for i = 1, 4 do assert(a[i][1] == i * 10); a[i] = undef end
337assert(next(a) == nil)
338
339local K = {}
340a[K] = {}
341for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end
342x = nil
343local k = 1
344for j = 1,100 do
345 local n = {}; local nk = k%10 + 1
346 a[a[K][nk]][n] = {x, k = k}; x = n; k = nk
347end
348GC()
349local n = x
350local i = 0
351while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end
352assert(i == 100)
353K = nil
354GC()
355-- assert(next(a) == nil)
356
357
358-- testing errors during GC
359if T then
360 collectgarbage("stop") -- stop collection
361 local u = {}
362 local s = {}; setmetatable(s, {__mode = 'k'})
363 setmetatable(u, {__gc = function (o)
364 local i = s[o]
365 s[i] = true
366 assert(not s[i - 1]) -- check proper finalization order
367 if i == 8 then error("@expected@") end -- error during GC
368 end})
369
370 for i = 6, 10 do
371 local n = setmetatable({}, getmetatable(u))
372 s[n] = i
373 end
374
375 warn("@on"); warn("@store")
376 collectgarbage()
377 assert(string.find(_WARN, "error in __gc"))
378 assert(string.match(_WARN, "@(.-)@") == "expected"); _WARN = false
379 for i = 8, 10 do assert(s[i]) end
380
381 for i = 1, 5 do
382 local n = setmetatable({}, getmetatable(u))
383 s[n] = i
384 end
385
386 collectgarbage()
387 for i = 1, 10 do assert(s[i]) end
388
389 getmetatable(u).__gc = nil
390 warn("@normal")
391
392end
393print '+'
394
395
396-- testing userdata
397if T==nil then
398 (Message or print)('\n >>> testC not active: skipping userdata GC tests <<<\n')
399
400else
401
402 local function newproxy(u)
403 return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u))
404 end
405
406 collectgarbage("stop") -- stop collection
407 local u = newproxy(nil)
408 debug.setmetatable(u, {__gc = true})
409 local s = 0
410 local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'})
411 for i=1,10 do a[newproxy(u)] = i end
412 for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end
413 local a1 = {}; for k,v in pairs(a) do a1[k] = v end
414 for k,v in pairs(a1) do a[v] = k end
415 for i =1,10 do assert(a[i]) end
416 getmetatable(u).a = a1
417 getmetatable(u).u = u
418 do
419 local u = u
420 getmetatable(u).__gc = function (o)
421 assert(a[o] == 10-s)
422 assert(a[10-s] == undef) -- udata already removed from weak table
423 assert(getmetatable(o) == getmetatable(u))
424 assert(getmetatable(o).a[o] == 10-s)
425 s=s+1
426 end
427 end
428 a1, u = nil
429 assert(next(a) ~= nil)
430 collectgarbage()
431 assert(s==11)
432 collectgarbage()
433 assert(next(a) == nil) -- finalized keys are removed in two cycles
434end
435
436
437-- __gc x weak tables
438local u = setmetatable({}, {__gc = true})
439-- __gc metamethod should be collected before running
440setmetatable(getmetatable(u), {__mode = "v"})
441getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen
442u = nil
443collectgarbage()
444
445local u = setmetatable({}, {__gc = true})
446local m = getmetatable(u)
447m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"});
448m.__gc = function (o)
449 assert(next(getmetatable(o).x) == nil)
450 m = 10
451end
452u, m = nil
453collectgarbage()
454assert(m==10)
455
456do -- tests for string keys in weak tables
457 collectgarbage(); collectgarbage()
458 local m = collectgarbage("count") -- current memory
459 local a = setmetatable({}, {__mode = "kv"})
460 a[string.rep("a", 2^22)] = 25 -- long string key -> number value
461 a[string.rep("b", 2^22)] = {} -- long string key -> colectable value
462 a[{}] = 14 -- colectable key
463 assert(collectgarbage("count") > m + 2^13) -- 2^13 == 2 * 2^22 in KB
464 collectgarbage()
465 assert(collectgarbage("count") >= m + 2^12 and
466 collectgarbage("count") < m + 2^13) -- one key was collected
467 local k, v = next(a) -- string key with number value preserved
468 assert(k == string.rep("a", 2^22) and v == 25)
469 assert(next(a, k) == nil) -- everything else cleared
470 assert(a[string.rep("b", 2^22)] == undef)
471 a[k] = undef -- erase this last entry
472 k = nil
473 collectgarbage()
474 assert(next(a) == nil)
475 -- make sure will not try to compare with dead key
476 assert(a[string.rep("b", 100)] == undef)
477 assert(collectgarbage("count") <= m + 1) -- eveything collected
478end
479
480
481-- errors during collection
482if T then
483 warn("@store")
484 u = setmetatable({}, {__gc = function () error "@expected error" end})
485 u = nil
486 collectgarbage()
487 assert(string.find(_WARN, "@expected error")); _WARN = false
488 warn("@normal")
489end
490
491
492if not _soft then
493 print("long list")
494 local a = {}
495 for i = 1,200000 do
496 a = {next = a}
497 end
498 a = nil
499 collectgarbage()
500end
501
502-- create many threads with self-references and open upvalues
503print("self-referenced threads")
504local thread_id = 0
505local threads = {}
506
507local function fn (thread)
508 local x = {}
509 threads[thread_id] = function()
510 thread = x
511 end
512 coroutine.yield()
513end
514
515while thread_id < 1000 do
516 local thread = coroutine.create(fn)
517 coroutine.resume(thread, thread)
518 thread_id = thread_id + 1
519end
520
521
522-- Create a closure (function inside 'f') with an upvalue ('param') that
523-- points (through a table) to the closure itself and to the thread
524-- ('co' and the initial value of 'param') where closure is running.
525-- Then, assert that table (and therefore everything else) will be
526-- collected.
527do
528 local collected = false -- to detect collection
529 collectgarbage(); collectgarbage("stop")
530 do
531 local function f (param)
532 ;(function ()
533 assert(type(f) == 'function' and type(param) == 'thread')
534 param = {param, f}
535 setmetatable(param, {__gc = function () collected = true end})
536 coroutine.yield(100)
537 end)()
538 end
539 local co = coroutine.create(f)
540 assert(coroutine.resume(co, co))
541 end
542 -- Now, thread and closure are not reacheable any more.
543 collectgarbage()
544 assert(collected)
545 collectgarbage("restart")
546end
547
548
549do
550 collectgarbage()
551 collectgarbage"stop"
552 collectgarbage("step", 0) -- steps should not unblock the collector
553 local x = gcinfo()
554 repeat
555 for i=1,1000 do _ENV.a = {} end -- no collection during the loop
556 until gcinfo() > 2 * x
557 collectgarbage"restart"
558 _ENV.a = nil
559end
560
561
562if T then -- tests for weird cases collecting upvalues
563
564 local function foo ()
565 local a = {x = 20}
566 coroutine.yield(function () return a.x end) -- will run collector
567 assert(a.x == 20) -- 'a' is 'ok'
568 a = {x = 30} -- create a new object
569 assert(T.gccolor(a) == "white") -- of course it is new...
570 coroutine.yield(100) -- 'a' is still local to this thread
571 end
572
573 local t = setmetatable({}, {__mode = "kv"})
574 collectgarbage(); collectgarbage('stop')
575 -- create coroutine in a weak table, so it will never be marked
576 t.co = coroutine.wrap(foo)
577 local f = t.co() -- create function to access local 'a'
578 T.gcstate("atomic") -- ensure all objects are traversed
579 assert(T.gcstate() == "atomic")
580 assert(t.co() == 100) -- resume coroutine, creating new table for 'a'
581 assert(T.gccolor(t.co) == "white") -- thread was not traversed
582 T.gcstate("pause") -- collect thread, but should mark 'a' before that
583 assert(t.co == nil and f() == 30) -- ensure correct access to 'a'
584
585 collectgarbage("restart")
586
587 -- test barrier in sweep phase (backing userdata to gray)
588 local u = T.newuserdata(0, 1) -- create a userdata
589 collectgarbage()
590 collectgarbage"stop"
591 local a = {} -- avoid 'u' as first element in 'allgc'
592 T.gcstate"atomic"
593 T.gcstate"sweepallgc"
594 local x = {}
595 assert(T.gccolor(u) == "black") -- userdata is "old" (black)
596 assert(T.gccolor(x) == "white") -- table is "new" (white)
597 debug.setuservalue(u, x) -- trigger barrier
598 assert(T.gccolor(u) == "gray") -- userdata changed back to gray
599 collectgarbage"restart"
600
601 print"+"
602end
603
604
605if T then
606 local debug = require "debug"
607 collectgarbage("stop")
608 local x = T.newuserdata(0)
609 local y = T.newuserdata(0)
610 debug.setmetatable(y, {__gc = nop}) -- bless the new udata before...
611 debug.setmetatable(x, {__gc = nop}) -- ...the old one
612 assert(T.gccolor(y) == "white")
613 T.checkmemory()
614 collectgarbage("restart")
615end
616
617
618if T then
619 print("emergency collections")
620 collectgarbage()
621 collectgarbage()
622 T.totalmem(T.totalmem() + 200)
623 for i=1,200 do local a = {} end
624 T.totalmem(0)
625 collectgarbage()
626 local t = T.totalmem("table")
627 local a = {{}, {}, {}} -- create 4 new tables
628 assert(T.totalmem("table") == t + 4)
629 t = T.totalmem("function")
630 a = function () end -- create 1 new closure
631 assert(T.totalmem("function") == t + 1)
632 t = T.totalmem("thread")
633 a = coroutine.create(function () end) -- create 1 new coroutine
634 assert(T.totalmem("thread") == t + 1)
635end
636
637
638-- create an object to be collected when state is closed
639do
640 local setmetatable,assert,type,print,getmetatable =
641 setmetatable,assert,type,print,getmetatable
642 local tt = {}
643 tt.__gc = function (o)
644 assert(getmetatable(o) == tt)
645 -- create new objects during GC
646 local a = 'xuxu'..(10+3)..'joao', {}
647 ___Glob = o -- ressurrect object!
648 setmetatable({}, tt) -- creates a new one with same metatable
649 print(">>> closing state " .. "<<<\n")
650 end
651 local u = setmetatable({}, tt)
652 ___Glob = {u} -- avoid object being collected before program end
653end
654
655-- create several objects to raise errors when collected while closing state
656if T then
657 local error, assert, find, warn = error, assert, string.find, warn
658 local n = 0
659 local lastmsg
660 local mt = {__gc = function (o)
661 n = n + 1
662 assert(n == o[1])
663 if n == 1 then
664 _WARN = false
665 elseif n == 2 then
666 assert(find(_WARN, "@expected warning"))
667 lastmsg = _WARN -- get message from previous error (first 'o')
668 else
669 assert(lastmsg == _WARN) -- subsequent error messages are equal
670 end
671 warn("@store"); _WARN = false
672 error"@expected warning"
673 end}
674 for i = 10, 1, -1 do
675 -- create object and preserve it until the end
676 table.insert(___Glob, setmetatable({i}, mt))
677 end
678end
679
680-- just to make sure
681assert(collectgarbage'isrunning')
682
683do -- check that the collector is not reentrant in incremental mode
684 local res = true
685 setmetatable({}, {__gc = function ()
686 res = collectgarbage()
687 end})
688 collectgarbage()
689 assert(not res)
690end
691
692
693collectgarbage(oldmode)
694
695print('OK')
diff --git a/zig-lua/lua-5.4.7/testes/gengc.lua b/zig-lua/lua-5.4.7/testes/gengc.lua
new file mode 100644
index 0000000..3d4f67f
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/gengc.lua
@@ -0,0 +1,172 @@
1-- $Id: testes/gengc.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing generational garbage collection')
5
6local debug = require"debug"
7
8assert(collectgarbage("isrunning"))
9
10collectgarbage()
11
12local oldmode = collectgarbage("generational")
13
14
15-- ensure that table barrier evolves correctly
16do
17 local U = {}
18 -- full collection makes 'U' old
19 collectgarbage()
20 assert(not T or T.gcage(U) == "old")
21
22 -- U refers to a new table, so it becomes 'touched1'
23 U[1] = {x = {234}}
24 assert(not T or (T.gcage(U) == "touched1" and T.gcage(U[1]) == "new"))
25
26 -- both U and the table survive one more collection
27 collectgarbage("step", 0)
28 assert(not T or (T.gcage(U) == "touched2" and T.gcage(U[1]) == "survival"))
29
30 -- both U and the table survive yet another collection
31 -- now everything is old
32 collectgarbage("step", 0)
33 assert(not T or (T.gcage(U) == "old" and T.gcage(U[1]) == "old1"))
34
35 -- data was not corrupted
36 assert(U[1].x[1] == 234)
37end
38
39
40do
41 -- ensure that 'firstold1' is corrected when object is removed from
42 -- the 'allgc' list
43 local function foo () end
44 local old = {10}
45 collectgarbage() -- make 'old' old
46 assert(not T or T.gcage(old) == "old")
47 setmetatable(old, {}) -- new table becomes OLD0 (barrier)
48 assert(not T or T.gcage(getmetatable(old)) == "old0")
49 collectgarbage("step", 0) -- new table becomes OLD1 and firstold1
50 assert(not T or T.gcage(getmetatable(old)) == "old1")
51 setmetatable(getmetatable(old), {__gc = foo}) -- get it out of allgc list
52 collectgarbage("step", 0) -- should not seg. fault
53end
54
55
56do -- bug in 5.4.0
57-- When an object aged OLD1 is finalized, it is moved from the list
58-- 'finobj' to the *beginning* of the list 'allgc', but that part of the
59-- list was not being visited by 'markold'.
60 local A = {}
61 A[1] = false -- old anchor for object
62
63 -- obj finalizer
64 local function gcf (obj)
65 A[1] = obj -- anchor object
66 assert(not T or T.gcage(obj) == "old1")
67 obj = nil -- remove it from the stack
68 collectgarbage("step", 0) -- do a young collection
69 print(getmetatable(A[1]).x) -- metatable was collected
70 end
71
72 collectgarbage() -- make A old
73 local obj = {} -- create a new object
74 collectgarbage("step", 0) -- make it a survival
75 assert(not T or T.gcage(obj) == "survival")
76 setmetatable(obj, {__gc = gcf, x = "+"}) -- create its metatable
77 assert(not T or T.gcage(getmetatable(obj)) == "new")
78 obj = nil -- clear object
79 collectgarbage("step", 0) -- will call obj's finalizer
80end
81
82
83do -- another bug in 5.4.0
84 local old = {10}
85 collectgarbage() -- make 'old' old
86 local co = coroutine.create(
87 function ()
88 local x = nil
89 local f = function ()
90 return x[1]
91 end
92 x = coroutine.yield(f)
93 coroutine.yield()
94 end
95 )
96 local _, f = coroutine.resume(co) -- create closure over 'x' in coroutine
97 collectgarbage("step", 0) -- make upvalue a survival
98 old[1] = {"hello"} -- 'old' go to grayagain as 'touched1'
99 coroutine.resume(co, {123}) -- its value will be new
100 co = nil
101 collectgarbage("step", 0) -- hit the barrier
102 assert(f() == 123 and old[1][1] == "hello")
103 collectgarbage("step", 0) -- run the collector once more
104 -- make sure old[1] was not collected
105 assert(f() == 123 and old[1][1] == "hello")
106end
107
108
109do -- bug introduced in commit 9cf3299fa
110 local t = setmetatable({}, {__mode = "kv"}) -- all-weak table
111 collectgarbage() -- full collection
112 assert(not T or T.gcage(t) == "old")
113 t[1] = {10}
114 assert(not T or (T.gcage(t) == "touched1" and T.gccolor(t) == "gray"))
115 collectgarbage("step", 0) -- minor collection
116 assert(not T or (T.gcage(t) == "touched2" and T.gccolor(t) == "black"))
117 collectgarbage("step", 0) -- minor collection
118 assert(not T or T.gcage(t) == "old") -- t should be black, but it was gray
119 t[1] = {10} -- no barrier here, so t was still old
120 collectgarbage("step", 0) -- minor collection
121 -- t, being old, is ignored by the collection, so it is not cleared
122 assert(t[1] == nil) -- fails with the bug
123end
124
125
126if T == nil then
127 (Message or print)('\n >>> testC not active: \z
128 skipping some generational tests <<<\n')
129 print 'OK'
130 return
131end
132
133
134-- ensure that userdata barrier evolves correctly
135do
136 local U = T.newuserdata(0, 1)
137 -- full collection makes 'U' old
138 collectgarbage()
139 assert(T.gcage(U) == "old")
140
141 -- U refers to a new table, so it becomes 'touched1'
142 debug.setuservalue(U, {x = {234}})
143 assert(T.gcage(U) == "touched1" and
144 T.gcage(debug.getuservalue(U)) == "new")
145
146 -- both U and the table survive one more collection
147 collectgarbage("step", 0)
148 assert(T.gcage(U) == "touched2" and
149 T.gcage(debug.getuservalue(U)) == "survival")
150
151 -- both U and the table survive yet another collection
152 -- now everything is old
153 collectgarbage("step", 0)
154 assert(T.gcage(U) == "old" and
155 T.gcage(debug.getuservalue(U)) == "old1")
156
157 -- data was not corrupted
158 assert(debug.getuservalue(U).x[1] == 234)
159end
160
161-- just to make sure
162assert(collectgarbage'isrunning')
163
164
165
166-- just to make sure
167assert(collectgarbage'isrunning')
168
169collectgarbage(oldmode)
170
171print('OK')
172
diff --git a/zig-lua/lua-5.4.7/testes/goto.lua b/zig-lua/lua-5.4.7/testes/goto.lua
new file mode 100644
index 0000000..4ac6d7d
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/goto.lua
@@ -0,0 +1,271 @@
1-- $Id: testes/goto.lua $
2-- See Copyright Notice in file all.lua
3
4collectgarbage()
5
6local function errmsg (code, m)
7 local st, msg = load(code)
8 assert(not st and string.find(msg, m))
9end
10
11-- cannot see label inside block
12errmsg([[ goto l1; do ::l1:: end ]], "label 'l1'")
13errmsg([[ do ::l1:: end goto l1; ]], "label 'l1'")
14
15-- repeated label
16errmsg([[ ::l1:: ::l1:: ]], "label 'l1'")
17errmsg([[ ::l1:: do ::l1:: end]], "label 'l1'")
18
19
20-- undefined label
21errmsg([[ goto l1; local aa ::l1:: ::l2:: print(3) ]], "local 'aa'")
22
23-- jumping over variable definition
24errmsg([[
25do local bb, cc; goto l1; end
26local aa
27::l1:: print(3)
28]], "local 'aa'")
29
30-- jumping into a block
31errmsg([[ do ::l1:: end goto l1 ]], "label 'l1'")
32errmsg([[ goto l1 do ::l1:: end ]], "label 'l1'")
33
34-- cannot continue a repeat-until with variables
35errmsg([[
36 repeat
37 if x then goto cont end
38 local xuxu = 10
39 ::cont::
40 until xuxu < x
41]], "local 'xuxu'")
42
43-- simple gotos
44local x
45do
46 local y = 12
47 goto l1
48 ::l2:: x = x + 1; goto l3
49 ::l1:: x = y; goto l2
50end
51::l3:: ::l3_1:: assert(x == 13)
52
53
54-- long labels
55do
56 local prog = [[
57 do
58 local a = 1
59 goto l%sa; a = a + 1
60 ::l%sa:: a = a + 10
61 goto l%sb; a = a + 2
62 ::l%sb:: a = a + 20
63 return a
64 end
65 ]]
66 local label = string.rep("0123456789", 40)
67 prog = string.format(prog, label, label, label, label)
68 assert(assert(load(prog))() == 31)
69end
70
71
72-- ok to jump over local dec. to end of block
73do
74 goto l1
75 local a = 23
76 x = a
77 ::l1::;
78end
79
80while true do
81 goto l4
82 goto l1 -- ok to jump over local dec. to end of block
83 goto l1 -- multiple uses of same label
84 local x = 45
85 ::l1:: ;;;
86end
87::l4:: assert(x == 13)
88
89if print then
90 goto l1 -- ok to jump over local dec. to end of block
91 error("should not be here")
92 goto l2 -- ok to jump over local dec. to end of block
93 local x
94 ::l1:: ; ::l2:: ;;
95else end
96
97-- to repeat a label in a different function is OK
98local function foo ()
99 local a = {}
100 goto l3
101 ::l1:: a[#a + 1] = 1; goto l2;
102 ::l2:: a[#a + 1] = 2; goto l5;
103 ::l3::
104 ::l3a:: a[#a + 1] = 3; goto l1;
105 ::l4:: a[#a + 1] = 4; goto l6;
106 ::l5:: a[#a + 1] = 5; goto l4;
107 ::l6:: assert(a[1] == 3 and a[2] == 1 and a[3] == 2 and
108 a[4] == 5 and a[5] == 4)
109 if not a[6] then a[6] = true; goto l3a end -- do it twice
110end
111
112::l6:: foo()
113
114
115do -- bug in 5.2 -> 5.3.2
116 local x
117 ::L1::
118 local y -- cannot join this SETNIL with previous one
119 assert(y == nil)
120 y = true
121 if x == nil then
122 x = 1
123 goto L1
124 else
125 x = x + 1
126 end
127 assert(x == 2 and y == true)
128end
129
130-- bug in 5.3
131do
132 local first = true
133 local a = false
134 if true then
135 goto LBL
136 ::loop::
137 a = true
138 ::LBL::
139 if first then
140 first = false
141 goto loop
142 end
143 end
144 assert(a)
145end
146
147do -- compiling infinite loops
148 goto escape -- do not run the infinite loops
149 ::a:: goto a
150 ::b:: goto c
151 ::c:: goto b
152end
153::escape::
154--------------------------------------------------------------------------------
155-- testing closing of upvalues
156
157local debug = require 'debug'
158
159local function foo ()
160 local t = {}
161 do
162 local i = 1
163 local a, b, c, d
164 t[1] = function () return a, b, c, d end
165 ::l1::
166 local b
167 do
168 local c
169 t[#t + 1] = function () return a, b, c, d end -- t[2], t[4], t[6]
170 if i > 2 then goto l2 end
171 do
172 local d
173 t[#t + 1] = function () return a, b, c, d end -- t[3], t[5]
174 i = i + 1
175 local a
176 goto l1
177 end
178 end
179 end
180 ::l2:: return t
181end
182
183local a = foo()
184assert(#a == 6)
185
186-- all functions share same 'a'
187for i = 2, 6 do
188 assert(debug.upvalueid(a[1], 1) == debug.upvalueid(a[i], 1))
189end
190
191-- 'b' and 'c' are shared among some of them
192for i = 2, 6 do
193 -- only a[1] uses external 'b'/'b'
194 assert(debug.upvalueid(a[1], 2) ~= debug.upvalueid(a[i], 2))
195 assert(debug.upvalueid(a[1], 3) ~= debug.upvalueid(a[i], 3))
196end
197
198for i = 3, 5, 2 do
199 -- inner functions share 'b'/'c' with previous ones
200 assert(debug.upvalueid(a[i], 2) == debug.upvalueid(a[i - 1], 2))
201 assert(debug.upvalueid(a[i], 3) == debug.upvalueid(a[i - 1], 3))
202 -- but not with next ones
203 assert(debug.upvalueid(a[i], 2) ~= debug.upvalueid(a[i + 1], 2))
204 assert(debug.upvalueid(a[i], 3) ~= debug.upvalueid(a[i + 1], 3))
205end
206
207-- only external 'd' is shared
208for i = 2, 6, 2 do
209 assert(debug.upvalueid(a[1], 4) == debug.upvalueid(a[i], 4))
210end
211
212-- internal 'd's are all different
213for i = 3, 5, 2 do
214 for j = 1, 6 do
215 assert((debug.upvalueid(a[i], 4) == debug.upvalueid(a[j], 4))
216 == (i == j))
217 end
218end
219
220--------------------------------------------------------------------------------
221-- testing if x goto optimizations
222
223local function testG (a)
224 if a == 1 then
225 goto l1
226 error("should never be here!")
227 elseif a == 2 then goto l2
228 elseif a == 3 then goto l3
229 elseif a == 4 then
230 goto l1 -- go to inside the block
231 error("should never be here!")
232 ::l1:: a = a + 1 -- must go to 'if' end
233 else
234 goto l4
235 ::l4a:: a = a * 2; goto l4b
236 error("should never be here!")
237 ::l4:: goto l4a
238 error("should never be here!")
239 ::l4b::
240 end
241 do return a end
242 ::l2:: do return "2" end
243 ::l3:: do return "3" end
244 ::l1:: return "1"
245end
246
247assert(testG(1) == "1")
248assert(testG(2) == "2")
249assert(testG(3) == "3")
250assert(testG(4) == 5)
251assert(testG(5) == 10)
252
253do
254 -- if x back goto out of scope of upvalue
255 local X
256 goto L1
257
258 ::L2:: goto L3
259
260 ::L1:: do
261 local a <close> = setmetatable({}, {__close = function () X = true end})
262 assert(X == nil)
263 if a then goto L2 end -- jumping back out of scope of 'a'
264 end
265
266 ::L3:: assert(X == true) -- checks that 'a' was correctly closed
267end
268--------------------------------------------------------------------------------
269
270
271print'OK'
diff --git a/zig-lua/lua-5.4.7/testes/heavy.lua b/zig-lua/lua-5.4.7/testes/heavy.lua
new file mode 100644
index 0000000..4731c74
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/heavy.lua
@@ -0,0 +1,173 @@
1-- $Id: heavy.lua,v 1.7 2017/12/29 15:42:15 roberto Exp $
2-- See Copyright Notice in file all.lua
3
4local function teststring ()
5 print("creating a string too long")
6 do
7 local a = "x"
8 local st, msg = pcall(function ()
9 while true do
10 a = a .. a.. a.. a.. a.. a.. a.. a.. a.. a
11 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
12 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
13 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
14 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
15 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
16 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
17 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
18 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
19 .. a .. a.. a.. a.. a.. a.. a.. a.. a.. a
20 print(string.format("string with %d bytes", #a))
21 end
22 end)
23 assert(not st and
24 (string.find(msg, "string length overflow") or
25 string.find(msg, "not enough memory")))
26 print("string length overflow with " .. #a * 100)
27 end
28 print('+')
29end
30
31local function loadrep (x, what)
32 local p = 1<<20
33 local s = string.rep(x, p)
34 local count = 0
35 local function f()
36 count = count + p
37 if count % (0x80*p) == 0 then
38 io.stderr:write("(", count // 2^20, " M)")
39 end
40 return s
41 end
42 local st, msg = load(f, "=big")
43 print("\nmemory: ", collectgarbage'count' * 1024)
44 msg = string.match(msg, "^[^\n]+") -- get only first line
45 print(string.format("total: 0x%x %s ('%s')", count, what, msg))
46 return st, msg
47end
48
49
50function controlstruct ()
51 print("control structure too long")
52 local lim = ((1 << 24) - 2) // 3
53 local s = string.rep("a = a + 1\n", lim)
54 s = "while true do " .. s .. "end"
55 assert(load(s))
56 print("ok with " .. lim .. " lines")
57 lim = lim + 3
58 s = string.rep("a = a + 1\n", lim)
59 s = "while true do " .. s .. "end"
60 local st, msg = load(s)
61 assert(not st and string.find(msg, "too long"))
62 print(msg)
63end
64
65
66function manylines ()
67 print("loading chunk with too many lines")
68 local st, msg = loadrep("\n", "lines")
69 assert(not st and string.find(msg, "too many lines"))
70 print('+')
71end
72
73
74function hugeid ()
75 print("loading chunk with huge identifier")
76 local st, msg = loadrep("a", "chars")
77 assert(not st and
78 (string.find(msg, "lexical element too long") or
79 string.find(msg, "not enough memory")))
80 print('+')
81end
82
83function toomanyinst ()
84 print("loading chunk with too many instructions")
85 local st, msg = loadrep("a = 10; ", "instructions")
86 print('+')
87end
88
89
90local function loadrepfunc (prefix, f)
91 local count = -1
92 local function aux ()
93 count = count + 1
94 if count == 0 then
95 return prefix
96 else
97 if count % (0x100000) == 0 then
98 io.stderr:write("(", count // 2^20, " M)")
99 end
100 return f(count)
101 end
102 end
103 local st, msg = load(aux, "k")
104 print("\nmemory: ", collectgarbage'count' * 1024)
105 msg = string.match(msg, "^[^\n]+") -- get only first line
106 print("expected error: ", msg)
107end
108
109
110function toomanyconst ()
111 print("loading function with too many constants")
112 loadrepfunc("function foo () return {0,",
113 function (n)
114 -- convert 'n' to a string in the format [["...",]],
115 -- where '...' is a kind of number in base 128
116 -- (in a range that does not include either the double quote
117 -- and the escape.)
118 return string.char(34,
119 ((n // 128^0) & 127) + 128,
120 ((n // 128^1) & 127) + 128,
121 ((n // 128^2) & 127) + 128,
122 ((n // 128^3) & 127) + 128,
123 ((n // 128^4) & 127) + 128,
124 34, 44)
125 end)
126end
127
128
129function toomanystr ()
130 local a = {}
131 local st, msg = pcall(function ()
132 for i = 1, math.huge do
133 if i % (0x100000) == 0 then
134 io.stderr:write("(", i // 2^20, " M)")
135 end
136 a[i] = string.pack("I", i)
137 end
138 end)
139 local size = #a
140 a = collectgarbage'count'
141 print("\nmemory:", a * 1024)
142 print("expected error:", msg)
143 print("size:", size)
144end
145
146
147function toomanyidx ()
148 local a = {}
149 local st, msg = pcall(function ()
150 for i = 1, math.huge do
151 if i % (0x100000) == 0 then
152 io.stderr:write("(", i // 2^20, " M)")
153 end
154 a[i] = i
155 end
156 end)
157 print("\nmemory: ", collectgarbage'count' * 1024)
158 print("expected error: ", msg)
159 print("size:", #a)
160end
161
162
163
164-- teststring()
165-- controlstruct()
166-- manylines()
167-- hugeid()
168-- toomanyinst()
169-- toomanyconst()
170-- toomanystr()
171toomanyidx()
172
173print "OK"
diff --git a/zig-lua/lua-5.4.7/testes/libs/P1/dummy b/zig-lua/lua-5.4.7/testes/libs/P1/dummy
new file mode 100644
index 0000000..b0468a0
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/P1/dummy
@@ -0,0 +1,2 @@
1# This is a dummy file just to make git keep the otherwise empty
2# directory 'P1' in the repository.
diff --git a/zig-lua/lua-5.4.7/testes/libs/lib1.c b/zig-lua/lua-5.4.7/testes/libs/lib1.c
new file mode 100644
index 0000000..56b6ef4
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/lib1.c
@@ -0,0 +1,44 @@
1#include "lua.h"
2#include "lauxlib.h"
3
4static int id (lua_State *L) {
5 return lua_gettop(L);
6}
7
8
9static const struct luaL_Reg funcs[] = {
10 {"id", id},
11 {NULL, NULL}
12};
13
14
15/* function used by lib11.c */
16LUAMOD_API int lib1_export (lua_State *L) {
17 lua_pushstring(L, "exported");
18 return 1;
19}
20
21
22LUAMOD_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
30LUAMOD_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
38LUAMOD_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/zig-lua/lua-5.4.7/testes/libs/lib11.c b/zig-lua/lua-5.4.7/testes/libs/lib11.c
new file mode 100644
index 0000000..377d0c4
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/lib11.c
@@ -0,0 +1,10 @@
1#include "lua.h"
2
3/* function from lib1.c */
4int lib1_export (lua_State *L);
5
6LUAMOD_API int luaopen_lib11 (lua_State *L) {
7 return lib1_export(L);
8}
9
10
diff --git a/zig-lua/lua-5.4.7/testes/libs/lib2.c b/zig-lua/lua-5.4.7/testes/libs/lib2.c
new file mode 100644
index 0000000..bc9651e
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/lib2.c
@@ -0,0 +1,23 @@
1#include "lua.h"
2#include "lauxlib.h"
3
4static int id (lua_State *L) {
5 return lua_gettop(L);
6}
7
8
9static const struct luaL_Reg funcs[] = {
10 {"id", id},
11 {NULL, NULL}
12};
13
14
15LUAMOD_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/zig-lua/lua-5.4.7/testes/libs/lib21.c b/zig-lua/lua-5.4.7/testes/libs/lib21.c
new file mode 100644
index 0000000..a39b683
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/lib21.c
@@ -0,0 +1,10 @@
1#include "lua.h"
2
3
4int luaopen_lib2 (lua_State *L);
5
6LUAMOD_API int luaopen_lib21 (lua_State *L) {
7 return luaopen_lib2(L);
8}
9
10
diff --git a/zig-lua/lua-5.4.7/testes/libs/lib22.c b/zig-lua/lua-5.4.7/testes/libs/lib22.c
new file mode 100644
index 0000000..8e65650
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/lib22.c
@@ -0,0 +1,25 @@
1#include "lua.h"
2#include "lauxlib.h"
3
4static int id (lua_State *L) {
5 lua_pushboolean(L, 1);
6 lua_insert(L, 1);
7 return lua_gettop(L);
8}
9
10
11static const struct luaL_Reg funcs[] = {
12 {"id", id},
13 {NULL, NULL}
14};
15
16
17LUAMOD_API int luaopen_lib2 (lua_State *L) {
18 lua_settop(L, 2);
19 lua_setglobal(L, "y"); /* y gets 2nd parameter */
20 lua_setglobal(L, "x"); /* x gets 1st parameter */
21 luaL_newlib(L, funcs);
22 return 1;
23}
24
25
diff --git a/zig-lua/lua-5.4.7/testes/libs/makefile b/zig-lua/lua-5.4.7/testes/libs/makefile
new file mode 100644
index 0000000..9c0c4e3
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/libs/makefile
@@ -0,0 +1,27 @@
1# change this variable to point to the directory with Lua headers
2# of the version being tested
3LUA_DIR = ../../
4
5CC = gcc
6
7# compilation should generate Dynamic-Link Libraries
8CFLAGS = -Wall -std=gnu99 -O2 -I$(LUA_DIR) -fPIC -shared
9
10# libraries used by the tests
11all: lib1.so lib11.so lib2.so lib21.so lib2-v2.so
12 touch all
13
14lib1.so: lib1.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/lua.h
15 $(CC) $(CFLAGS) -o lib1.so lib1.c
16
17lib11.so: lib11.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/lua.h
18 $(CC) $(CFLAGS) -o lib11.so lib11.c
19
20lib2.so: lib2.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/lua.h
21 $(CC) $(CFLAGS) -o lib2.so lib2.c
22
23lib21.so: lib21.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/lua.h
24 $(CC) $(CFLAGS) -o lib21.so lib21.c
25
26lib2-v2.so: lib21.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/lua.h
27 $(CC) $(CFLAGS) -o lib2-v2.so lib22.c
diff --git a/zig-lua/lua-5.4.7/testes/literals.lua b/zig-lua/lua-5.4.7/testes/literals.lua
new file mode 100644
index 0000000..30ab9ab
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/literals.lua
@@ -0,0 +1,343 @@
1-- $Id: testes/literals.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing scanner')
5
6local debug = require "debug"
7
8
9local function dostring (x) return assert(load(x), "")() end
10
11dostring("x \v\f = \t\r 'a\0a' \v\f\f")
12assert(x == 'a\0a' and string.len(x) == 3)
13_G.x = nil
14
15-- escape sequences
16assert('\n\"\'\\' == [[
17
18"'\]])
19
20assert(string.find("\a\b\f\n\r\t\v", "^%c%c%c%c%c%c%c$"))
21
22-- assume ASCII just for tests:
23assert("\09912" == 'c12')
24assert("\99ab" == 'cab')
25assert("\099" == '\99')
26assert("\099\n" == 'c\10')
27assert('\0\0\0alo' == '\0' .. '\0\0' .. 'alo')
28
29assert(010 .. 020 .. -030 == "1020-30")
30
31-- hexadecimal escapes
32assert("\x00\x05\x10\x1f\x3C\xfF\xe8" == "\0\5\16\31\60\255\232")
33
34local function lexstring (x, y, n)
35 local f = assert(load('return ' .. x ..
36 ', require"debug".getinfo(1).currentline', ''))
37 local s, l = f()
38 assert(s == y and l == n)
39end
40
41lexstring("'abc\\z \n efg'", "abcefg", 2)
42lexstring("'abc\\z \n\n\n'", "abc", 4)
43lexstring("'\\z \n\t\f\v\n'", "", 3)
44lexstring("[[\nalo\nalo\n\n]]", "alo\nalo\n\n", 5)
45lexstring("[[\nalo\ralo\n\n]]", "alo\nalo\n\n", 5)
46lexstring("[[\nalo\ralo\r\n]]", "alo\nalo\n", 4)
47lexstring("[[\ralo\n\ralo\r\n]]", "alo\nalo\n", 4)
48lexstring("[[alo]\n]alo]]", "alo]\n]alo", 2)
49
50assert("abc\z
51 def\z
52 ghi\z
53 " == 'abcdefghi')
54
55
56-- UTF-8 sequences
57assert("\u{0}\u{00000000}\x00\0" == string.char(0, 0, 0, 0))
58
59-- limits for 1-byte sequences
60assert("\u{0}\u{7F}" == "\x00\x7F")
61
62-- limits for 2-byte sequences
63assert("\u{80}\u{7FF}" == "\xC2\x80\xDF\xBF")
64
65-- limits for 3-byte sequences
66assert("\u{800}\u{FFFF}" == "\xE0\xA0\x80\xEF\xBF\xBF")
67
68-- limits for 4-byte sequences
69assert("\u{10000}\u{1FFFFF}" == "\xF0\x90\x80\x80\xF7\xBF\xBF\xBF")
70
71-- limits for 5-byte sequences
72assert("\u{200000}\u{3FFFFFF}" == "\xF8\x88\x80\x80\x80\xFB\xBF\xBF\xBF\xBF")
73
74-- limits for 6-byte sequences
75assert("\u{4000000}\u{7FFFFFFF}" ==
76 "\xFC\x84\x80\x80\x80\x80\xFD\xBF\xBF\xBF\xBF\xBF")
77
78
79-- Error in escape sequences
80local function lexerror (s, err)
81 local st, msg = load('return ' .. s, '')
82 if err ~= '<eof>' then err = err .. "'" end
83 assert(not st and string.find(msg, "near .-" .. err))
84end
85
86lexerror([["abc\x"]], [[\x"]])
87lexerror([["abc\x]], [[\x]])
88lexerror([["\x]], [[\x]])
89lexerror([["\x5"]], [[\x5"]])
90lexerror([["\x5]], [[\x5]])
91lexerror([["\xr"]], [[\xr]])
92lexerror([["\xr]], [[\xr]])
93lexerror([["\x.]], [[\x.]])
94lexerror([["\x8%"]], [[\x8%%]])
95lexerror([["\xAG]], [[\xAG]])
96lexerror([["\g"]], [[\g]])
97lexerror([["\g]], [[\g]])
98lexerror([["\."]], [[\%.]])
99
100lexerror([["\999"]], [[\999"]])
101lexerror([["xyz\300"]], [[\300"]])
102lexerror([[" \256"]], [[\256"]])
103
104-- errors in UTF-8 sequences
105lexerror([["abc\u{100000000}"]], [[abc\u{100000000]]) -- too large
106lexerror([["abc\u11r"]], [[abc\u1]]) -- missing '{'
107lexerror([["abc\u"]], [[abc\u"]]) -- missing '{'
108lexerror([["abc\u{11r"]], [[abc\u{11r]]) -- missing '}'
109lexerror([["abc\u{11"]], [[abc\u{11"]]) -- missing '}'
110lexerror([["abc\u{11]], [[abc\u{11]]) -- missing '}'
111lexerror([["abc\u{r"]], [[abc\u{r]]) -- no digits
112
113-- unfinished strings
114lexerror("[=[alo]]", "<eof>")
115lexerror("[=[alo]=", "<eof>")
116lexerror("[=[alo]", "<eof>")
117lexerror("'alo", "<eof>")
118lexerror("'alo \\z \n\n", "<eof>")
119lexerror("'alo \\z", "<eof>")
120lexerror([['alo \98]], "<eof>")
121
122-- valid characters in variable names
123for i = 0, 255 do
124 local s = string.char(i)
125 assert(not string.find(s, "[a-zA-Z_]") == not load(s .. "=1", ""))
126 assert(not string.find(s, "[a-zA-Z_0-9]") ==
127 not load("a" .. s .. "1 = 1", ""))
128end
129
130
131-- long variable names
132
133local var1 = string.rep('a', 15000) .. '1'
134local var2 = string.rep('a', 15000) .. '2'
135local prog = string.format([[
136 %s = 5
137 %s = %s + 1
138 return function () return %s - %s end
139]], var1, var2, var1, var1, var2)
140local f = dostring(prog)
141assert(_G[var1] == 5 and _G[var2] == 6 and f() == -1)
142_G[var1], _G[var2] = nil
143print('+')
144
145-- escapes --
146assert("\n\t" == [[
147
148 ]])
149assert([[
150
151 $debug]] == "\n $debug")
152assert([[ [ ]] ~= [[ ] ]])
153-- long strings --
154local b = "001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789"
155assert(string.len(b) == 960)
156prog = [=[
157print('+')
158
159local a1 = [["this is a 'string' with several 'quotes'"]]
160local a2 = "'quotes'"
161
162assert(string.find(a1, a2) == 34)
163print('+')
164
165a1 = [==[temp = [[an arbitrary value]]; ]==]
166assert(load(a1))()
167assert(temp == 'an arbitrary value')
168_G.temp = nil
169-- long strings --
170local b = "001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789001234567890123456789012345678901234567891234567890123456789012345678901234567890012345678901234567890123456789012345678912345678901234567890123456789012345678900123456789012345678901234567890123456789123456789012345678901234567890123456789"
171assert(string.len(b) == 960)
172print('+')
173
174local a = [[00123456789012345678901234567890123456789123456789012345678901234567890123456789
17500123456789012345678901234567890123456789123456789012345678901234567890123456789
17600123456789012345678901234567890123456789123456789012345678901234567890123456789
17700123456789012345678901234567890123456789123456789012345678901234567890123456789
17800123456789012345678901234567890123456789123456789012345678901234567890123456789
17900123456789012345678901234567890123456789123456789012345678901234567890123456789
18000123456789012345678901234567890123456789123456789012345678901234567890123456789
18100123456789012345678901234567890123456789123456789012345678901234567890123456789
18200123456789012345678901234567890123456789123456789012345678901234567890123456789
18300123456789012345678901234567890123456789123456789012345678901234567890123456789
18400123456789012345678901234567890123456789123456789012345678901234567890123456789
18500123456789012345678901234567890123456789123456789012345678901234567890123456789
18600123456789012345678901234567890123456789123456789012345678901234567890123456789
18700123456789012345678901234567890123456789123456789012345678901234567890123456789
18800123456789012345678901234567890123456789123456789012345678901234567890123456789
18900123456789012345678901234567890123456789123456789012345678901234567890123456789
19000123456789012345678901234567890123456789123456789012345678901234567890123456789
19100123456789012345678901234567890123456789123456789012345678901234567890123456789
19200123456789012345678901234567890123456789123456789012345678901234567890123456789
19300123456789012345678901234567890123456789123456789012345678901234567890123456789
19400123456789012345678901234567890123456789123456789012345678901234567890123456789
19500123456789012345678901234567890123456789123456789012345678901234567890123456789
19600123456789012345678901234567890123456789123456789012345678901234567890123456789
197]]
198assert(string.len(a) == 1863)
199assert(string.sub(a, 1, 40) == string.sub(b, 1, 40))
200x = 1
201]=]
202
203print('+')
204_G.x = nil
205dostring(prog)
206assert(x)
207_G.x = nil
208
209
210
211do -- reuse of long strings
212
213 -- get the address of a string
214 local function getadd (s) return string.format("%p", s) end
215
216 local s1 <const> = "01234567890123456789012345678901234567890123456789"
217 local s2 <const> = "01234567890123456789012345678901234567890123456789"
218 local s3 = "01234567890123456789012345678901234567890123456789"
219 local function foo() return s1 end
220 local function foo1() return s3 end
221 local function foo2()
222 return "01234567890123456789012345678901234567890123456789"
223 end
224 local a1 = getadd(s1)
225 assert(a1 == getadd(s2))
226 assert(a1 == getadd(foo()))
227 assert(a1 == getadd(foo1()))
228 assert(a1 == getadd(foo2()))
229
230 local sd = "0123456789" .. "0123456789012345678901234567890123456789"
231 assert(sd == s1 and getadd(sd) ~= a1)
232end
233
234
235-- testing line ends
236prog = [[
237local a = 1 -- a comment
238local b = 2
239
240
241x = [=[
242hi
243]=]
244y = "\
245hello\r\n\
246"
247return require"debug".getinfo(1).currentline
248]]
249
250for _, n in pairs{"\n", "\r", "\n\r", "\r\n"} do
251 local prog, nn = string.gsub(prog, "\n", n)
252 assert(dostring(prog) == nn)
253 assert(_G.x == "hi\n" and _G.y == "\nhello\r\n\n")
254end
255_G.x, _G.y = nil
256
257
258-- testing comments and strings with long brackets
259local a = [==[]=]==]
260assert(a == "]=")
261
262a = [==[[===[[=[]]=][====[]]===]===]==]
263assert(a == "[===[[=[]]=][====[]]===]===")
264
265a = [====[[===[[=[]]=][====[]]===]===]====]
266assert(a == "[===[[=[]]=][====[]]===]===")
267
268a = [=[]]]]]]]]]=]
269assert(a == "]]]]]]]]")
270
271
272--[===[
273x y z [==[ blu foo
274]==
275]
276]=]==]
277error error]=]===]
278
279-- generate all strings of four of these chars
280local x = {"=", "[", "]", "\n"}
281local len = 4
282local function gen (c, n)
283 if n==0 then coroutine.yield(c)
284 else
285 for _, a in pairs(x) do
286 gen(c..a, n-1)
287 end
288 end
289end
290
291for s in coroutine.wrap(function () gen("", len) end) do
292 assert(s == load("return [====[\n"..s.."]====]", "")())
293end
294
295
296-- testing decimal point locale
297if os.setlocale("pt_BR") or os.setlocale("ptb") then
298 assert(tonumber("3,4") == 3.4 and tonumber"3.4" == 3.4)
299 assert(tonumber(" -.4 ") == -0.4)
300 assert(tonumber(" +0x.41 ") == 0X0.41)
301 assert(not load("a = (3,4)"))
302 assert(assert(load("return 3.4"))() == 3.4)
303 assert(assert(load("return .4,3"))() == .4)
304 assert(assert(load("return 4."))() == 4.)
305 assert(assert(load("return 4.+.5"))() == 4.5)
306
307 assert(" 0x.1 " + " 0x,1" + "-0X.1\t" == 0x0.1)
308
309 assert(not tonumber"inf" and not tonumber"NAN")
310
311 assert(assert(load(string.format("return %q", 4.51)))() == 4.51)
312
313 local a,b = load("return 4.5.")
314 assert(string.find(b, "'4%.5%.'"))
315
316 assert(os.setlocale("C"))
317else
318 (Message or print)(
319 '\n >>> pt_BR locale not available: skipping decimal point tests <<<\n')
320end
321
322
323-- testing %q x line ends
324local s = "a string with \r and \n and \r\n and \n\r"
325local c = string.format("return %q", s)
326assert(assert(load(c))() == s)
327
328-- testing errors
329assert(not load"a = 'non-ending string")
330assert(not load"a = 'non-ending string\n'")
331assert(not load"a = '\\345'")
332assert(not load"a = [=x]")
333
334local function malformednum (n, exp)
335 local s, msg = load("return " .. n)
336 assert(not s and string.find(msg, exp))
337end
338
339malformednum("0xe-", "near <eof>")
340malformednum("0xep-p", "malformed number")
341malformednum("1print()", "malformed number")
342
343print('OK')
diff --git a/zig-lua/lua-5.4.7/testes/locals.lua b/zig-lua/lua-5.4.7/testes/locals.lua
new file mode 100644
index 0000000..2c48546
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/locals.lua
@@ -0,0 +1,1181 @@
1-- $Id: testes/locals.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing local variables and environments')
5
6local debug = require"debug"
7
8local tracegc = require"tracegc"
9
10
11-- bug in 5.1:
12
13local function f(x) x = nil; return x end
14assert(f(10) == nil)
15
16local function f() local x; return x end
17assert(f(10) == nil)
18
19local function f(x) x = nil; local y; return x, y end
20assert(f(10) == nil and select(2, f(20)) == nil)
21
22do
23 local i = 10
24 do local i = 100; assert(i==100) end
25 do local i = 1000; assert(i==1000) end
26 assert(i == 10)
27 if i ~= 10 then
28 local i = 20
29 else
30 local i = 30
31 assert(i == 30)
32 end
33end
34
35
36
37f = nil
38
39local f
40local x = 1
41
42a = nil
43load('local a = {}')()
44assert(a == nil)
45
46function f (a)
47 local _1, _2, _3, _4, _5
48 local _6, _7, _8, _9, _10
49 local x = 3
50 local b = a
51 local c,d = a,b
52 if (d == b) then
53 local x = 'q'
54 x = b
55 assert(x == 2)
56 else
57 assert(nil)
58 end
59 assert(x == 3)
60 local f = 10
61end
62
63local b=10
64local a; repeat local b; a,b=1,2; assert(a+1==b); until a+b==3
65
66
67assert(x == 1)
68
69f(2)
70assert(type(f) == 'function')
71
72
73local function getenv (f)
74 local a,b = debug.getupvalue(f, 1)
75 assert(a == '_ENV')
76 return b
77end
78
79-- test for global table of loaded chunks
80assert(getenv(load"a=3") == _G)
81local c = {}; local f = load("a = 3", nil, nil, c)
82assert(getenv(f) == c)
83assert(c.a == nil)
84f()
85assert(c.a == 3)
86
87-- old test for limits for special instructions
88do
89 local i = 2
90 local p = 4 -- p == 2^i
91 repeat
92 for j=-3,3 do
93 assert(load(string.format([[local a=%s;
94 a=a+%s;
95 assert(a ==2^%s)]], j, p-j, i), '')) ()
96 assert(load(string.format([[local a=%s;
97 a=a-%s;
98 assert(a==-2^%s)]], -j, p-j, i), '')) ()
99 assert(load(string.format([[local a,b=0,%s;
100 a=b-%s;
101 assert(a==-2^%s)]], -j, p-j, i), '')) ()
102 end
103 p = 2 * p; i = i + 1
104 until p <= 0
105end
106
107print'+'
108
109
110if rawget(_G, "T") then
111 -- testing clearing of dead elements from tables
112 collectgarbage("stop") -- stop GC
113 local a = {[{}] = 4, [3] = 0, alo = 1,
114 a1234567890123456789012345678901234567890 = 10}
115
116 local t = T.querytab(a)
117
118 for k,_ in pairs(a) do a[k] = undef end
119 collectgarbage() -- restore GC and collect dead fields in 'a'
120 for i=0,t-1 do
121 local k = querytab(a, i)
122 assert(k == nil or type(k) == 'number' or k == 'alo')
123 end
124
125 -- testing allocation errors during table insertions
126 local a = {}
127 local function additems ()
128 a.x = true; a.y = true; a.z = true
129 a[1] = true
130 a[2] = true
131 end
132 for i = 1, math.huge do
133 T.alloccount(i)
134 local st, msg = pcall(additems)
135 T.alloccount()
136 local count = 0
137 for k, v in pairs(a) do
138 assert(a[k] == v)
139 count = count + 1
140 end
141 if st then assert(count == 5); break end
142 end
143end
144
145
146-- testing lexical environments
147
148assert(_ENV == _G)
149
150do
151local dummy
152local _ENV = (function (...) return ... end)(_G, dummy) -- {
153
154do local _ENV = {assert=assert}; assert(true) end
155local mt = {_G = _G}
156local foo,x
157A = false -- "declare" A
158do local _ENV = mt
159 function foo (x)
160 A = x
161 do local _ENV = _G; A = 1000 end
162 return function (x) return A .. x end
163 end
164end
165assert(getenv(foo) == mt)
166x = foo('hi'); assert(mt.A == 'hi' and A == 1000)
167assert(x('*') == mt.A .. '*')
168
169do local _ENV = {assert=assert, A=10};
170 do local _ENV = {assert=assert, A=20};
171 assert(A==20);x=A
172 end
173 assert(A==10 and x==20)
174end
175assert(x==20)
176
177A = nil
178
179
180do -- constants
181 local a<const>, b, c<const> = 10, 20, 30
182 b = a + c + b -- 'b' is not constant
183 assert(a == 10 and b == 60 and c == 30)
184 local function checkro (name, code)
185 local st, msg = load(code)
186 local gab = string.format("attempt to assign to const variable '%s'", name)
187 assert(not st and string.find(msg, gab))
188 end
189 checkro("y", "local x, y <const>, z = 10, 20, 30; x = 11; y = 12")
190 checkro("x", "local x <const>, y, z <const> = 10, 20, 30; x = 11")
191 checkro("z", "local x <const>, y, z <const> = 10, 20, 30; y = 10; z = 11")
192 checkro("foo", "local foo <const> = 10; function foo() end")
193 checkro("foo", "local foo <const> = {}; function foo() end")
194
195 checkro("z", [[
196 local a, z <const>, b = 10;
197 function foo() a = 20; z = 32; end
198 ]])
199
200 checkro("var1", [[
201 local a, var1 <const> = 10;
202 function foo() a = 20; z = function () var1 = 12; end end
203 ]])
204end
205
206
207print"testing to-be-closed variables"
208
209local function stack(n) n = ((n == 0) or stack(n - 1)) end
210
211local function func2close (f, x, y)
212 local obj = setmetatable({}, {__close = f})
213 if x then
214 return x, obj, y
215 else
216 return obj
217 end
218end
219
220
221do
222 local a = {}
223 do
224 local b <close> = false -- not to be closed
225 local x <close> = setmetatable({"x"}, {__close = function (self)
226 a[#a + 1] = self[1] end})
227 local w, y <close>, z = func2close(function (self, err)
228 assert(err == nil); a[#a + 1] = "y"
229 end, 10, 20)
230 local c <close> = nil -- not to be closed
231 a[#a + 1] = "in"
232 assert(w == 10 and z == 20)
233 end
234 a[#a + 1] = "out"
235 assert(a[1] == "in" and a[2] == "y" and a[3] == "x" and a[4] == "out")
236end
237
238do
239 local X = false
240
241 local x, closescope = func2close(function (_, msg)
242 stack(10);
243 assert(msg == nil)
244 X = true
245 end, 100)
246 assert(x == 100); x = 101; -- 'x' is not read-only
247
248 -- closing functions do not corrupt returning values
249 local function foo (x)
250 local _ <close> = closescope
251 return x, X, 23
252 end
253
254 local a, b, c = foo(1.5)
255 assert(a == 1.5 and b == false and c == 23 and X == true)
256
257 X = false
258 foo = function (x)
259 local _<close> = func2close(function (_, msg)
260 -- without errors, enclosing function should be still active when
261 -- __close is called
262 assert(debug.getinfo(2).name == "foo")
263 assert(msg == nil)
264 end)
265 local _<close> = closescope
266 local y = 15
267 return y
268 end
269
270 assert(foo() == 15 and X == true)
271
272 X = false
273 foo = function ()
274 local x <close> = closescope
275 return x
276 end
277
278 assert(foo() == closescope and X == true)
279
280end
281
282
283-- testing to-be-closed x compile-time constants
284-- (there were some bugs here in Lua 5.4-rc3, due to a confusion
285-- between compile levels and stack levels of variables)
286do
287 local flag = false
288 local x = setmetatable({},
289 {__close = function() assert(flag == false); flag = true end})
290 local y <const> = nil
291 local z <const> = nil
292 do
293 local a <close> = x
294 end
295 assert(flag) -- 'x' must be closed here
296end
297
298do
299 -- similar problem, but with implicit close in for loops
300 local flag = false
301 local x = setmetatable({},
302 {__close = function () assert(flag == false); flag = true end})
303 -- return an empty iterator, nil, nil, and 'x' to be closed
304 local function a ()
305 return (function () return nil end), nil, nil, x
306 end
307 local v <const> = 1
308 local w <const> = 1
309 local x <const> = 1
310 local y <const> = 1
311 local z <const> = 1
312 for k in a() do
313 a = k
314 end -- ending the loop must close 'x'
315 assert(flag) -- 'x' must be closed here
316end
317
318
319
320do
321 -- calls cannot be tail in the scope of to-be-closed variables
322 local X, Y
323 local function foo ()
324 local _ <close> = func2close(function () Y = 10 end)
325 assert(X == true and Y == nil) -- 'X' not closed yet
326 return 1,2,3
327 end
328
329 local function bar ()
330 local _ <close> = func2close(function () X = false end)
331 X = true
332 do
333 return foo() -- not a tail call!
334 end
335 end
336
337 local a, b, c, d = bar()
338 assert(a == 1 and b == 2 and c == 3 and X == false and Y == 10 and d == nil)
339end
340
341
342do
343 -- bug in 5.4.3: previous condition (calls cannot be tail in the
344 -- scope of to-be-closed variables) must be valid for tbc variables
345 -- created by 'for' loops.
346
347 local closed = false
348
349 local function foo ()
350 return function () return true end, 0, 0,
351 func2close(function () closed = true end)
352 end
353
354 local function tail() return closed end
355
356 local function foo1 ()
357 for k in foo() do return tail() end
358 end
359
360 assert(foo1() == false)
361 assert(closed == true)
362end
363
364
365do
366 -- bug in 5.4.4: 'break' may generate wrong 'close' instruction when
367 -- leaving a loop block.
368
369 local closed = false
370
371 local o1 = setmetatable({}, {__close=function() closed = true end})
372
373 local function test()
374 for k, v in next, {}, nil, o1 do
375 local function f() return k end -- create an upvalue
376 break
377 end
378 assert(closed)
379 end
380
381 test()
382end
383
384
385do print("testing errors in __close")
386
387 -- original error is in __close
388 local function foo ()
389
390 local x <close> =
391 func2close(function (self, msg)
392 assert(string.find(msg, "@y"))
393 error("@x")
394 end)
395
396 local x1 <close> =
397 func2close(function (self, msg)
398 assert(string.find(msg, "@y"))
399 end)
400
401 local gc <close> = func2close(function () collectgarbage() end)
402
403 local y <close> =
404 func2close(function (self, msg)
405 assert(string.find(msg, "@z")) -- error in 'z'
406 error("@y")
407 end)
408
409 local z <close> =
410 func2close(function (self, msg)
411 assert(msg == nil)
412 error("@z")
413 end)
414
415 return 200
416 end
417
418 local stat, msg = pcall(foo, false)
419 assert(string.find(msg, "@x"))
420
421
422 -- original error not in __close
423 local function foo ()
424
425 local x <close> =
426 func2close(function (self, msg)
427 -- after error, 'foo' was discarded, so caller now
428 -- must be 'pcall'
429 assert(debug.getinfo(2).name == "pcall")
430 assert(string.find(msg, "@x1"))
431 end)
432
433 local x1 <close> =
434 func2close(function (self, msg)
435 assert(debug.getinfo(2).name == "pcall")
436 assert(string.find(msg, "@y"))
437 error("@x1")
438 end)
439
440 local gc <close> = func2close(function () collectgarbage() end)
441
442 local y <close> =
443 func2close(function (self, msg)
444 assert(debug.getinfo(2).name == "pcall")
445 assert(string.find(msg, "@z"))
446 error("@y")
447 end)
448
449 local first = true
450 local z <close> =
451 func2close(function (self, msg)
452 assert(debug.getinfo(2).name == "pcall")
453 -- 'z' close is called once
454 assert(first and msg == 4)
455 first = false
456 error("@z")
457 end)
458
459 error(4) -- original error
460 end
461
462 local stat, msg = pcall(foo, true)
463 assert(string.find(msg, "@x1"))
464
465 -- error leaving a block
466 local function foo (...)
467 do
468 local x1 <close> =
469 func2close(function (self, msg)
470 assert(string.find(msg, "@X"))
471 error("@Y")
472 end)
473
474 local x123 <close> =
475 func2close(function (_, msg)
476 assert(msg == nil)
477 error("@X")
478 end)
479 end
480 os.exit(false) -- should not run
481 end
482
483 local st, msg = xpcall(foo, debug.traceback)
484 assert(string.match(msg, "^[^ ]* @Y"))
485
486 -- error in toclose in vararg function
487 local function foo (...)
488 local x123 <close> = func2close(function () error("@x123") end)
489 end
490
491 local st, msg = xpcall(foo, debug.traceback)
492 assert(string.match(msg, "^[^ ]* @x123"))
493 assert(string.find(msg, "in metamethod 'close'"))
494end
495
496
497do -- errors due to non-closable values
498 local function foo ()
499 local x <close> = {}
500 os.exit(false) -- should not run
501 end
502 local stat, msg = pcall(foo)
503 assert(not stat and
504 string.find(msg, "variable 'x' got a non%-closable value"))
505
506 local function foo ()
507 local xyz <close> = setmetatable({}, {__close = print})
508 getmetatable(xyz).__close = nil -- remove metamethod
509 end
510 local stat, msg = pcall(foo)
511 assert(not stat and string.find(msg, "metamethod 'close'"))
512
513 local function foo ()
514 local a1 <close> = func2close(function (_, msg)
515 assert(string.find(msg, "number value"))
516 error(12)
517 end)
518 local a2 <close> = setmetatable({}, {__close = print})
519 local a3 <close> = func2close(function (_, msg)
520 assert(msg == nil)
521 error(123)
522 end)
523 getmetatable(a2).__close = 4 -- invalidate metamethod
524 end
525 local stat, msg = pcall(foo)
526 assert(not stat and msg == 12)
527end
528
529
530do -- tbc inside close methods
531 local track = {}
532 local function foo ()
533 local x <close> = func2close(function ()
534 local xx <close> = func2close(function (_, msg)
535 assert(msg == nil)
536 track[#track + 1] = "xx"
537 end)
538 track[#track + 1] = "x"
539 end)
540 track[#track + 1] = "foo"
541 return 20, 30, 40
542 end
543 local a, b, c, d = foo()
544 assert(a == 20 and b == 30 and c == 40 and d == nil)
545 assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx")
546
547 -- again, with errors
548 local track = {}
549 local function foo ()
550 local x0 <close> = func2close(function (_, msg)
551 assert(msg == 202)
552 track[#track + 1] = "x0"
553 end)
554 local x <close> = func2close(function ()
555 local xx <close> = func2close(function (_, msg)
556 assert(msg == 101)
557 track[#track + 1] = "xx"
558 error(202)
559 end)
560 track[#track + 1] = "x"
561 error(101)
562 end)
563 track[#track + 1] = "foo"
564 return 20, 30, 40
565 end
566 local st, msg = pcall(foo)
567 assert(not st and msg == 202)
568 assert(track[1] == "foo" and track[2] == "x" and track[3] == "xx" and
569 track[4] == "x0")
570end
571
572
573local function checktable (t1, t2)
574 assert(#t1 == #t2)
575 for i = 1, #t1 do
576 assert(t1[i] == t2[i])
577 end
578end
579
580
581do -- test for tbc variable high in the stack
582
583 -- function to force a stack overflow
584 local function overflow (n)
585 overflow(n + 1)
586 end
587
588 -- error handler will create tbc variable handling a stack overflow,
589 -- high in the stack
590 local function errorh (m)
591 assert(string.find(m, "stack overflow"))
592 local x <close> = func2close(function (o) o[1] = 10 end)
593 return x
594 end
595
596 local flag
597 local st, obj
598 -- run test in a coroutine so as not to swell the main stack
599 local co = coroutine.wrap(function ()
600 -- tbc variable down the stack
601 local y <close> = func2close(function (obj, msg)
602 assert(msg == nil)
603 obj[1] = 100
604 flag = obj
605 end)
606 tracegc.stop()
607 st, obj = xpcall(overflow, errorh, 0)
608 tracegc.start()
609 end)
610 co()
611 assert(not st and obj[1] == 10 and flag[1] == 100)
612end
613
614
615if rawget(_G, "T") then
616
617 do
618 -- bug in 5.4.3
619 -- 'lua_settop' may use a pointer to stack invalidated by 'luaF_close'
620
621 -- reduce stack size
622 collectgarbage(); collectgarbage(); collectgarbage()
623
624 -- force a stack reallocation
625 local function loop (n)
626 if n < 400 then loop(n + 1) end
627 end
628
629 -- close metamethod will reallocate the stack
630 local o = setmetatable({}, {__close = function () loop(0) end})
631
632 local script = [[toclose 2; settop 1; return 1]]
633
634 assert(T.testC(script, o) == script)
635
636 end
637
638
639 -- memory error inside closing function
640 local function foo ()
641 local y <close> = func2close(function () T.alloccount() end)
642 local x <close> = setmetatable({}, {__close = function ()
643 T.alloccount(0); local x = {} -- force a memory error
644 end})
645 error(1000) -- common error inside the function's body
646 end
647
648 stack(5) -- ensure a minimal number of CI structures
649
650 -- despite memory error, 'y' will be executed and
651 -- memory limit will be lifted
652 local _, msg = pcall(foo)
653 assert(msg == "not enough memory")
654
655 local closemsg
656 local close = func2close(function (self, msg)
657 T.alloccount()
658 closemsg = msg
659 end)
660
661 -- set a memory limit and return a closing object to remove the limit
662 local function enter (count)
663 stack(10) -- reserve some stack space
664 T.alloccount(count)
665 closemsg = nil
666 return close
667 end
668
669 local function test ()
670 local x <close> = enter(0) -- set a memory limit
671 local y = {} -- raise a memory error
672 end
673
674 local _, msg = pcall(test)
675 assert(msg == "not enough memory" and closemsg == "not enough memory")
676
677
678 -- repeat test with extra closing upvalues
679 local function test ()
680 local xxx <close> = func2close(function (self, msg)
681 assert(msg == "not enough memory");
682 error(1000) -- raise another error
683 end)
684 local xx <close> = func2close(function (self, msg)
685 assert(msg == "not enough memory");
686 end)
687 local x <close> = enter(0) -- set a memory limit
688 local y = {} -- raise a memory error
689 end
690
691 local _, msg = pcall(test)
692 assert(msg == 1000 and closemsg == "not enough memory")
693
694 do -- testing 'toclose' in C string buffer
695 collectgarbage()
696 local s = string.rep('a', 10000) -- large string
697 local m = T.totalmem()
698 collectgarbage("stop")
699 s = string.upper(s) -- allocate buffer + new string (10K each)
700 -- ensure buffer was deallocated
701 assert(T.totalmem() - m <= 11000)
702 collectgarbage("restart")
703 end
704
705 do -- now some tests for freeing buffer in case of errors
706 local lim = 10000 -- some size larger than the static buffer
707 local extra = 2000 -- some extra memory (for callinfo, etc.)
708
709 local s = string.rep("a", lim)
710
711 -- concat this table needs two buffer resizes (one for each 's')
712 local a = {s, s}
713
714 collectgarbage(); collectgarbage()
715
716 local m = T.totalmem()
717 collectgarbage("stop")
718
719 -- error in the first buffer allocation
720 T. totalmem(m + extra)
721 assert(not pcall(table.concat, a))
722 -- first buffer was not even allocated
723 assert(T.totalmem() - m <= extra)
724
725 -- error in the second buffer allocation
726 T. totalmem(m + lim + extra)
727 assert(not pcall(table.concat, a))
728 -- first buffer was released by 'toclose'
729 assert(T.totalmem() - m <= extra)
730
731 -- error in creation of final string
732 T.totalmem(m + 2 * lim + extra)
733 assert(not pcall(table.concat, a))
734 -- second buffer was released by 'toclose'
735 assert(T.totalmem() - m <= extra)
736
737 -- userdata, buffer, buffer, final string
738 T.totalmem(m + 4*lim + extra)
739 assert(#table.concat(a) == 2*lim)
740
741 T.totalmem(0) -- remove memory limit
742 collectgarbage("restart")
743
744 print'+'
745 end
746
747
748 do
749 -- '__close' vs. return hooks in C functions
750 local trace = {}
751
752 local function hook (event)
753 trace[#trace + 1] = event .. " " .. (debug.getinfo(2).name or "?")
754 end
755
756 -- create tbc variables to be used by C function
757 local x = func2close(function (_,msg)
758 trace[#trace + 1] = "x"
759 end)
760
761 local y = func2close(function (_,msg)
762 trace[#trace + 1] = "y"
763 end)
764
765 debug.sethook(hook, "r")
766 local t = {T.testC([[
767 toclose 2 # x
768 pushnum 10
769 pushint 20
770 toclose 3 # y
771 return 2
772 ]], x, y)}
773 debug.sethook()
774
775 -- hooks ran before return hook from 'testC'
776 checktable(trace,
777 {"return sethook", "y", "return ?", "x", "return ?", "return testC"})
778 -- results are correct
779 checktable(t, {10, 20})
780 end
781end
782
783
784do -- '__close' vs. return hooks in Lua functions
785 local trace = {}
786
787 local function hook (event)
788 trace[#trace + 1] = event .. " " .. debug.getinfo(2).name
789 end
790
791 local function foo (...)
792 local x <close> = func2close(function (_,msg)
793 trace[#trace + 1] = "x"
794 end)
795
796 local y <close> = func2close(function (_,msg)
797 debug.sethook(hook, "r")
798 end)
799
800 return ...
801 end
802
803 local t = {foo(10,20,30)}
804 debug.sethook()
805 checktable(t, {10, 20, 30})
806 checktable(trace,
807 {"return sethook", "return close", "x", "return close", "return foo"})
808end
809
810
811print "to-be-closed variables in coroutines"
812
813do
814 -- yielding inside closing metamethods
815
816 local trace = {}
817 local co = coroutine.wrap(function ()
818
819 trace[#trace + 1] = "nowX"
820
821 -- will be closed after 'y'
822 local x <close> = func2close(function (_, msg)
823 assert(msg == nil)
824 trace[#trace + 1] = "x1"
825 coroutine.yield("x")
826 trace[#trace + 1] = "x2"
827 end)
828
829 return pcall(function ()
830 do -- 'z' will be closed first
831 local z <close> = func2close(function (_, msg)
832 assert(msg == nil)
833 trace[#trace + 1] = "z1"
834 coroutine.yield("z")
835 trace[#trace + 1] = "z2"
836 end)
837 end
838
839 trace[#trace + 1] = "nowY"
840
841 -- will be closed after 'z'
842 local y <close> = func2close(function(_, msg)
843 assert(msg == nil)
844 trace[#trace + 1] = "y1"
845 coroutine.yield("y")
846 trace[#trace + 1] = "y2"
847 end)
848
849 return 10, 20, 30
850 end)
851 end)
852
853 assert(co() == "z")
854 assert(co() == "y")
855 assert(co() == "x")
856 checktable({co()}, {true, 10, 20, 30})
857 checktable(trace, {"nowX", "z1", "z2", "nowY", "y1", "y2", "x1", "x2"})
858
859end
860
861
862do
863 -- yielding inside closing metamethods while returning
864 -- (bug in 5.4.3)
865
866 local extrares -- result from extra yield (if any)
867
868 local function check (body, extra, ...)
869 local t = table.pack(...) -- expected returns
870 local co = coroutine.wrap(body)
871 if extra then
872 extrares = co() -- runs until first (extra) yield
873 end
874 local res = table.pack(co()) -- runs until yield inside '__close'
875 assert(res.n == 2 and res[2] == nil)
876 local res2 = table.pack(co()) -- runs until end of function
877 assert(res2.n == t.n)
878 for i = 1, #t do
879 if t[i] == "x" then
880 assert(res2[i] == res[1]) -- value that was closed
881 else
882 assert(res2[i] == t[i])
883 end
884 end
885 end
886
887 local function foo ()
888 local x <close> = func2close(coroutine.yield)
889 local extra <close> = func2close(function (self)
890 assert(self == extrares)
891 coroutine.yield(100)
892 end)
893 extrares = extra
894 return table.unpack{10, x, 30}
895 end
896 check(foo, true, 10, "x", 30)
897 assert(extrares == 100)
898
899 local function foo ()
900 local x <close> = func2close(coroutine.yield)
901 return
902 end
903 check(foo, false)
904
905 local function foo ()
906 local x <close> = func2close(coroutine.yield)
907 local y, z = 20, 30
908 return x
909 end
910 check(foo, false, "x")
911
912 local function foo ()
913 local x <close> = func2close(coroutine.yield)
914 local extra <close> = func2close(coroutine.yield)
915 return table.unpack({}, 1, 100) -- 100 nils
916 end
917 check(foo, true, table.unpack({}, 1, 100))
918
919end
920
921do
922 -- yielding inside closing metamethods after an error
923
924 local co = coroutine.wrap(function ()
925
926 local function foo (err)
927
928 local z <close> = func2close(function(_, msg)
929 assert(msg == nil or msg == err + 20)
930 coroutine.yield("z")
931 return 100, 200
932 end)
933
934 local y <close> = func2close(function(_, msg)
935 -- still gets the original error (if any)
936 assert(msg == err or (msg == nil and err == 1))
937 coroutine.yield("y")
938 if err then error(err + 20) end -- creates or changes the error
939 end)
940
941 local x <close> = func2close(function(_, msg)
942 assert(msg == err or (msg == nil and err == 1))
943 coroutine.yield("x")
944 return 100, 200
945 end)
946
947 if err == 10 then error(err) else return 10, 20 end
948 end
949
950 coroutine.yield(pcall(foo, nil)) -- no error
951 coroutine.yield(pcall(foo, 1)) -- error in __close
952 return pcall(foo, 10) -- 'foo' will raise an error
953 end)
954
955 local a, b = co() -- first foo: no error
956 assert(a == "x" and b == nil) -- yields inside 'x'; Ok
957 a, b = co()
958 assert(a == "y" and b == nil) -- yields inside 'y'; Ok
959 a, b = co()
960 assert(a == "z" and b == nil) -- yields inside 'z'; Ok
961 local a, b, c = co()
962 assert(a and b == 10 and c == 20) -- returns from 'pcall(foo, nil)'
963
964 local a, b = co() -- second foo: error in __close
965 assert(a == "x" and b == nil) -- yields inside 'x'; Ok
966 a, b = co()
967 assert(a == "y" and b == nil) -- yields inside 'y'; Ok
968 a, b = co()
969 assert(a == "z" and b == nil) -- yields inside 'z'; Ok
970 local st, msg = co() -- reports the error in 'y'
971 assert(not st and msg == 21)
972
973 local a, b = co() -- third foo: error in function body
974 assert(a == "x" and b == nil) -- yields inside 'x'; Ok
975 a, b = co()
976 assert(a == "y" and b == nil) -- yields inside 'y'; Ok
977 a, b = co()
978 assert(a == "z" and b == nil) -- yields inside 'z'; Ok
979 local st, msg = co() -- gets final error
980 assert(not st and msg == 10 + 20)
981
982end
983
984
985do
986 -- an error in a wrapped coroutine closes variables
987 local x = false
988 local y = false
989 local co = coroutine.wrap(function ()
990 local xv <close> = func2close(function () x = true end)
991 do
992 local yv <close> = func2close(function () y = true end)
993 coroutine.yield(100) -- yield doesn't close variable
994 end
995 coroutine.yield(200) -- yield doesn't close variable
996 error(23) -- error does
997 end)
998
999 local b = co()
1000 assert(b == 100 and not x and not y)
1001 b = co()
1002 assert(b == 200 and not x and y)
1003 local a, b = pcall(co)
1004 assert(not a and b == 23 and x and y)
1005end
1006
1007
1008do
1009
1010 -- error in a wrapped coroutine raising errors when closing a variable
1011 local x = 0
1012 local co = coroutine.wrap(function ()
1013 local xx <close> = func2close(function (_, msg)
1014 x = x + 1;
1015 assert(string.find(msg, "@XXX"))
1016 error("@YYY")
1017 end)
1018 local xv <close> = func2close(function () x = x + 1; error("@XXX") end)
1019 coroutine.yield(100)
1020 error(200)
1021 end)
1022 assert(co() == 100); assert(x == 0)
1023 local st, msg = pcall(co); assert(x == 2)
1024 assert(not st and string.find(msg, "@YYY")) -- should get error raised
1025
1026 local x = 0
1027 local y = 0
1028 co = coroutine.wrap(function ()
1029 local xx <close> = func2close(function (_, err)
1030 y = y + 1;
1031 assert(string.find(err, "XXX"))
1032 error("YYY")
1033 end)
1034 local xv <close> = func2close(function ()
1035 x = x + 1; error("XXX")
1036 end)
1037 coroutine.yield(100)
1038 return 200
1039 end)
1040 assert(co() == 100); assert(x == 0)
1041 local st, msg = pcall(co)
1042 assert(x == 1 and y == 1)
1043 -- should get first error raised
1044 assert(not st and string.find(msg, "%w+%.%w+:%d+: YYY"))
1045
1046end
1047
1048
1049-- a suspended coroutine should not close its variables when collected
1050local co
1051co = coroutine.wrap(function()
1052 -- should not run
1053 local x <close> = func2close(function () os.exit(false) end)
1054 co = nil
1055 coroutine.yield()
1056end)
1057co() -- start coroutine
1058assert(co == nil) -- eventually it will be collected
1059collectgarbage()
1060
1061
1062if rawget(_G, "T") then
1063 print("to-be-closed variables x coroutines in C")
1064 do
1065 local token = 0
1066 local count = 0
1067 local f = T.makeCfunc[[
1068 toclose 1
1069 toclose 2
1070 return .
1071 ]]
1072
1073 local obj = func2close(function (_, msg)
1074 count = count + 1
1075 token = coroutine.yield(count, token)
1076 end)
1077
1078 local co = coroutine.wrap(f)
1079 local ct, res = co(obj, obj, 10, 20, 30, 3) -- will return 10, 20, 30
1080 -- initial token value, after closing 2nd obj
1081 assert(ct == 1 and res == 0)
1082 -- run until yield when closing 1st obj
1083 ct, res = co(100)
1084 assert(ct == 2 and res == 100)
1085 res = {co(200)} -- run until end
1086 assert(res[1] == 10 and res[2] == 20 and res[3] == 30 and res[4] == nil)
1087 assert(token == 200)
1088 end
1089
1090 do
1091 local f = T.makeCfunc[[
1092 toclose 1
1093 return .
1094 ]]
1095
1096 local obj = func2close(function ()
1097 local temp
1098 local x <close> = func2close(function ()
1099 coroutine.yield(temp)
1100 return 1,2,3 -- to be ignored
1101 end)
1102 temp = coroutine.yield("closing obj")
1103 return 1,2,3 -- to be ignored
1104 end)
1105
1106 local co = coroutine.wrap(f)
1107 local res = co(obj, 10, 30, 1) -- will return only 30
1108 assert(res == "closing obj")
1109 res = co("closing x")
1110 assert(res == "closing x")
1111 res = {co()}
1112 assert(res[1] == 30 and res[2] == nil)
1113 end
1114
1115 do
1116 -- still cannot yield inside 'closeslot'
1117 local f = T.makeCfunc[[
1118 toclose 1
1119 closeslot 1
1120 ]]
1121 local obj = func2close(coroutine.yield)
1122 local co = coroutine.create(f)
1123 local st, msg = coroutine.resume(co, obj)
1124 assert(not st and string.find(msg, "attempt to yield across"))
1125
1126 -- nor outside a coroutine
1127 local f = T.makeCfunc[[
1128 toclose 1
1129 ]]
1130 local st, msg = pcall(f, obj)
1131 assert(not st and string.find(msg, "attempt to yield from outside"))
1132 end
1133end
1134
1135
1136
1137-- to-be-closed variables in generic for loops
1138do
1139 local numopen = 0
1140 local function open (x)
1141 numopen = numopen + 1
1142 return
1143 function () -- iteraction function
1144 x = x - 1
1145 if x > 0 then return x end
1146 end,
1147 nil, -- state
1148 nil, -- control variable
1149 func2close(function () numopen = numopen - 1 end) -- closing function
1150 end
1151
1152 local s = 0
1153 for i in open(10) do
1154 s = s + i
1155 end
1156 assert(s == 45 and numopen == 0)
1157
1158 local s = 0
1159 for i in open(10) do
1160 if i < 5 then break end
1161 s = s + i
1162 end
1163 assert(s == 35 and numopen == 0)
1164
1165 local s = 0
1166 for i in open(10) do
1167 for j in open(10) do
1168 if i + j < 5 then goto endloop end
1169 s = s + i
1170 end
1171 end
1172 ::endloop::
1173 assert(s == 375 and numopen == 0)
1174end
1175
1176print('OK')
1177
1178return 5,f
1179
1180end -- }
1181
diff --git a/zig-lua/lua-5.4.7/testes/main.lua b/zig-lua/lua-5.4.7/testes/main.lua
new file mode 100644
index 0000000..11b14b4
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/main.lua
@@ -0,0 +1,563 @@
1# testing special comment on first line
2-- $Id: testes/main.lua $
3-- See Copyright Notice in file all.lua
4
5-- most (all?) tests here assume a reasonable "Unix-like" shell
6if _port then return end
7
8-- use only "double quotes" inside shell scripts (better change to
9-- run on Windows)
10
11
12print ("testing stand-alone interpreter")
13
14assert(os.execute()) -- machine has a system command
15
16local arg = arg or ARG
17
18local prog = os.tmpname()
19local otherprog = os.tmpname()
20local out = os.tmpname()
21
22local progname
23do
24 local i = 0
25 while arg[i] do i=i-1 end
26 progname = arg[i+1]
27end
28print("progname: "..progname)
29
30
31local prepfile = function (s, mod, p)
32 mod = mod and "wb" or "w" -- mod true means binary files
33 p = p or prog -- file to write the program
34 local f = io.open(p, mod)
35 f:write(s)
36 assert(f:close())
37end
38
39local function getoutput ()
40 local f = io.open(out)
41 local t = f:read("a")
42 f:close()
43 assert(os.remove(out))
44 return t
45end
46
47local function checkprogout (s)
48 -- expected result must end with new line
49 assert(string.sub(s, -1) == "\n")
50 local t = getoutput()
51 for line in string.gmatch(s, ".-\n") do
52 assert(string.find(t, line, 1, true))
53 end
54end
55
56local function checkout (s)
57 local t = getoutput()
58 if s ~= t then print(string.format("'%s' - '%s'\n", s, t)) end
59 assert(s == t)
60 return t
61end
62
63
64local function RUN (p, ...)
65 p = string.gsub(p, "lua", '"'..progname..'"', 1)
66 local s = string.format(p, ...)
67 assert(os.execute(s))
68end
69
70
71local function NoRun (msg, p, ...)
72 p = string.gsub(p, "lua", '"'..progname..'"', 1)
73 local s = string.format(p, ...)
74 s = string.format("%s >%s 2>&1", s, out) -- send output and error to 'out'
75 assert(not os.execute(s))
76 assert(string.find(getoutput(), msg, 1, true)) -- check error message
77end
78
79RUN('lua -v')
80
81print(string.format("(temporary program file used in these tests: %s)", prog))
82
83-- running stdin as a file
84prepfile""
85RUN('lua - < %s > %s', prog, out)
86checkout("")
87
88prepfile[[
89 print(
901, a
91)
92]]
93RUN('lua - < %s > %s', prog, out)
94checkout("1\tnil\n")
95
96RUN('echo "print(10)\nprint(2)\n" | lua > %s', out)
97checkout("10\n2\n")
98
99
100-- testing BOM
101prepfile("\xEF\xBB\xBF")
102RUN('lua %s > %s', prog, out)
103checkout("")
104
105prepfile("\xEF\xBB\xBFprint(3)")
106RUN('lua %s > %s', prog, out)
107checkout("3\n")
108
109prepfile("\xEF\xBB\xBF# comment!!\nprint(3)")
110RUN('lua %s > %s', prog, out)
111checkout("3\n")
112
113-- bad BOMs
114prepfile("\xEF", true)
115NoRun("unexpected symbol", 'lua %s', prog)
116
117prepfile("\xEF\xBB", true)
118NoRun("unexpected symbol", 'lua %s', prog)
119
120prepfile("\xEFprint(3)", true)
121NoRun("unexpected symbol", 'lua %s', prog)
122
123prepfile("\xEF\xBBprint(3)", true)
124NoRun("unexpected symbol", 'lua %s', prog)
125
126
127-- test option '-'
128RUN('echo "print(arg[1])" | lua - -h > %s', out)
129checkout("-h\n")
130
131-- test environment variables used by Lua
132
133prepfile("print(package.path)")
134
135-- test LUA_PATH
136RUN('env LUA_INIT= LUA_PATH=x lua %s > %s', prog, out)
137checkout("x\n")
138
139-- test LUA_PATH_version
140RUN('env LUA_INIT= LUA_PATH_5_4=y LUA_PATH=x lua %s > %s', prog, out)
141checkout("y\n")
142
143-- test LUA_CPATH
144prepfile("print(package.cpath)")
145RUN('env LUA_INIT= LUA_CPATH=xuxu lua %s > %s', prog, out)
146checkout("xuxu\n")
147
148-- test LUA_CPATH_version
149RUN('env LUA_INIT= LUA_CPATH_5_4=yacc LUA_CPATH=x lua %s > %s', prog, out)
150checkout("yacc\n")
151
152-- test LUA_INIT (and its access to 'arg' table)
153prepfile("print(X)")
154RUN('env LUA_INIT="X=tonumber(arg[1])" lua %s 3.2 > %s', prog, out)
155checkout("3.2\n")
156
157-- test LUA_INIT_version
158prepfile("print(X)")
159RUN('env LUA_INIT_5_4="X=10" LUA_INIT="X=3" lua %s > %s', prog, out)
160checkout("10\n")
161
162-- test LUA_INIT for files
163prepfile("x = x or 10; print(x); x = x + 1")
164RUN('env LUA_INIT="@%s" lua %s > %s', prog, prog, out)
165checkout("10\n11\n")
166
167-- test errors in LUA_INIT
168NoRun('LUA_INIT:1: msg', 'env LUA_INIT="error(\'msg\')" lua')
169
170-- test option '-E'
171local defaultpath, defaultCpath
172
173do
174 prepfile("print(package.path, package.cpath)")
175 RUN('env LUA_INIT="error(10)" LUA_PATH=xxx LUA_CPATH=xxx lua -E %s > %s',
176 prog, out)
177 local output = getoutput()
178 defaultpath = string.match(output, "^(.-)\t")
179 defaultCpath = string.match(output, "\t(.-)$")
180
181 -- running with an empty environment
182 RUN('env -i lua %s > %s', prog, out)
183 local out = getoutput()
184 assert(defaultpath == string.match(output, "^(.-)\t"))
185 assert(defaultCpath == string.match(output, "\t(.-)$"))
186end
187
188-- paths did not change
189assert(not string.find(defaultpath, "xxx") and
190 string.find(defaultpath, "lua") and
191 not string.find(defaultCpath, "xxx") and
192 string.find(defaultCpath, "lua"))
193
194
195-- test replacement of ';;' to default path
196local function convert (p)
197 prepfile("print(package.path)")
198 RUN('env LUA_PATH="%s" lua %s > %s', p, prog, out)
199 local expected = getoutput()
200 expected = string.sub(expected, 1, -2) -- cut final end of line
201 if string.find(p, ";;") then
202 p = string.gsub(p, ";;", ";"..defaultpath..";")
203 p = string.gsub(p, "^;", "") -- remove ';' at the beginning
204 p = string.gsub(p, ";$", "") -- remove ';' at the end
205 end
206 assert(p == expected)
207end
208
209convert(";")
210convert(";;")
211convert("a;;b")
212convert(";;b")
213convert("a;;")
214convert("a;b;;c")
215
216
217-- test -l over multiple libraries
218prepfile("print(1); a=2; return {x=15}")
219prepfile(("print(a); print(_G['%s'].x)"):format(prog), false, otherprog)
220RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out)
221checkout("1\n2\n15\n2\n15\n")
222
223-- test explicit global names in -l
224prepfile("print(str.upper'alo alo', m.max(10, 20))")
225RUN("lua -l 'str=string' '-lm=math' -e 'print(m.sin(0))' %s > %s", prog, out)
226checkout("0.0\nALO ALO\t20\n")
227
228
229-- test module names with version sufix ("libs/lib2-v2")
230RUN("env LUA_CPATH='./libs/?.so' lua -l lib2-v2 -e 'print(lib2.id())' > %s",
231 out)
232checkout("true\n")
233
234
235-- test 'arg' table
236local a = [[
237 assert(#arg == 3 and arg[1] == 'a' and
238 arg[2] == 'b' and arg[3] == 'c')
239 assert(arg[-1] == '--' and arg[-2] == "-e " and arg[-3] == '%s')
240 assert(arg[4] == undef and arg[-4] == undef)
241 local a, b, c = ...
242 assert(... == 'a' and a == 'a' and b == 'b' and c == 'c')
243]]
244a = string.format(a, progname)
245prepfile(a)
246RUN('lua "-e " -- %s a b c', prog) -- "-e " runs an empty command
247
248-- test 'arg' availability in libraries
249prepfile"assert(arg)"
250prepfile("assert(arg)", false, otherprog)
251RUN('env LUA_PATH="?;;" lua -l%s - < %s', prog, otherprog)
252
253-- test messing up the 'arg' table
254RUN('echo "print(...)" | lua -e "arg[1] = 100" - > %s', out)
255checkout("100\n")
256NoRun("'arg' is not a table", 'echo "" | lua -e "arg = 1" -')
257
258-- test error in 'print'
259RUN('echo 10 | lua -e "print=nil" -i > /dev/null 2> %s', out)
260assert(string.find(getoutput(), "error calling 'print'"))
261
262-- test 'debug.debug'
263RUN('echo "io.stderr:write(1000)\ncont" | lua -e "require\'debug\'.debug()" 2> %s', out)
264checkout("lua_debug> 1000lua_debug> ")
265
266
267print("testing warnings")
268
269-- no warnings by default
270RUN('echo "io.stderr:write(1); warn[[XXX]]" | lua 2> %s', out)
271checkout("1")
272
273prepfile[[
274warn("@allow") -- unknown control, ignored
275warn("@off", "XXX", "@off") -- these are not control messages
276warn("@off") -- this one is
277warn("@on", "YYY", "@on") -- not control, but warn is off
278warn("@off") -- keep it off
279warn("@on") -- restart warnings
280warn("", "@on") -- again, no control, real warning
281warn("@on") -- keep it "started"
282warn("Z", "Z", "Z") -- common warning
283]]
284RUN('lua -W %s 2> %s', prog, out)
285checkout[[
286Lua warning: @offXXX@off
287Lua warning: @on
288Lua warning: ZZZ
289]]
290
291prepfile[[
292warn("@allow")
293-- create two objects to be finalized when closing state
294-- the errors in the finalizers must generate warnings
295u1 = setmetatable({}, {__gc = function () error("XYZ") end})
296u2 = setmetatable({}, {__gc = function () error("ZYX") end})
297]]
298RUN('lua -W %s 2> %s', prog, out)
299checkprogout("ZYX)\nXYZ)\n")
300
301-- bug since 5.2: finalizer called when closing a state could
302-- subvert finalization order
303prepfile[[
304-- should be called last
305print("creating 1")
306setmetatable({}, {__gc = function () print(1) end})
307
308print("creating 2")
309setmetatable({}, {__gc = function ()
310 print("2")
311 print("creating 3")
312 -- this finalizer should not be called, as object will be
313 -- created after 'lua_close' has been called
314 setmetatable({}, {__gc = function () print(3) end})
315 print(collectgarbage()) -- cannot call collector here
316 os.exit(0, true)
317end})
318]]
319RUN('lua -W %s > %s', prog, out)
320checkout[[
321creating 1
322creating 2
3232
324creating 3
325nil
3261
327]]
328
329
330-- test many arguments
331prepfile[[print(({...})[30])]]
332RUN('lua %s %s > %s', prog, string.rep(" a", 30), out)
333checkout("a\n")
334
335RUN([[lua "-eprint(1)" -ea=3 -e "print(a)" > %s]], out)
336checkout("1\n3\n")
337
338-- test iteractive mode
339prepfile[[
340(6*2-6) -- ===
341a =
34210
343print(a)
344a]]
345RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
346checkprogout("6\n10\n10\n\n")
347
348prepfile("a = [[b\nc\nd\ne]]\n=a")
349RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
350checkprogout("b\nc\nd\ne\n\n")
351
352local prompt = "alo"
353prepfile[[ --
354a = 2
355]]
356RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
357local t = getoutput()
358assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
359
360-- using the prompt default
361prepfile[[ --
362a = 2
363]]
364RUN([[lua -i < %s > %s]], prog, out)
365local t = getoutput()
366prompt = "> " -- the default
367assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
368
369
370-- non-string prompt
371prompt =
372 "local C = 0;\z
373 _PROMPT=setmetatable({},{__tostring = function () \z
374 C = C + 1; return C end})"
375prepfile[[ --
376a = 2
377]]
378RUN([[lua -e "%s" -i < %s > %s]], prompt, prog, out)
379local t = getoutput()
380assert(string.find(t, [[
3811 --
3822a = 2
3833
384]], 1, true))
385
386
387-- test for error objects
388prepfile[[
389debug = require "debug"
390m = {x=0}
391setmetatable(m, {__tostring = function(x)
392 return tostring(debug.getinfo(4).currentline + x.x)
393end})
394error(m)
395]]
396NoRun(progname .. ": 6\n", [[lua %s]], prog)
397
398prepfile("error{}")
399NoRun("error object is a table value", [[lua %s]], prog)
400
401
402-- chunk broken in many lines
403local s = [=[ --
404function f ( x )
405 local a = [[
406xuxu
407]]
408 local b = "\
409xuxu\n"
410 if x == 11 then return 1 + 12 , 2 + 20 end --[[ test multiple returns ]]
411 return x + 1
412 --\\
413end
414return( f( 100 ) )
415assert( a == b )
416do return f( 11 ) end ]=]
417s = string.gsub(s, ' ', '\n\n') -- change all spaces for newlines
418prepfile(s)
419RUN([[lua -e"_PROMPT='' _PROMPT2=''" -i < %s > %s]], prog, out)
420checkprogout("101\n13\t22\n\n")
421
422prepfile[[#comment in 1st line without \n at the end]]
423RUN('lua %s', prog)
424
425-- first-line comment with binary file
426prepfile("#comment\n" .. string.dump(load("print(3)")), true)
427RUN('lua %s > %s', prog, out)
428checkout('3\n')
429
430-- close Lua with an open file
431prepfile(string.format([[io.output(%q); io.write('alo')]], out))
432RUN('lua %s', prog)
433checkout('alo')
434
435-- bug in 5.2 beta (extra \0 after version line)
436RUN([[lua -v -e"print'hello'" > %s]], out)
437t = getoutput()
438assert(string.find(t, "PUC%-Rio\nhello"))
439
440
441-- testing os.exit
442prepfile("os.exit(nil, true)")
443RUN('lua %s', prog)
444prepfile("os.exit(0, true)")
445RUN('lua %s', prog)
446prepfile("os.exit(true, true)")
447RUN('lua %s', prog)
448prepfile("os.exit(1, true)")
449NoRun("", "lua %s", prog) -- no message
450prepfile("os.exit(false, true)")
451NoRun("", "lua %s", prog) -- no message
452
453
454-- to-be-closed variables in main chunk
455prepfile[[
456 local x <close> = setmetatable({},
457 {__close = function (self, err)
458 assert(err == nil)
459 print("Ok")
460 end})
461 local e1 <close> = setmetatable({}, {__close = function () print(120) end})
462 os.exit(true, true)
463]]
464RUN('lua %s > %s', prog, out)
465checkprogout("120\nOk\n")
466
467
468-- remove temporary files
469assert(os.remove(prog))
470assert(os.remove(otherprog))
471assert(not os.remove(out))
472
473-- invalid options
474NoRun("unrecognized option '-h'", "lua -h")
475NoRun("unrecognized option '---'", "lua ---")
476NoRun("unrecognized option '-Ex'", "lua -Ex")
477NoRun("unrecognized option '-vv'", "lua -vv")
478NoRun("unrecognized option '-iv'", "lua -iv")
479NoRun("'-e' needs argument", "lua -e")
480NoRun("syntax error", "lua -e a")
481NoRun("'-l' needs argument", "lua -l")
482
483
484if T then -- test library?
485 print("testing 'not enough memory' to create a state")
486 NoRun("not enough memory", "env MEMLIMIT=100 lua")
487
488 -- testing 'warn'
489 warn("@store")
490 warn("@123", "456", "789")
491 assert(_WARN == "@123456789"); _WARN = false
492
493 warn("zip", "", " ", "zap")
494 assert(_WARN == "zip zap"); _WARN = false
495 warn("ZIP", "", " ", "ZAP")
496 assert(_WARN == "ZIP ZAP"); _WARN = false
497 warn("@normal")
498end
499
500do
501 -- 'warn' must get at least one argument
502 local st, msg = pcall(warn)
503 assert(string.find(msg, "string expected"))
504
505 -- 'warn' does not leave unfinished warning in case of errors
506 -- (message would appear in next warning)
507 st, msg = pcall(warn, "SHOULD NOT APPEAR", {})
508 assert(string.find(msg, "string expected"))
509end
510
511print('+')
512
513print('testing Ctrl C')
514do
515 -- interrupt a script
516 local function kill (pid)
517 return os.execute(string.format('kill -INT %s 2> /dev/null', pid))
518 end
519
520 -- function to run a script in background, returning its output file
521 -- descriptor and its pid
522 local function runback (luaprg)
523 -- shell script to run 'luaprg' in background and echo its pid
524 local shellprg = string.format('%s -e "%s" & echo $!', progname, luaprg)
525 local f = io.popen(shellprg, "r") -- run shell script
526 local pid = f:read() -- get pid for Lua script
527 print("(if test fails now, it may leave a Lua script running in \z
528 background, pid " .. pid .. ")")
529 return f, pid
530 end
531
532 -- Lua script that runs protected infinite loop and then prints '42'
533 local f, pid = runback[[
534 pcall(function () print(12); while true do end end); print(42)]]
535 -- wait until script is inside 'pcall'
536 assert(f:read() == "12")
537 kill(pid) -- send INT signal to Lua script
538 -- check that 'pcall' captured the exception and script continued running
539 assert(f:read() == "42") -- expected output
540 assert(f:close())
541 print("done")
542
543 -- Lua script in a long unbreakable search
544 local f, pid = runback[[
545 print(15); string.find(string.rep('a', 100000), '.*b')]]
546 -- wait (so script can reach the loop)
547 assert(f:read() == "15")
548 assert(os.execute("sleep 1"))
549 -- must send at least two INT signals to stop this Lua script
550 local n = 100
551 for i = 0, 100 do -- keep sending signals
552 if not kill(pid) then -- until it fails
553 n = i -- number of non-failed kills
554 break
555 end
556 end
557 assert(f:close())
558 assert(n >= 2)
559 print(string.format("done (with %d kills)", n))
560
561end
562
563print("OK")
diff --git a/zig-lua/lua-5.4.7/testes/math.lua b/zig-lua/lua-5.4.7/testes/math.lua
new file mode 100644
index 0000000..0191f7d
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/math.lua
@@ -0,0 +1,1024 @@
1-- $Id: testes/math.lua $
2-- See Copyright Notice in file all.lua
3
4print("testing numbers and math lib")
5
6local minint <const> = math.mininteger
7local maxint <const> = math.maxinteger
8
9local intbits <const> = math.floor(math.log(maxint, 2) + 0.5) + 1
10assert((1 << intbits) == 0)
11
12assert(minint == 1 << (intbits - 1))
13assert(maxint == minint - 1)
14
15-- number of bits in the mantissa of a floating-point number
16local floatbits = 24
17do
18 local p = 2.0^floatbits
19 while p < p + 1.0 do
20 p = p * 2.0
21 floatbits = floatbits + 1
22 end
23end
24
25local function isNaN (x)
26 return (x ~= x)
27end
28
29assert(isNaN(0/0))
30assert(not isNaN(1/0))
31
32
33do
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))
39end
40
41assert(math.type(0) == "integer" and math.type(0.0) == "float"
42 and not math.type("10"))
43
44
45local function checkerror (msg, f, ...)
46 local s, err = pcall(f, ...)
47 assert(not s and string.find(err, msg))
48end
49
50local msgf2i = "number.* has no integer representation"
51
52-- float equality
53local 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
61end
62
63
64-- equality with types
65local function eqT (a,b)
66 return a == b and math.type(a) == math.type(b)
67end
68
69
70-- basic float notation
71assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2)
72
73do
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)
81end
82
83do
84 local x = -1
85 local mz = 0/x -- minus zero
86 local t = {[0] = 10, 20, 30, 40, 50}
87 assert(t[mz] == t[0] and t[-0] == t[0])
88end
89
90do -- 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))
109end
110
111assert(math.huge > 10e30)
112assert(-math.huge < -10e30)
113
114
115-- integer arithmetic
116assert(minint < minint + 1)
117assert(maxint - 1 < maxint)
118assert(0 - minint == minint)
119assert(minint * minint == 0)
120assert(maxint * maxint * maxint == maxint)
121
122
123-- testing floor division and conversions
124
125for _, 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
135end
136
137assert(1//0.0 == 1/0)
138assert(-1 // 0.0 == -1/0)
139assert(eqT(3.5 // 1.5, 2.0))
140assert(eqT(3.5 // -1.5, -3.0))
141
142do -- tests for different kinds of opcodes
143 local x, y
144 x = 1; assert(x // 0.0 == 1/0)
145 x = 1.0; assert(x // 0 == 1/0)
146 x = 3.5; assert(eqT(x // 1, 3.0))
147 assert(eqT(x // -1, -4.0))
148
149 x = 3.5; y = 1.5; assert(eqT(x // y, 2.0))
150 x = 3.5; y = -1.5; assert(eqT(x // y, -3.0))
151end
152
153assert(maxint // maxint == 1)
154assert(maxint // 1 == maxint)
155assert((maxint - 1) // maxint == 0)
156assert(maxint // (maxint - 1) == 1)
157assert(minint // minint == 1)
158assert(minint // minint == 1)
159assert((minint + 1) // minint == 0)
160assert(minint // (minint + 1) == 1)
161assert(minint // 1 == minint)
162
163assert(minint // -1 == -minint)
164assert(minint // -2 == 2^(intbits - 2))
165assert(maxint // -1 == -maxint)
166
167
168-- negative exponents
169do
170 assert(2^-3 == 1 / 2^3)
171 assert(eq((-3)^-3, 1 / (-3)^3))
172 for i = -3, 3 do -- variables avoid constant folding
173 for j = -3, 3 do
174 -- domain errors (0^(-n)) are not portable
175 if not _port or i ~= 0 or j > 0 then
176 assert(eq(i^j, 1 / i^(-j)))
177 end
178 end
179 end
180end
181
182-- comparison between floats and integers (border cases)
183if floatbits < intbits then
184 assert(2.0^floatbits == (1 << floatbits))
185 assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0)
186 assert(2.0^floatbits - 1.0 ~= (1 << floatbits))
187 -- float is rounded, int is not
188 assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1)
189else -- floats can express all integers with full accuracy
190 assert(maxint == maxint + 0.0)
191 assert(maxint - 1 == maxint - 1.0)
192 assert(minint + 1 == minint + 1.0)
193 assert(maxint ~= maxint - 1.0)
194end
195assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0)
196assert(minint + 0.0 == minint)
197assert(minint + 0.0 == -2.0^(intbits - 1))
198
199
200-- order between floats and integers
201assert(1 < 1.1); assert(not (1 < 0.9))
202assert(1 <= 1.1); assert(not (1 <= 0.9))
203assert(-1 < -0.9); assert(not (-1 < -1.1))
204assert(1 <= 1.1); assert(not (-1 <= -1.1))
205assert(-1 < -0.9); assert(not (-1 < -1.1))
206assert(-1 <= -0.9); assert(not (-1 <= -1.1))
207assert(minint <= minint + 0.0)
208assert(minint + 0.0 <= minint)
209assert(not (minint < minint + 0.0))
210assert(not (minint + 0.0 < minint))
211assert(maxint < minint * -1.0)
212assert(maxint <= minint * -1.0)
213
214do
215 local fmaxi1 = 2^(intbits - 1)
216 assert(maxint < fmaxi1)
217 assert(maxint <= fmaxi1)
218 assert(not (fmaxi1 <= maxint))
219 assert(minint <= -2^(intbits - 1))
220 assert(-2^(intbits - 1) <= minint)
221end
222
223if floatbits < intbits then
224 print("testing order (floats cannot represent all integers)")
225 local fmax = 2^floatbits
226 local ifmax = fmax | 0
227 assert(fmax < ifmax + 1)
228 assert(fmax - 1 < ifmax)
229 assert(-(fmax - 1) > -ifmax)
230 assert(not (fmax <= ifmax - 1))
231 assert(-fmax > -(ifmax + 1))
232 assert(not (-fmax >= -(ifmax - 1)))
233
234 assert(fmax/2 - 0.5 < ifmax//2)
235 assert(-(fmax/2 - 0.5) > -ifmax//2)
236
237 assert(maxint < 2^intbits)
238 assert(minint > -2^intbits)
239 assert(maxint <= 2^intbits)
240 assert(minint >= -2^intbits)
241else
242 print("testing order (floats can represent all integers)")
243 assert(maxint < maxint + 1.0)
244 assert(maxint < maxint + 0.5)
245 assert(maxint - 1.0 < maxint)
246 assert(maxint - 0.5 < maxint)
247 assert(not (maxint + 0.0 < maxint))
248 assert(maxint + 0.0 <= maxint)
249 assert(not (maxint < maxint + 0.0))
250 assert(maxint + 0.0 <= maxint)
251 assert(maxint <= maxint + 0.0)
252 assert(not (maxint + 1.0 <= maxint))
253 assert(not (maxint + 0.5 <= maxint))
254 assert(not (maxint <= maxint - 1.0))
255 assert(not (maxint <= maxint - 0.5))
256
257 assert(minint < minint + 1.0)
258 assert(minint < minint + 0.5)
259 assert(minint <= minint + 0.5)
260 assert(minint - 1.0 < minint)
261 assert(minint - 1.0 <= minint)
262 assert(not (minint + 0.0 < minint))
263 assert(not (minint + 0.5 < minint))
264 assert(not (minint < minint + 0.0))
265 assert(minint + 0.0 <= minint)
266 assert(minint <= minint + 0.0)
267 assert(not (minint + 1.0 <= minint))
268 assert(not (minint + 0.5 <= minint))
269 assert(not (minint <= minint - 1.0))
270end
271
272do
273 local NaN <const> = 0/0
274 assert(not (NaN < 0))
275 assert(not (NaN > minint))
276 assert(not (NaN <= -9))
277 assert(not (NaN <= maxint))
278 assert(not (NaN < maxint))
279 assert(not (minint <= NaN))
280 assert(not (minint < NaN))
281 assert(not (4 <= NaN))
282 assert(not (4 < NaN))
283end
284
285
286-- avoiding errors at compile time
287local function checkcompt (msg, code)
288 checkerror(msg, assert(load(code)))
289end
290checkcompt("divide by zero", "return 2 // 0")
291checkcompt(msgf2i, "return 2.3 >> 0")
292checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1))
293checkcompt("field 'huge'", "return math.huge << 1")
294checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1))
295checkcompt(msgf2i, "return 2.3 ~ 0.0")
296
297
298-- testing overflow errors when converting from float to integer (runtime)
299local function f2i (x) return x | x end
300checkerror(msgf2i, f2i, math.huge) -- +inf
301checkerror(msgf2i, f2i, -math.huge) -- -inf
302checkerror(msgf2i, f2i, 0/0) -- NaN
303
304if floatbits < intbits then
305 -- conversion tests when float cannot represent all integers
306 assert(maxint + 1.0 == maxint + 0.0)
307 assert(minint - 1.0 == minint + 0.0)
308 checkerror(msgf2i, f2i, maxint + 0.0)
309 assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2))
310 assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2)))
311 assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1)
312 -- maximum integer representable as a float
313 local mf = maxint - (1 << (floatbits - intbits)) + 1
314 assert(f2i(mf + 0.0) == mf) -- OK up to here
315 mf = mf + 1
316 assert(f2i(mf + 0.0) ~= mf) -- no more representable
317else
318 -- conversion tests when float can represent all integers
319 assert(maxint + 1.0 > maxint)
320 assert(minint - 1.0 < minint)
321 assert(f2i(maxint + 0.0) == maxint)
322 checkerror("no integer rep", f2i, maxint + 1.0)
323 checkerror("no integer rep", f2i, minint - 1.0)
324end
325
326-- 'minint' should be representable as a float no matter the precision
327assert(f2i(minint + 0.0) == minint)
328
329
330-- testing numeric strings
331
332assert("2" + 1 == 3)
333assert("2 " + 1 == 3)
334assert(" -2 " + 1 == -1)
335assert(" -0xa " + 1 == -9)
336
337
338-- Literal integer Overflows (new behavior in 5.3.3)
339do
340 -- no overflows
341 assert(eqT(tonumber(tostring(maxint)), maxint))
342 assert(eqT(tonumber(tostring(minint)), minint))
343
344 -- add 1 to last digit as a string (it cannot be 9...)
345 local function incd (n)
346 local s = string.format("%d", n)
347 s = string.gsub(s, "%d$", function (d)
348 assert(d ~= '9')
349 return string.char(string.byte(d) + 1)
350 end)
351 return s
352 end
353
354 -- 'tonumber' with overflow by 1
355 assert(eqT(tonumber(incd(maxint)), maxint + 1.0))
356 assert(eqT(tonumber(incd(minint)), minint - 1.0))
357
358 -- large numbers
359 assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30))
360 assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30))
361
362 -- hexa format still wraps around
363 assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0))
364
365 -- lexer in the limits
366 assert(minint == load("return " .. minint)())
367 assert(eqT(maxint, load("return " .. maxint)()))
368
369 assert(eqT(10000000000000000000000.0, 10000000000000000000000))
370 assert(eqT(-10000000000000000000000.0, -10000000000000000000000))
371end
372
373
374-- testing 'tonumber'
375
376-- 'tonumber' with numbers
377assert(tonumber(3.4) == 3.4)
378assert(eqT(tonumber(3), 3))
379assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint))
380assert(tonumber(1/0) == 1/0)
381
382-- 'tonumber' with strings
383assert(tonumber("0") == 0)
384assert(not tonumber(""))
385assert(not tonumber(" "))
386assert(not tonumber("-"))
387assert(not tonumber(" -0x "))
388assert(not tonumber{})
389assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
390 tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
391 tonumber'+1.' == 1)
392assert(not tonumber'+ 0.01' and not tonumber'+.e1' and
393 not tonumber'1e' and not tonumber'1.0e+' and
394 not tonumber'.')
395assert(tonumber('-012') == -010-2)
396assert(tonumber('-1.2e2') == - - -120)
397
398assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1)
399assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1)
400assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1)
401
402-- testing 'tonumber' with base
403assert(tonumber(' 001010 ', 2) == 10)
404assert(tonumber(' 001010 ', 10) == 001010)
405assert(tonumber(' -1010 ', 2) == -10)
406assert(tonumber('10', 36) == 36)
407assert(tonumber(' -10 ', 36) == -36)
408assert(tonumber(' +1Z ', 36) == 36 + 35)
409assert(tonumber(' -1z ', 36) == -36 + -35)
410assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15)))))))
411assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2))
412assert(tonumber('ffffFFFF', 16)+1 == (1 << 32))
413assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32))
414assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40))
415for i = 2,36 do
416 local i2 = i * i
417 local i10 = i2 * i2 * i2 * i2 * i2 -- i^10
418 assert(tonumber('\t10000000000\t', i) == i10)
419end
420
421if not _soft then
422 -- tests with very long numerals
423 assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1)
424 assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1)
425 assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1)
426 assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1)
427 assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3)
428 assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10)
429 assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14))
430 assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151))
431 assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301))
432 assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501))
433
434 assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0)
435 assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4)
436end
437
438-- testing 'tonumber' for invalid formats
439
440local function f (...)
441 if select('#', ...) == 1 then
442 return (...)
443 else
444 return "***"
445 end
446end
447
448assert(not f(tonumber('fFfa', 15)))
449assert(not f(tonumber('099', 8)))
450assert(not f(tonumber('1\0', 2)))
451assert(not f(tonumber('', 8)))
452assert(not f(tonumber(' ', 9)))
453assert(not f(tonumber(' ', 9)))
454assert(not f(tonumber('0xf', 10)))
455
456assert(not f(tonumber('inf')))
457assert(not f(tonumber(' INF ')))
458assert(not f(tonumber('Nan')))
459assert(not f(tonumber('nan')))
460
461assert(not f(tonumber(' ')))
462assert(not f(tonumber('')))
463assert(not f(tonumber('1 a')))
464assert(not f(tonumber('1 a', 2)))
465assert(not f(tonumber('1\0')))
466assert(not f(tonumber('1 \0')))
467assert(not f(tonumber('1\0 ')))
468assert(not f(tonumber('e1')))
469assert(not f(tonumber('e 1')))
470assert(not f(tonumber(' 3.4.5 ')))
471
472
473-- testing 'tonumber' for invalid hexadecimal formats
474
475assert(not tonumber('0x'))
476assert(not tonumber('x'))
477assert(not tonumber('x3'))
478assert(not tonumber('0x3.3.3')) -- two decimal points
479assert(not tonumber('00x2'))
480assert(not tonumber('0x 2'))
481assert(not tonumber('0 x2'))
482assert(not tonumber('23x'))
483assert(not tonumber('- 0xaa'))
484assert(not tonumber('-0xaaP ')) -- no exponent
485assert(not tonumber('0x0.51p'))
486assert(not tonumber('0x5p+-2'))
487
488
489-- testing hexadecimal numerals
490
491assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251)
492assert(0x0p12 == 0 and 0x.0p-3 == 0)
493assert(0xFFFFFFFF == (1 << 32) - 1)
494assert(tonumber('+0x2') == 2)
495assert(tonumber('-0xaA') == -170)
496assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1)
497
498-- possible confusion with decimal exponent
499assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13)
500
501
502-- floating hexas
503
504assert(tonumber(' 0x2.5 ') == 0x25/16)
505assert(tonumber(' -0x2.5 ') == -0x25/16)
506assert(tonumber(' +0x0.51p+8 ') == 0x51)
507assert(0x.FfffFFFF == 1 - '0x.00000001')
508assert('0xA.a' + 0 == 10 + 10/16)
509assert(0xa.aP4 == 0XAA)
510assert(0x4P-2 == 1)
511assert(0x1.1 == '0x1.' + '+0x.1')
512assert(0Xabcdef.0 == 0x.ABCDEFp+24)
513
514
515assert(1.1 == 1.+.1)
516assert(100.0 == 1E2 and .01 == 1e-2)
517assert(1111111111 - 1111111110 == 1000.00e-03)
518assert(1.1 == '1.'+'.1')
519assert(tonumber'1111111111' - tonumber'1111111110' ==
520 tonumber" +0.001e+3 \n\t")
521
522assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31)
523
524assert(0.123456 > 0.123455)
525
526assert(tonumber('+1.23E18') == 1.23*10.0^18)
527
528-- testing order operators
529assert(not(1<1) and (1<2) and not(2<1))
530assert(not('a'<'a') and ('a'<'b') and not('b'<'a'))
531assert((1<=1) and (1<=2) and not(2<=1))
532assert(('a'<='a') and ('a'<='b') and not('b'<='a'))
533assert(not(1>1) and not(1>2) and (2>1))
534assert(not('a'>'a') and not('a'>'b') and ('b'>'a'))
535assert((1>=1) and not(1>=2) and (2>=1))
536assert(('a'>='a') and not('a'>='b') and ('b'>='a'))
537assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3)
538
539-- testing mod operator
540assert(eqT(-4 % 3, 2))
541assert(eqT(4 % -3, -2))
542assert(eqT(-4.0 % 3, 2.0))
543assert(eqT(4 % -3.0, -2.0))
544assert(eqT(4 % -5, -1))
545assert(eqT(4 % -5.0, -1.0))
546assert(eqT(4 % 5, 4))
547assert(eqT(4 % 5.0, 4.0))
548assert(eqT(-4 % -5, -4))
549assert(eqT(-4 % -5.0, -4.0))
550assert(eqT(-4 % 5, 1))
551assert(eqT(-4 % 5.0, 1.0))
552assert(eqT(4.25 % 4, 0.25))
553assert(eqT(10.0 % 2, 0.0))
554assert(eqT(-10.0 % 2, 0.0))
555assert(eqT(-10.0 % -2, 0.0))
556assert(math.pi - math.pi % 1 == 3)
557assert(math.pi - math.pi % 0.001 == 3.141)
558
559do -- very small numbers
560 local i, j = 0, 20000
561 while i < j do
562 local m = (i + j) // 2
563 if 10^-m > 0 then
564 i = m + 1
565 else
566 j = m
567 end
568 end
569 -- 'i' is the smallest possible ten-exponent
570 local b = 10^-(i - (i // 10)) -- a very small number
571 assert(b > 0 and b * b == 0)
572 local delta = b / 1000
573 assert(eq((2.1 * b) % (2 * b), (0.1 * b), delta))
574 assert(eq((-2.1 * b) % (2 * b), (2 * b) - (0.1 * b), delta))
575 assert(eq((2.1 * b) % (-2 * b), (0.1 * b) - (2 * b), delta))
576 assert(eq((-2.1 * b) % (-2 * b), (-0.1 * b), delta))
577end
578
579
580-- basic consistency between integer modulo and float modulo
581for i = -10, 10 do
582 for j = -10, 10 do
583 if j ~= 0 then
584 assert((i + 0.0) % j == i % j)
585 end
586 end
587end
588
589for i = 0, 10 do
590 for j = -10, 10 do
591 if j ~= 0 then
592 assert((2^i) % j == (1 << i) % j)
593 end
594 end
595end
596
597do -- precision of module for large numbers
598 local i = 10
599 while (1 << i) > 0 do
600 assert((1 << i) % 3 == i % 2 + 1)
601 i = i + 1
602 end
603
604 i = 10
605 while 2^i < math.huge do
606 assert(2^i % 3 == i % 2 + 1)
607 i = i + 1
608 end
609end
610
611assert(eqT(minint % minint, 0))
612assert(eqT(maxint % maxint, 0))
613assert((minint + 1) % minint == minint + 1)
614assert((maxint - 1) % maxint == maxint - 1)
615assert(minint % maxint == maxint - 1)
616
617assert(minint % -1 == 0)
618assert(minint % -2 == 0)
619assert(maxint % -2 == -1)
620
621-- non-portable tests because Windows C library cannot compute
622-- fmod(1, huge) correctly
623if not _port then
624 local function anan (x) assert(isNaN(x)) end -- assert Not a Number
625 anan(0.0 % 0)
626 anan(1.3 % 0)
627 anan(math.huge % 1)
628 anan(math.huge % 1e30)
629 anan(-math.huge % 1e30)
630 anan(-math.huge % -1e30)
631 assert(1 % math.huge == 1)
632 assert(1e30 % math.huge == 1e30)
633 assert(1e30 % -math.huge == -math.huge)
634 assert(-1 % math.huge == math.huge)
635 assert(-1 % -math.huge == -1)
636end
637
638
639-- testing unsigned comparisons
640assert(math.ult(3, 4))
641assert(not math.ult(4, 4))
642assert(math.ult(-2, -1))
643assert(math.ult(2, -1))
644assert(not math.ult(-2, -2))
645assert(math.ult(maxint, minint))
646assert(not math.ult(minint, maxint))
647
648
649assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1))
650assert(eq(math.tan(math.pi/4), 1))
651assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0))
652assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and
653 eq(math.asin(1), math.pi/2))
654assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2))
655assert(math.abs(-10.43) == 10.43)
656assert(eqT(math.abs(minint), minint))
657assert(eqT(math.abs(maxint), maxint))
658assert(eqT(math.abs(-maxint), maxint))
659assert(eq(math.atan(1,0), math.pi/2))
660assert(math.fmod(10,3) == 1)
661assert(eq(math.sqrt(10)^2, 10))
662assert(eq(math.log(2, 10), math.log(2)/math.log(10)))
663assert(eq(math.log(2, 2), 1))
664assert(eq(math.log(9, 3), 2))
665assert(eq(math.exp(0), 1))
666assert(eq(math.sin(10), math.sin(10%(2*math.pi))))
667
668
669assert(tonumber(' 1.3e-2 ') == 1.3e-2)
670assert(tonumber(' -1.00000000000001 ') == -1.00000000000001)
671
672-- testing constant limits
673-- 2^23 = 8388608
674assert(8388609 + -8388609 == 0)
675assert(8388608 + -8388608 == 0)
676assert(8388607 + -8388607 == 0)
677
678
679
680do -- testing floor & ceil
681 assert(eqT(math.floor(3.4), 3))
682 assert(eqT(math.ceil(3.4), 4))
683 assert(eqT(math.floor(-3.4), -4))
684 assert(eqT(math.ceil(-3.4), -3))
685 assert(eqT(math.floor(maxint), maxint))
686 assert(eqT(math.ceil(maxint), maxint))
687 assert(eqT(math.floor(minint), minint))
688 assert(eqT(math.floor(minint + 0.0), minint))
689 assert(eqT(math.ceil(minint), minint))
690 assert(eqT(math.ceil(minint + 0.0), minint))
691 assert(math.floor(1e50) == 1e50)
692 assert(math.ceil(1e50) == 1e50)
693 assert(math.floor(-1e50) == -1e50)
694 assert(math.ceil(-1e50) == -1e50)
695 for _, p in pairs{31,32,63,64} do
696 assert(math.floor(2^p) == 2^p)
697 assert(math.floor(2^p + 0.5) == 2^p)
698 assert(math.ceil(2^p) == 2^p)
699 assert(math.ceil(2^p - 0.5) == 2^p)
700 end
701 checkerror("number expected", math.floor, {})
702 checkerror("number expected", math.ceil, print)
703 assert(eqT(math.tointeger(minint), minint))
704 assert(eqT(math.tointeger(minint .. ""), minint))
705 assert(eqT(math.tointeger(maxint), maxint))
706 assert(eqT(math.tointeger(maxint .. ""), maxint))
707 assert(eqT(math.tointeger(minint + 0.0), minint))
708 assert(not math.tointeger(0.0 - minint))
709 assert(not math.tointeger(math.pi))
710 assert(not math.tointeger(-math.pi))
711 assert(math.floor(math.huge) == math.huge)
712 assert(math.ceil(math.huge) == math.huge)
713 assert(not math.tointeger(math.huge))
714 assert(math.floor(-math.huge) == -math.huge)
715 assert(math.ceil(-math.huge) == -math.huge)
716 assert(not math.tointeger(-math.huge))
717 assert(math.tointeger("34.0") == 34)
718 assert(not math.tointeger("34.3"))
719 assert(not math.tointeger({}))
720 assert(not math.tointeger(0/0)) -- NaN
721end
722
723
724-- testing fmod for integers
725for i = -6, 6 do
726 for j = -6, 6 do
727 if j ~= 0 then
728 local mi = math.fmod(i, j)
729 local mf = math.fmod(i + 0.0, j)
730 assert(mi == mf)
731 assert(math.type(mi) == 'integer' and math.type(mf) == 'float')
732 if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then
733 assert(eqT(mi, i % j))
734 end
735 end
736 end
737end
738assert(eqT(math.fmod(minint, minint), 0))
739assert(eqT(math.fmod(maxint, maxint), 0))
740assert(eqT(math.fmod(minint + 1, minint), minint + 1))
741assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1))
742
743checkerror("zero", math.fmod, 3, 0)
744
745
746do -- testing max/min
747 checkerror("value expected", math.max)
748 checkerror("value expected", math.min)
749 assert(eqT(math.max(3), 3))
750 assert(eqT(math.max(3, 5, 9, 1), 9))
751 assert(math.max(maxint, 10e60) == 10e60)
752 assert(eqT(math.max(minint, minint + 1), minint + 1))
753 assert(eqT(math.min(3), 3))
754 assert(eqT(math.min(3, 5, 9, 1), 1))
755 assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2)
756 assert(math.min(1.9, 1.7, 1.72) == 1.7)
757 assert(math.min(-10e60, minint) == -10e60)
758 assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
759 assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
760end
761-- testing implicit conversions
762
763local a,b = '10', '20'
764assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
765assert(a == '10' and b == '20')
766
767
768do
769 print("testing -0 and NaN")
770 local mz <const> = -0.0
771 local z <const> = 0.0
772 assert(mz == z)
773 assert(1/mz < 0 and 0 < 1/z)
774 local a = {[mz] = 1}
775 assert(a[z] == 1 and a[mz] == 1)
776 a[z] = 2
777 assert(a[z] == 2 and a[mz] == 2)
778 local inf = math.huge * 2 + 1
779 local mz <const> = -1/inf
780 local z <const> = 1/inf
781 assert(mz == z)
782 assert(1/mz < 0 and 0 < 1/z)
783 local NaN <const> = inf - inf
784 assert(NaN ~= NaN)
785 assert(not (NaN < NaN))
786 assert(not (NaN <= NaN))
787 assert(not (NaN > NaN))
788 assert(not (NaN >= NaN))
789 assert(not (0 < NaN) and not (NaN < 0))
790 local NaN1 <const> = 0/0
791 assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
792 local a = {}
793 assert(not pcall(rawset, a, NaN, 1))
794 assert(a[NaN] == undef)
795 a[1] = 1
796 assert(not pcall(rawset, a, NaN, 1))
797 assert(a[NaN] == undef)
798 -- strings with same binary representation as 0.0 (might create problems
799 -- for constant manipulation in the pre-compiler)
800 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"
801 assert(a1 == a2 and a2 == a4 and a1 ~= a3)
802 assert(a3 == a5)
803end
804
805
806print("testing 'math.random'")
807
808local random, max, min = math.random, math.max, math.min
809
810local function testnear (val, ref, tol)
811 return (math.abs(val - ref) < ref * tol)
812end
813
814
815-- low-level!! For the current implementation of random in Lua,
816-- the first call after seed 1007 should return 0x7a7040a5a323c9d6
817do
818 -- all computations should work with 32-bit integers
819 local h <const> = 0x7a7040a5 -- higher half
820 local l <const> = 0xa323c9d6 -- lower half
821
822 math.randomseed(1007)
823 -- get the low 'intbits' of the 64-bit expected result
824 local res = (h << 32 | l) & ~(~0 << intbits)
825 assert(random(0) == res)
826
827 math.randomseed(1007, 0)
828 -- using higher bits to generate random floats; (the '% 2^32' converts
829 -- 32-bit integers to floats as unsigned)
830 local res
831 if floatbits <= 32 then
832 -- get all bits from the higher half
833 res = (h >> (32 - floatbits)) % 2^32
834 else
835 -- get 32 bits from the higher half and the rest from the lower half
836 res = (h % 2^32) * 2^(floatbits - 32) + ((l >> (64 - floatbits)) % 2^32)
837 end
838 local rand = random()
839 assert(eq(rand, 0x0.7a7040a5a323c9d6, 2^-floatbits))
840 assert(rand * 2^floatbits == res)
841end
842
843do
844 -- testing return of 'randomseed'
845 local x, y = math.randomseed()
846 local res = math.random(0)
847 x, y = math.randomseed(x, y) -- should repeat the state
848 assert(math.random(0) == res)
849 math.randomseed(x, y) -- again should repeat the state
850 assert(math.random(0) == res)
851 -- keep the random seed for following tests
852 print(string.format("random seeds: %d, %d", x, y))
853end
854
855do -- test random for floats
856 local randbits = math.min(floatbits, 64) -- at most 64 random bits
857 local mult = 2^randbits -- to make random float into an integral
858 local counts = {} -- counts for bits
859 for i = 1, randbits do counts[i] = 0 end
860 local up = -math.huge
861 local low = math.huge
862 local rounds = 100 * randbits -- 100 times for each bit
863 local totalrounds = 0
864 ::doagain:: -- will repeat test until we get good statistics
865 for i = 0, rounds do
866 local t = random()
867 assert(0 <= t and t < 1)
868 up = max(up, t)
869 low = min(low, t)
870 assert(t * mult % 1 == 0) -- no extra bits
871 local bit = i % randbits -- bit to be tested
872 if (t * 2^bit) % 1 >= 0.5 then -- is bit set?
873 counts[bit + 1] = counts[bit + 1] + 1 -- increment its count
874 end
875 end
876 totalrounds = totalrounds + rounds
877 if not (eq(up, 1, 0.001) and eq(low, 0, 0.001)) then
878 goto doagain
879 end
880 -- all bit counts should be near 50%
881 local expected = (totalrounds / randbits / 2)
882 for i = 1, randbits do
883 if not testnear(counts[i], expected, 0.10) then
884 goto doagain
885 end
886 end
887 print(string.format("float random range in %d calls: [%f, %f]",
888 totalrounds, low, up))
889end
890
891
892do -- test random for full integers
893 local up = 0
894 local low = 0
895 local counts = {} -- counts for bits
896 for i = 1, intbits do counts[i] = 0 end
897 local rounds = 100 * intbits -- 100 times for each bit
898 local totalrounds = 0
899 ::doagain:: -- will repeat test until we get good statistics
900 for i = 0, rounds do
901 local t = random(0)
902 up = max(up, t)
903 low = min(low, t)
904 local bit = i % intbits -- bit to be tested
905 -- increment its count if it is set
906 counts[bit + 1] = counts[bit + 1] + ((t >> bit) & 1)
907 end
908 totalrounds = totalrounds + rounds
909 local lim = maxint >> 10
910 if not (maxint - up < lim and low - minint < lim) then
911 goto doagain
912 end
913 -- all bit counts should be near 50%
914 local expected = (totalrounds / intbits / 2)
915 for i = 1, intbits do
916 if not testnear(counts[i], expected, 0.10) then
917 goto doagain
918 end
919 end
920 print(string.format(
921 "integer random range in %d calls: [minint + %.0fppm, maxint - %.0fppm]",
922 totalrounds, (minint - low) / minint * 1e6,
923 (maxint - up) / maxint * 1e6))
924end
925
926do
927 -- test distribution for a dice
928 local count = {0, 0, 0, 0, 0, 0}
929 local rep = 200
930 local totalrep = 0
931 ::doagain::
932 for i = 1, rep * 6 do
933 local r = random(6)
934 count[r] = count[r] + 1
935 end
936 totalrep = totalrep + rep
937 for i = 1, 6 do
938 if not testnear(count[i], totalrep, 0.05) then
939 goto doagain
940 end
941 end
942end
943
944do
945 local function aux (x1, x2) -- test random for small intervals
946 local mark = {}; local count = 0 -- to check that all values appeared
947 while true do
948 local t = random(x1, x2)
949 assert(x1 <= t and t <= x2)
950 if not mark[t] then -- new value
951 mark[t] = true
952 count = count + 1
953 if count == x2 - x1 + 1 then -- all values appeared; OK
954 goto ok
955 end
956 end
957 end
958 ::ok::
959 end
960
961 aux(-10,0)
962 aux(1, 6)
963 aux(1, 2)
964 aux(1, 13)
965 aux(1, 31)
966 aux(1, 32)
967 aux(1, 33)
968 aux(-10, 10)
969 aux(-10,-10) -- unit set
970 aux(minint, minint) -- unit set
971 aux(maxint, maxint) -- unit set
972 aux(minint, minint + 9)
973 aux(maxint - 3, maxint)
974end
975
976do
977 local function aux(p1, p2) -- test random for large intervals
978 local max = minint
979 local min = maxint
980 local n = 100
981 local mark = {}; local count = 0 -- to count how many different values
982 ::doagain::
983 for _ = 1, n do
984 local t = random(p1, p2)
985 if not mark[t] then -- new value
986 assert(p1 <= t and t <= p2)
987 max = math.max(max, t)
988 min = math.min(min, t)
989 mark[t] = true
990 count = count + 1
991 end
992 end
993 -- at least 80% of values are different
994 if not (count >= n * 0.8) then
995 goto doagain
996 end
997 -- min and max not too far from formal min and max
998 local diff = (p2 - p1) >> 4
999 if not (min < p1 + diff and max > p2 - diff) then
1000 goto doagain
1001 end
1002 end
1003 aux(0, maxint)
1004 aux(1, maxint)
1005 aux(3, maxint // 3)
1006 aux(minint, -1)
1007 aux(minint // 2, maxint // 2)
1008 aux(minint, maxint)
1009 aux(minint + 1, maxint)
1010 aux(minint, maxint - 1)
1011 aux(0, 1 << (intbits - 5))
1012end
1013
1014
1015assert(not pcall(random, 1, 2, 3)) -- too many arguments
1016
1017-- empty interval
1018assert(not pcall(random, minint + 1, minint))
1019assert(not pcall(random, maxint, maxint - 1))
1020assert(not pcall(random, maxint, minint))
1021
1022
1023
1024print('OK')
diff --git a/zig-lua/lua-5.4.7/testes/nextvar.lua b/zig-lua/lua-5.4.7/testes/nextvar.lua
new file mode 100644
index 0000000..02b7dea
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/nextvar.lua
@@ -0,0 +1,825 @@
1-- $Id: testes/nextvar.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing tables, next, and for')
5
6local function checkerror (msg, f, ...)
7 local s, err = pcall(f, ...)
8 assert(not s and string.find(err, msg))
9end
10
11
12local function check (t, na, nh)
13 if not T then return end
14 local a, h = T.querytab(t)
15 if a ~= na or h ~= nh then
16 print(na, nh, a, h)
17 assert(nil)
18 end
19end
20
21
22local a = {}
23
24-- make sure table has lots of space in hash part
25for i=1,100 do a[i.."+"] = true end
26for i=1,100 do a[i.."+"] = undef end
27-- fill hash part with numeric indices testing size operator
28for i=1,100 do
29 a[i] = true
30 assert(#a == i)
31end
32
33
34do -- rehash moving elements from array to hash
35 local a = {}
36 for i = 1, 100 do a[i] = i end
37 check(a, 128, 0)
38
39 for i = 5, 95 do a[i] = nil end
40 check(a, 128, 0)
41
42 a.x = 1 -- force a re-hash
43 check(a, 4, 8)
44
45 for i = 1, 4 do assert(a[i] == i) end
46 for i = 5, 95 do assert(a[i] == nil) end
47 for i = 96, 100 do assert(a[i] == i) end
48 assert(a.x == 1)
49end
50
51
52-- testing ipairs
53local x = 0
54for k,v in ipairs{10,20,30;x=12} do
55 x = x + 1
56 assert(k == x and v == x * 10)
57end
58
59for _ in ipairs{x=12, y=24} do assert(nil) end
60
61-- test for 'false' x ipair
62x = false
63local i = 0
64for k,v in ipairs{true,false,true,false} do
65 i = i + 1
66 x = not x
67 assert(x == v)
68end
69assert(i == 4)
70
71-- iterator function is always the same
72assert(type(ipairs{}) == 'function' and ipairs{} == ipairs{})
73
74
75do -- overflow (must wrap-around)
76 local f = ipairs{}
77 local k, v = f({[math.mininteger] = 10}, math.maxinteger)
78 assert(k == math.mininteger and v == 10)
79 k, v = f({[math.mininteger] = 10}, k)
80 assert(k == nil)
81end
82
83if not T then
84 (Message or print)
85 ('\n >>> testC not active: skipping tests for table sizes <<<\n')
86else --[
87-- testing table sizes
88
89
90local function mp2 (n) -- minimum power of 2 >= n
91 local mp = 2^math.ceil(math.log(n, 2))
92 assert(n == 0 or (mp/2 < n and n <= mp))
93 return mp
94end
95
96
97-- testing C library sizes
98do
99 local s = 0
100 for _ in pairs(math) do s = s + 1 end
101 check(math, 0, mp2(s))
102end
103
104
105-- testing constructor sizes
106local sizes = {0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17,
107 30, 31, 32, 33, 34, 254, 255, 256, 500, 1000}
108
109for _, sa in ipairs(sizes) do -- 'sa' is size of the array part
110 local arr = {"return {"}
111 for i = 1, sa do arr[1 + i] = "1," end -- build array part
112 for _, sh in ipairs(sizes) do -- 'sh' is size of the hash part
113 for j = 1, sh do -- build hash part
114 arr[1 + sa + j] = string.format('k%x=%d,', j, j)
115 end
116 arr[1 + sa + sh + 1] = "}"
117 local prog = table.concat(arr)
118 local f = assert(load(prog))
119 collectgarbage("stop")
120 f() -- call once to ensure stack space
121 -- make sure table is not resized after being created
122 if sa == 0 or sh == 0 then
123 T.alloccount(2); -- header + array or hash part
124 else
125 T.alloccount(3); -- header + array part + hash part
126 end
127 local t = f()
128 T.alloccount();
129 collectgarbage("restart")
130 assert(#t == sa)
131 check(t, sa, mp2(sh))
132 end
133end
134
135
136-- tests with unknown number of elements
137local a = {}
138for i=1,sizes[#sizes] do a[i] = i end -- build auxiliary table
139for k in ipairs(sizes) do
140 local t = {table.unpack(a,1,k)}
141 assert(#t == k)
142 check(t, k, 0)
143 t = {1,2,3,table.unpack(a,1,k)}
144 check(t, k+3, 0)
145 assert(#t == k + 3)
146end
147
148
149-- testing tables dynamically built
150local lim = 130
151local a = {}; a[2] = 1; check(a, 0, 1)
152a = {}; a[0] = 1; check(a, 0, 1); a[2] = 1; check(a, 0, 2)
153a = {}; a[0] = 1; a[1] = 1; check(a, 1, 1)
154a = {}
155for i = 1,lim do
156 a[i] = 1
157 assert(#a == i)
158 check(a, mp2(i), 0)
159end
160
161a = {}
162for i = 1,lim do
163 a['a'..i] = 1
164 assert(#a == 0)
165 check(a, 0, mp2(i))
166end
167
168a = {}
169for i=1,16 do a[i] = i end
170check(a, 16, 0)
171do
172 for i=1,11 do a[i] = undef end
173 for i=30,50 do a[i] = true; a[i] = undef end -- force a rehash (?)
174 check(a, 0, 8) -- 5 elements in the table
175 a[10] = 1
176 for i=30,50 do a[i] = true; a[i] = undef end -- force a rehash (?)
177 check(a, 0, 8) -- only 6 elements in the table
178 for i=1,14 do a[i] = true; a[i] = undef end
179 for i=18,50 do a[i] = true; a[i] = undef end -- force a rehash (?)
180 check(a, 0, 4) -- only 2 elements ([15] and [16])
181end
182
183-- reverse filling
184for i=1,lim do
185 local a = {}
186 for i=i,1,-1 do a[i] = i end -- fill in reverse
187 check(a, mp2(i), 0)
188end
189
190-- size tests for vararg
191lim = 35
192local function foo (n, ...)
193 local arg = {...}
194 check(arg, n, 0)
195 assert(select('#', ...) == n)
196 arg[n+1] = true
197 check(arg, mp2(n+1), 0)
198 arg.x = true
199 check(arg, mp2(n+1), 1)
200end
201local a = {}
202for i=1,lim do a[i] = true; foo(i, table.unpack(a)) end
203
204
205-- Table length with limit smaller than maximum value at array
206local a = {}
207for i = 1,64 do a[i] = true end -- make its array size 64
208for i = 1,64 do a[i] = nil end -- erase all elements
209assert(T.querytab(a) == 64) -- array part has 64 elements
210a[32] = true; a[48] = true; -- binary search will find these ones
211a[51] = true -- binary search will miss this one
212assert(#a == 48) -- this will set the limit
213assert(select(4, T.querytab(a)) == 48) -- this is the limit now
214a[50] = true -- this will set a new limit
215assert(select(4, T.querytab(a)) == 50) -- this is the limit now
216-- but the size is larger (and still inside the array part)
217assert(#a == 51)
218
219end --]
220
221
222-- test size operation on tables with nils
223assert(#{} == 0)
224assert(#{nil} == 0)
225assert(#{nil, nil} == 0)
226assert(#{nil, nil, nil} == 0)
227assert(#{nil, nil, nil, nil} == 0)
228assert(#{1, 2, 3, nil, nil} == 3)
229print'+'
230
231
232local nofind = {}
233
234a,b,c = 1,2,3
235a,b,c = nil
236
237
238-- next uses always the same iteraction function
239assert(next{} == next{})
240
241local function find (name)
242 local n,v
243 while 1 do
244 n,v = next(_G, n)
245 if not n then return nofind end
246 assert(_G[n] ~= undef)
247 if n == name then return v end
248 end
249end
250
251local function find1 (name)
252 for n,v in pairs(_G) do
253 if n==name then return v end
254 end
255 return nil -- not found
256end
257
258
259assert(print==find("print") and print == find1("print"))
260assert(_G["print"]==find("print"))
261assert(assert==find1("assert"))
262assert(nofind==find("return"))
263assert(not find1("return"))
264_G["ret" .. "urn"] = undef
265assert(nofind==find("return"))
266_G["xxx"] = 1
267assert(xxx==find("xxx"))
268
269-- invalid key to 'next'
270checkerror("invalid key", next, {10,20}, 3)
271
272-- both 'pairs' and 'ipairs' need an argument
273checkerror("bad argument", pairs)
274checkerror("bad argument", ipairs)
275
276print('+')
277
278a = {}
279for i=0,10000 do
280 if math.fmod(i,10) ~= 0 then
281 a['x'..i] = i
282 end
283end
284
285n = {n=0}
286for i,v in pairs(a) do
287 n.n = n.n+1
288 assert(i and v and a[i] == v)
289end
290assert(n.n == 9000)
291a = nil
292
293do -- clear global table
294 local a = {}
295 for n,v in pairs(_G) do a[n]=v end
296 for n,v in pairs(a) do
297 if not package.loaded[n] and type(v) ~= "function" and
298 not string.find(n, "^[%u_]") then
299 _G[n] = undef
300 end
301 collectgarbage()
302 end
303end
304
305
306--
307
308local function checknext (a)
309 local b = {}
310 do local k,v = next(a); while k do b[k] = v; k,v = next(a,k) end end
311 for k,v in pairs(b) do assert(a[k] == v) end
312 for k,v in pairs(a) do assert(b[k] == v) end
313end
314
315checknext{1,x=1,y=2,z=3}
316checknext{1,2,x=1,y=2,z=3}
317checknext{1,2,3,x=1,y=2,z=3}
318checknext{1,2,3,4,x=1,y=2,z=3}
319checknext{1,2,3,4,5,x=1,y=2,z=3}
320
321assert(#{} == 0)
322assert(#{[-1] = 2} == 0)
323for i=0,40 do
324 local a = {}
325 for j=1,i do a[j]=j end
326 assert(#a == i)
327end
328
329-- 'maxn' is now deprecated, but it is easily defined in Lua
330function table.maxn (t)
331 local max = 0
332 for k in pairs(t) do
333 max = (type(k) == 'number') and math.max(max, k) or max
334 end
335 return max
336end
337
338assert(table.maxn{} == 0)
339assert(table.maxn{["1000"] = true} == 0)
340assert(table.maxn{["1000"] = true, [24.5] = 3} == 24.5)
341assert(table.maxn{[1000] = true} == 1000)
342assert(table.maxn{[10] = true, [100*math.pi] = print} == 100*math.pi)
343
344table.maxn = nil
345
346-- int overflow
347a = {}
348for i=0,50 do a[2^i] = true end
349assert(a[#a])
350
351print('+')
352
353
354do -- testing 'next' with all kinds of keys
355 local a = {
356 [1] = 1, -- integer
357 [1.1] = 2, -- float
358 ['x'] = 3, -- short string
359 [string.rep('x', 1000)] = 4, -- long string
360 [print] = 5, -- C function
361 [checkerror] = 6, -- Lua function
362 [coroutine.running()] = 7, -- thread
363 [true] = 8, -- boolean
364 [io.stdin] = 9, -- userdata
365 [{}] = 10, -- table
366 }
367 local b = {}; for i = 1, 10 do b[i] = true end
368 for k, v in pairs(a) do
369 assert(b[v]); b[v] = undef
370 end
371 assert(next(b) == nil) -- 'b' now is empty
372end
373
374
375-- erasing values
376local t = {[{1}] = 1, [{2}] = 2, [string.rep("x ", 4)] = 3,
377 [100.3] = 4, [4] = 5}
378
379local n = 0
380for k, v in pairs( t ) do
381 n = n+1
382 assert(t[k] == v)
383 t[k] = undef
384 collectgarbage()
385 assert(t[k] == undef)
386end
387assert(n == 5)
388
389
390do
391 print("testing next x GC of deleted keys")
392 -- bug in 5.4.1
393 local co = coroutine.wrap(function (t)
394 for k, v in pairs(t) do
395 local k1 = next(t) -- all previous keys were deleted
396 assert(k == k1) -- current key is the first in the table
397 t[k] = nil
398 local expected = (type(k) == "table" and k[1] or
399 type(k) == "function" and k() or
400 string.sub(k, 1, 1))
401 assert(expected == v)
402 coroutine.yield(v)
403 end
404 end)
405 local t = {}
406 t[{1}] = 1 -- add several unanchored, collectable keys
407 t[{2}] = 2
408 t[string.rep("a", 50)] = "a" -- long string
409 t[string.rep("b", 50)] = "b"
410 t[{3}] = 3
411 t[string.rep("c", 10)] = "c" -- short string
412 t[function () return 10 end] = 10
413 local count = 7
414 while co(t) do
415 collectgarbage("collect") -- collect dead keys
416 count = count - 1
417 end
418 assert(count == 0 and next(t) == nil) -- traversed the whole table
419end
420
421
422local function test (a)
423 assert(not pcall(table.insert, a, 2, 20));
424 table.insert(a, 10); table.insert(a, 2, 20);
425 table.insert(a, 1, -1); table.insert(a, 40);
426 table.insert(a, #a+1, 50)
427 table.insert(a, 2, -2)
428 assert(a[2] ~= undef)
429 assert(a["2"] == undef)
430 assert(not pcall(table.insert, a, 0, 20));
431 assert(not pcall(table.insert, a, #a + 2, 20));
432 assert(table.remove(a,1) == -1)
433 assert(table.remove(a,1) == -2)
434 assert(table.remove(a,1) == 10)
435 assert(table.remove(a,1) == 20)
436 assert(table.remove(a,1) == 40)
437 assert(table.remove(a,1) == 50)
438 assert(table.remove(a,1) == nil)
439 assert(table.remove(a) == nil)
440 assert(table.remove(a, #a) == nil)
441end
442
443a = {n=0, [-7] = "ban"}
444test(a)
445assert(a.n == 0 and a[-7] == "ban")
446
447a = {[-7] = "ban"};
448test(a)
449assert(a.n == nil and #a == 0 and a[-7] == "ban")
450
451a = {[-1] = "ban"}
452test(a)
453assert(#a == 0 and table.remove(a) == nil and a[-1] == "ban")
454
455a = {[0] = "ban"}
456assert(#a == 0 and table.remove(a) == "ban" and a[0] == undef)
457
458table.insert(a, 1, 10); table.insert(a, 1, 20); table.insert(a, 1, -1)
459assert(table.remove(a) == 10)
460assert(table.remove(a) == 20)
461assert(table.remove(a) == -1)
462assert(table.remove(a) == nil)
463
464a = {'c', 'd'}
465table.insert(a, 3, 'a')
466table.insert(a, 'b')
467assert(table.remove(a, 1) == 'c')
468assert(table.remove(a, 1) == 'd')
469assert(table.remove(a, 1) == 'a')
470assert(table.remove(a, 1) == 'b')
471assert(table.remove(a, 1) == nil)
472assert(#a == 0 and a.n == nil)
473
474a = {10,20,30,40}
475assert(table.remove(a, #a + 1) == nil)
476assert(not pcall(table.remove, a, 0))
477assert(a[#a] == 40)
478assert(table.remove(a, #a) == 40)
479assert(a[#a] == 30)
480assert(table.remove(a, 2) == 20)
481assert(a[#a] == 30 and #a == 2)
482
483do -- testing table library with metamethods
484 local function test (proxy, t)
485 for i = 1, 10 do
486 table.insert(proxy, 1, i)
487 end
488 assert(#proxy == 10 and #t == 10 and proxy[1] ~= undef)
489 for i = 1, 10 do
490 assert(t[i] == 11 - i)
491 end
492 table.sort(proxy)
493 for i = 1, 10 do
494 assert(t[i] == i and proxy[i] == i)
495 end
496 assert(table.concat(proxy, ",") == "1,2,3,4,5,6,7,8,9,10")
497 for i = 1, 8 do
498 assert(table.remove(proxy, 1) == i)
499 end
500 assert(#proxy == 2 and #t == 2)
501 local a, b, c = table.unpack(proxy)
502 assert(a == 9 and b == 10 and c == nil)
503 end
504
505 -- all virtual
506 local t = {}
507 local proxy = setmetatable({}, {
508 __len = function () return #t end,
509 __index = t,
510 __newindex = t,
511 })
512 test(proxy, t)
513
514 -- only __newindex
515 local count = 0
516 t = setmetatable({}, {
517 __newindex = function (t,k,v) count = count + 1; rawset(t,k,v) end})
518 test(t, t)
519 assert(count == 10) -- after first 10, all other sets are not new
520
521 -- no __newindex
522 t = setmetatable({}, {
523 __index = function (_,k) return k + 1 end,
524 __len = function (_) return 5 end})
525 assert(table.concat(t, ";") == "2;3;4;5;6")
526
527end
528
529
530do -- testing overflow in table.insert (must wrap-around)
531
532 local t = setmetatable({},
533 {__len = function () return math.maxinteger end})
534 table.insert(t, 20)
535 local k, v = next(t)
536 assert(k == math.mininteger and v == 20)
537end
538
539if not T then
540 (Message or print)
541 ('\n >>> testC not active: skipping tests for table library on non-tables <<<\n')
542else --[
543 local debug = require'debug'
544 local tab = {10, 20, 30}
545 local mt = {}
546 local u = T.newuserdata(0)
547 checkerror("table expected", table.insert, u, 40)
548 checkerror("table expected", table.remove, u)
549 debug.setmetatable(u, mt)
550 checkerror("table expected", table.insert, u, 40)
551 checkerror("table expected", table.remove, u)
552 mt.__index = tab
553 checkerror("table expected", table.insert, u, 40)
554 checkerror("table expected", table.remove, u)
555 mt.__newindex = tab
556 checkerror("table expected", table.insert, u, 40)
557 checkerror("table expected", table.remove, u)
558 mt.__len = function () return #tab end
559 table.insert(u, 40)
560 assert(#u == 4 and #tab == 4 and u[4] == 40 and tab[4] == 40)
561 assert(table.remove(u) == 40)
562 table.insert(u, 1, 50)
563 assert(#u == 4 and #tab == 4 and u[4] == 30 and tab[1] == 50)
564
565 mt.__newindex = nil
566 mt.__len = nil
567 local tab2 = {}
568 local u2 = T.newuserdata(0)
569 debug.setmetatable(u2, {__newindex = function (_, k, v) tab2[k] = v end})
570 table.move(u, 1, 4, 1, u2)
571 assert(#tab2 == 4 and tab2[1] == tab[1] and tab2[4] == tab[4])
572
573end -- ]
574
575print('+')
576
577a = {}
578for i=1,1000 do
579 a[i] = i; a[i - 1] = undef
580end
581assert(next(a,nil) == 1000 and next(a,1000) == nil)
582
583assert(next({}) == nil)
584assert(next({}, nil) == nil)
585
586for a,b in pairs{} do error"not here" end
587for i=1,0 do error'not here' end
588for i=0,1,-1 do error'not here' end
589a = nil; for i=1,1 do assert(not a); a=1 end; assert(a)
590a = nil; for i=1,1,-1 do assert(not a); a=1 end; assert(a)
591
592do
593 print("testing floats in numeric for")
594 local a
595 -- integer count
596 a = 0; for i=1, 1, 1 do a=a+1 end; assert(a==1)
597 a = 0; for i=10000, 1e4, -1 do a=a+1 end; assert(a==1)
598 a = 0; for i=1, 0.99999, 1 do a=a+1 end; assert(a==0)
599 a = 0; for i=9999, 1e4, -1 do a=a+1 end; assert(a==0)
600 a = 0; for i=1, 0.99999, -1 do a=a+1 end; assert(a==1)
601
602 -- float count
603 a = 0; for i=0, 0.999999999, 0.1 do a=a+1 end; assert(a==10)
604 a = 0; for i=1.0, 1, 1 do a=a+1 end; assert(a==1)
605 a = 0; for i=-1.5, -1.5, 1 do a=a+1 end; assert(a==1)
606 a = 0; for i=1e6, 1e6, -1 do a=a+1 end; assert(a==1)
607 a = 0; for i=1.0, 0.99999, 1 do a=a+1 end; assert(a==0)
608 a = 0; for i=99999, 1e5, -1.0 do a=a+1 end; assert(a==0)
609 a = 0; for i=1.0, 0.99999, -1 do a=a+1 end; assert(a==1)
610end
611
612do -- changing the control variable
613 local a
614 a = 0; for i = 1, 10 do a = a + 1; i = "x" end; assert(a == 10)
615 a = 0; for i = 10.0, 1, -1 do a = a + 1; i = "x" end; assert(a == 10)
616end
617
618-- conversion
619a = 0; for i="10","1","-2" do a=a+1 end; assert(a==5)
620
621do -- checking types
622 local c
623 local function checkfloat (i)
624 assert(math.type(i) == "float")
625 c = c + 1
626 end
627
628 c = 0; for i = 1.0, 10 do checkfloat(i) end
629 assert(c == 10)
630
631 c = 0; for i = -1, -10, -1.0 do checkfloat(i) end
632 assert(c == 10)
633
634 local function checkint (i)
635 assert(math.type(i) == "integer")
636 c = c + 1
637 end
638
639 local m = math.maxinteger
640 c = 0; for i = m, m - 10, -1 do checkint(i) end
641 assert(c == 11)
642
643 c = 0; for i = 1, 10.9 do checkint(i) end
644 assert(c == 10)
645
646 c = 0; for i = 10, 0.001, -1 do checkint(i) end
647 assert(c == 10)
648
649 c = 0; for i = 1, "10.8" do checkint(i) end
650 assert(c == 10)
651
652 c = 0; for i = 9, "3.4", -1 do checkint(i) end
653 assert(c == 6)
654
655 c = 0; for i = 0, " -3.4 ", -1 do checkint(i) end
656 assert(c == 4)
657
658 c = 0; for i = 100, "96.3", -2 do checkint(i) end
659 assert(c == 2)
660
661 c = 0; for i = 1, math.huge do if i > 10 then break end; checkint(i) end
662 assert(c == 10)
663
664 c = 0; for i = -1, -math.huge, -1 do
665 if i < -10 then break end; checkint(i)
666 end
667 assert(c == 10)
668
669
670 for i = math.mininteger, -10e100 do assert(false) end
671 for i = math.maxinteger, 10e100, -1 do assert(false) end
672
673end
674
675
676do -- testing other strange cases for numeric 'for'
677
678 local function checkfor (from, to, step, t)
679 local c = 0
680 for i = from, to, step do
681 c = c + 1
682 assert(i == t[c])
683 end
684 assert(c == #t)
685 end
686
687 local maxi = math.maxinteger
688 local mini = math.mininteger
689
690 checkfor(mini, maxi, maxi, {mini, -1, maxi - 1})
691
692 checkfor(mini, math.huge, maxi, {mini, -1, maxi - 1})
693
694 checkfor(maxi, mini, mini, {maxi, -1})
695
696 checkfor(maxi, mini, -maxi, {maxi, 0, -maxi})
697
698 checkfor(maxi, -math.huge, mini, {maxi, -1})
699
700 checkfor(maxi, mini, 1, {})
701 checkfor(mini, maxi, -1, {})
702
703 checkfor(maxi - 6, maxi, 3, {maxi - 6, maxi - 3, maxi})
704 checkfor(mini + 4, mini, -2, {mini + 4, mini + 2, mini})
705
706 local step = maxi // 10
707 local c = mini
708 for i = mini, maxi, step do
709 assert(i == c)
710 c = c + step
711 end
712
713 c = maxi
714 for i = maxi, mini, -step do
715 assert(i == c)
716 c = c - step
717 end
718
719 checkfor(maxi, maxi, maxi, {maxi})
720 checkfor(maxi, maxi, mini, {maxi})
721 checkfor(mini, mini, maxi, {mini})
722 checkfor(mini, mini, mini, {mini})
723end
724
725
726checkerror("'for' step is zero", function ()
727 for i = 1, 10, 0 do end
728end)
729
730checkerror("'for' step is zero", function ()
731 for i = 1, -10, 0 do end
732end)
733
734checkerror("'for' step is zero", function ()
735 for i = 1.0, -10, 0.0 do end
736end)
737
738collectgarbage()
739
740
741-- testing generic 'for'
742
743local function f (n, p)
744 local t = {}; for i=1,p do t[i] = i*10 end
745 return function (_, n, ...)
746 assert(select("#", ...) == 0) -- no extra arguments
747 if n > 0 then
748 n = n-1
749 return n, table.unpack(t)
750 end
751 end, nil, n
752end
753
754local x = 0
755for n,a,b,c,d in f(5,3) do
756 x = x+1
757 assert(a == 10 and b == 20 and c == 30 and d == nil)
758end
759assert(x == 5)
760
761
762
763-- testing __pairs and __ipairs metamethod
764a = {}
765do
766 local x,y,z = pairs(a)
767 assert(type(x) == 'function' and y == a and z == nil)
768end
769
770local function foo (e,i)
771 assert(e == a)
772 if i <= 10 then return i+1, i+2 end
773end
774
775local function foo1 (e,i)
776 i = i + 1
777 assert(e == a)
778 if i <= e.n then return i,a[i] end
779end
780
781setmetatable(a, {__pairs = function (x) return foo, x, 0 end})
782
783local i = 0
784for k,v in pairs(a) do
785 i = i + 1
786 assert(k == i and v == k+1)
787end
788
789a.n = 5
790a[3] = 30
791
792-- testing ipairs with metamethods
793a = {n=10}
794setmetatable(a, { __index = function (t,k)
795 if k <= t.n then return k * 10 end
796 end})
797i = 0
798for k,v in ipairs(a) do
799 i = i + 1
800 assert(k == i and v == i * 10)
801end
802assert(i == a.n)
803
804
805-- testing yield inside __pairs
806do
807 local t = setmetatable({10, 20, 30}, {__pairs = function (t)
808 local inc = coroutine.yield()
809 return function (t, i)
810 if i > 1 then return i - inc, t[i - inc] else return nil end
811 end, t, #t + 1
812 end})
813
814 local res = {}
815 local co = coroutine.wrap(function ()
816 for i,p in pairs(t) do res[#res + 1] = p end
817 end)
818
819 co() -- start coroutine
820 co(1) -- continue after yield
821 assert(res[1] == 30 and res[2] == 20 and res[3] == 10 and #res == 3)
822
823end
824
825print"OK"
diff --git a/zig-lua/lua-5.4.7/testes/packtests b/zig-lua/lua-5.4.7/testes/packtests
new file mode 100755
index 0000000..0dbb92f
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/packtests
@@ -0,0 +1,55 @@
1NAME=$1"-tests"
2
3ln -s . $NAME
4ln -s .. ltests
5
6tar --create --gzip --no-recursion --file=$NAME.tar.gz \
7$NAME/all.lua \
8$NAME/api.lua \
9$NAME/attrib.lua \
10$NAME/big.lua \
11$NAME/bitwise.lua \
12$NAME/bwcoercion.lua \
13$NAME/calls.lua \
14$NAME/closure.lua \
15$NAME/code.lua \
16$NAME/constructs.lua \
17$NAME/coroutine.lua \
18$NAME/cstack.lua \
19$NAME/db.lua \
20$NAME/errors.lua \
21$NAME/events.lua \
22$NAME/files.lua \
23$NAME/gc.lua \
24$NAME/gengc.lua \
25$NAME/goto.lua \
26$NAME/heavy.lua \
27$NAME/literals.lua \
28$NAME/locals.lua \
29$NAME/main.lua \
30$NAME/math.lua \
31$NAME/nextvar.lua \
32$NAME/pm.lua \
33$NAME/sort.lua \
34$NAME/strings.lua \
35$NAME/tpack.lua \
36$NAME/tracegc.lua \
37$NAME/utf8.lua \
38$NAME/vararg.lua \
39$NAME/verybig.lua \
40$NAME/libs/makefile \
41$NAME/libs/P1 \
42$NAME/libs/lib1.c \
43$NAME/libs/lib11.c \
44$NAME/libs/lib2.c \
45$NAME/libs/lib21.c \
46$NAME/libs/lib22.c \
47$NAME/ltests/ltests.h \
48$NAME/ltests/ltests.c
49
50\rm -I $NAME
51\rm -I ltests
52
53echo ${NAME}.tar.gz" created"
54
55
diff --git a/zig-lua/lua-5.4.7/testes/pm.lua b/zig-lua/lua-5.4.7/testes/pm.lua
new file mode 100644
index 0000000..e5e3f7a
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/pm.lua
@@ -0,0 +1,440 @@
1-- $Id: testes/pm.lua $
2-- See Copyright Notice in file all.lua
3
4-- UTF-8 file
5
6
7print('testing pattern matching')
8
9local function checkerror (msg, f, ...)
10 local s, err = pcall(f, ...)
11 assert(not s and string.find(err, msg))
12end
13
14
15local function f (s, p)
16 local i,e = string.find(s, p)
17 if i then return string.sub(s, i, e) end
18end
19
20local a,b = string.find('', '') -- empty patterns are tricky
21assert(a == 1 and b == 0);
22a,b = string.find('alo', '')
23assert(a == 1 and b == 0)
24a,b = string.find('a\0o a\0o a\0o', 'a', 1) -- first position
25assert(a == 1 and b == 1)
26a,b = string.find('a\0o a\0o a\0o', 'a\0o', 2) -- starts in the midle
27assert(a == 5 and b == 7)
28a,b = string.find('a\0o a\0o a\0o', 'a\0o', 9) -- starts in the midle
29assert(a == 9 and b == 11)
30a,b = string.find('a\0a\0a\0a\0\0ab', '\0ab', 2); -- finds at the end
31assert(a == 9 and b == 11);
32a,b = string.find('a\0a\0a\0a\0\0ab', 'b') -- last position
33assert(a == 11 and b == 11)
34assert(not string.find('a\0a\0a\0a\0\0ab', 'b\0')) -- check ending
35assert(not string.find('', '\0'))
36assert(string.find('alo123alo', '12') == 4)
37assert(not string.find('alo123alo', '^12'))
38
39assert(string.match("aaab", ".*b") == "aaab")
40assert(string.match("aaa", ".*a") == "aaa")
41assert(string.match("b", ".*b") == "b")
42
43assert(string.match("aaab", ".+b") == "aaab")
44assert(string.match("aaa", ".+a") == "aaa")
45assert(not string.match("b", ".+b"))
46
47assert(string.match("aaab", ".?b") == "ab")
48assert(string.match("aaa", ".?a") == "aa")
49assert(string.match("b", ".?b") == "b")
50
51assert(f('aloALO', '%l*') == 'alo')
52assert(f('aLo_ALO', '%a*') == 'aLo')
53
54assert(f(" \n\r*&\n\r xuxu \n\n", "%g%g%g+") == "xuxu")
55
56
57-- Adapt a pattern to UTF-8
58local function PU (p)
59 -- reapply '?' into each individual byte of a character.
60 -- (For instance, "á?" becomes "\195?\161?".)
61 p = string.gsub(p, "(" .. utf8.charpattern .. ")%?", function (c)
62 return string.gsub(c, ".", "%0?")
63 end)
64 -- change '.' to utf-8 character patterns
65 p = string.gsub(p, "%.", utf8.charpattern)
66 return p
67end
68
69
70assert(f('aaab', 'a*') == 'aaa');
71assert(f('aaa', '^.*$') == 'aaa');
72assert(f('aaa', 'b*') == '');
73assert(f('aaa', 'ab*a') == 'aa')
74assert(f('aba', 'ab*a') == 'aba')
75assert(f('aaab', 'a+') == 'aaa')
76assert(f('aaa', '^.+$') == 'aaa')
77assert(not f('aaa', 'b+'))
78assert(not f('aaa', 'ab+a'))
79assert(f('aba', 'ab+a') == 'aba')
80assert(f('a$a', '.$') == 'a')
81assert(f('a$a', '.%$') == 'a$')
82assert(f('a$a', '.$.') == 'a$a')
83assert(not f('a$a', '$$'))
84assert(not f('a$b', 'a$'))
85assert(f('a$a', '$') == '')
86assert(f('', 'b*') == '')
87assert(not f('aaa', 'bb*'))
88assert(f('aaab', 'a-') == '')
89assert(f('aaa', '^.-$') == 'aaa')
90assert(f('aabaaabaaabaaaba', 'b.*b') == 'baaabaaabaaab')
91assert(f('aabaaabaaabaaaba', 'b.-b') == 'baaab')
92assert(f('alo xo', '.o$') == 'xo')
93assert(f(' \n isto é assim', '%S%S*') == 'isto')
94assert(f(' \n isto é assim', '%S*$') == 'assim')
95assert(f(' \n isto é assim', '[a-z]*$') == 'assim')
96assert(f('um caracter ? extra', '[^%sa-z]') == '?')
97assert(f('', 'a?') == '')
98assert(f('á', PU'á?') == 'á')
99assert(f('ábl', PU'á?b?l?') == 'ábl')
100assert(f(' ábl', PU'á?b?l?') == '')
101assert(f('aa', '^aa?a?a') == 'aa')
102assert(f(']]]áb', '[^]]+') == 'áb')
103assert(f("0alo alo", "%x*") == "0a")
104assert(f("alo alo", "%C+") == "alo alo")
105print('+')
106
107
108local function f1 (s, p)
109 p = string.gsub(p, "%%([0-9])", function (s)
110 return "%" .. (tonumber(s)+1)
111 end)
112 p = string.gsub(p, "^(^?)", "%1()", 1)
113 p = string.gsub(p, "($?)$", "()%1", 1)
114 local t = {string.match(s, p)}
115 return string.sub(s, t[1], t[#t] - 1)
116end
117
118assert(f1('alo alx 123 b\0o b\0o', '(..*) %1') == "b\0o b\0o")
119assert(f1('axz123= 4= 4 34', '(.+)=(.*)=%2 %1') == '3= 4= 4 3')
120assert(f1('=======', '^(=*)=%1$') == '=======')
121assert(not string.match('==========', '^([=]*)=%1$'))
122
123local function range (i, j)
124 if i <= j then
125 return i, range(i+1, j)
126 end
127end
128
129local abc = string.char(range(0, 127)) .. string.char(range(128, 255));
130
131assert(string.len(abc) == 256)
132
133local function strset (p)
134 local res = {s=''}
135 string.gsub(abc, p, function (c) res.s = res.s .. c end)
136 return res.s
137end;
138
139assert(string.len(strset('[\200-\210]')) == 11)
140
141assert(strset('[a-z]') == "abcdefghijklmnopqrstuvwxyz")
142assert(strset('[a-z%d]') == strset('[%da-uu-z]'))
143assert(strset('[a-]') == "-a")
144assert(strset('[^%W]') == strset('[%w]'))
145assert(strset('[]%%]') == '%]')
146assert(strset('[a%-z]') == '-az')
147assert(strset('[%^%[%-a%]%-b]') == '-[]^ab')
148assert(strset('%Z') == strset('[\1-\255]'))
149assert(strset('.') == strset('[\1-\255%z]'))
150print('+');
151
152assert(string.match("alo xyzK", "(%w+)K") == "xyz")
153assert(string.match("254 K", "(%d*)K") == "")
154assert(string.match("alo ", "(%w*)$") == "")
155assert(not string.match("alo ", "(%w+)$"))
156assert(string.find("(álo)", "%(á") == 1)
157local a, b, c, d, e = string.match("âlo alo", PU"^(((.).). (%w*))$")
158assert(a == 'âlo alo' and b == 'âl' and c == 'â' and d == 'alo' and e == nil)
159a, b, c, d = string.match('0123456789', '(.+(.?)())')
160assert(a == '0123456789' and b == '' and c == 11 and d == nil)
161print('+')
162
163assert(string.gsub('ülo ülo', 'ü', 'x') == 'xlo xlo')
164assert(string.gsub('alo úlo ', ' +$', '') == 'alo úlo') -- trim
165assert(string.gsub(' alo alo ', '^%s*(.-)%s*$', '%1') == 'alo alo') -- double trim
166assert(string.gsub('alo alo \n 123\n ', '%s+', ' ') == 'alo alo 123 ')
167local t = "abç d"
168a, b = string.gsub(t, PU'(.)', '%1@')
169assert(a == "a@b@ç@ @d@" and b == 5)
170a, b = string.gsub('abçd', PU'(.)', '%0@', 2)
171assert(a == 'a@b@çd' and b == 2)
172assert(string.gsub('alo alo', '()[al]', '%1') == '12o 56o')
173assert(string.gsub("abc=xyz", "(%w*)(%p)(%w+)", "%3%2%1-%0") ==
174 "xyz=abc-abc=xyz")
175assert(string.gsub("abc", "%w", "%1%0") == "aabbcc")
176assert(string.gsub("abc", "%w+", "%0%1") == "abcabc")
177assert(string.gsub('áéí', '$', '\0óú') == 'áéí\0óú')
178assert(string.gsub('', '^', 'r') == 'r')
179assert(string.gsub('', '$', 'r') == 'r')
180print('+')
181
182
183do -- new (5.3.3) semantics for empty matches
184 assert(string.gsub("a b cd", " *", "-") == "-a-b-c-d-")
185
186 local res = ""
187 local sub = "a \nbc\t\td"
188 local i = 1
189 for p, e in string.gmatch(sub, "()%s*()") do
190 res = res .. string.sub(sub, i, p - 1) .. "-"
191 i = e
192 end
193 assert(res == "-a-b-c-d-")
194end
195
196
197assert(string.gsub("um (dois) tres (quatro)", "(%(%w+%))", string.upper) ==
198 "um (DOIS) tres (QUATRO)")
199
200do
201 local function setglobal (n,v) rawset(_G, n, v) end
202 string.gsub("a=roberto,roberto=a", "(%w+)=(%w%w*)", setglobal)
203 assert(_G.a=="roberto" and _G.roberto=="a")
204 _G.a = nil; _G.roberto = nil
205end
206
207function f(a,b) return string.gsub(a,'.',b) end
208assert(string.gsub("trocar tudo em |teste|b| é |beleza|al|", "|([^|]*)|([^|]*)|", f) ==
209 "trocar tudo em bbbbb é alalalalalal")
210
211local function dostring (s) return load(s, "")() or "" end
212assert(string.gsub("alo $a='x'$ novamente $return a$",
213 "$([^$]*)%$",
214 dostring) == "alo novamente x")
215
216local x = string.gsub("$x=string.gsub('alo', '.', string.upper)$ assim vai para $return x$",
217 "$([^$]*)%$", dostring)
218assert(x == ' assim vai para ALO')
219_G.a, _G.x = nil
220
221local t = {}
222local s = 'a alo jose joao'
223local r = string.gsub(s, '()(%w+)()', function (a,w,b)
224 assert(string.len(w) == b-a);
225 t[a] = b-a;
226 end)
227assert(s == r and t[1] == 1 and t[3] == 3 and t[7] == 4 and t[13] == 4)
228
229
230local function isbalanced (s)
231 return not string.find(string.gsub(s, "%b()", ""), "[()]")
232end
233
234assert(isbalanced("(9 ((8))(\0) 7) \0\0 a b ()(c)() a"))
235assert(not isbalanced("(9 ((8) 7) a b (\0 c) a"))
236assert(string.gsub("alo 'oi' alo", "%b''", '"') == 'alo " alo')
237
238
239local t = {"apple", "orange", "lime"; n=0}
240assert(string.gsub("x and x and x", "x", function () t.n=t.n+1; return t[t.n] end)
241 == "apple and orange and lime")
242
243t = {n=0}
244string.gsub("first second word", "%w%w*", function (w) t.n=t.n+1; t[t.n] = w end)
245assert(t[1] == "first" and t[2] == "second" and t[3] == "word" and t.n == 3)
246
247t = {n=0}
248assert(string.gsub("first second word", "%w+",
249 function (w) t.n=t.n+1; t[t.n] = w end, 2) == "first second word")
250assert(t[1] == "first" and t[2] == "second" and t[3] == undef)
251
252checkerror("invalid replacement value %(a table%)",
253 string.gsub, "alo", ".", {a = {}})
254checkerror("invalid capture index %%2", string.gsub, "alo", ".", "%2")
255checkerror("invalid capture index %%0", string.gsub, "alo", "(%0)", "a")
256checkerror("invalid capture index %%1", string.gsub, "alo", "(%1)", "a")
257checkerror("invalid use of '%%'", string.gsub, "alo", ".", "%x")
258
259
260if not _soft then
261 print("big strings")
262 local a = string.rep('a', 300000)
263 assert(string.find(a, '^a*.?$'))
264 assert(not string.find(a, '^a*.?b$'))
265 assert(string.find(a, '^a-.?$'))
266
267 -- bug in 5.1.2
268 a = string.rep('a', 10000) .. string.rep('b', 10000)
269 assert(not pcall(string.gsub, a, 'b'))
270end
271
272-- recursive nest of gsubs
273local function rev (s)
274 return string.gsub(s, "(.)(.+)", function (c,s1) return rev(s1)..c end)
275end
276
277local x = "abcdef"
278assert(rev(rev(x)) == x)
279
280
281-- gsub with tables
282assert(string.gsub("alo alo", ".", {}) == "alo alo")
283assert(string.gsub("alo alo", "(.)", {a="AA", l=""}) == "AAo AAo")
284assert(string.gsub("alo alo", "(.).", {a="AA", l="K"}) == "AAo AAo")
285assert(string.gsub("alo alo", "((.)(.?))", {al="AA", o=false}) == "AAo AAo")
286
287assert(string.gsub("alo alo", "().", {'x','yy','zzz'}) == "xyyzzz alo")
288
289t = {}; setmetatable(t, {__index = function (t,s) return string.upper(s) end})
290assert(string.gsub("a alo b hi", "%w%w+", t) == "a ALO b HI")
291
292
293-- tests for gmatch
294local a = 0
295for i in string.gmatch('abcde', '()') do assert(i == a+1); a=i end
296assert(a==6)
297
298t = {n=0}
299for w in string.gmatch("first second word", "%w+") do
300 t.n=t.n+1; t[t.n] = w
301end
302assert(t[1] == "first" and t[2] == "second" and t[3] == "word")
303
304t = {3, 6, 9}
305for i in string.gmatch ("xuxx uu ppar r", "()(.)%2") do
306 assert(i == table.remove(t, 1))
307end
308assert(#t == 0)
309
310t = {}
311for i,j in string.gmatch("13 14 10 = 11, 15= 16, 22=23", "(%d+)%s*=%s*(%d+)") do
312 t[tonumber(i)] = tonumber(j)
313end
314a = 0
315for k,v in pairs(t) do assert(k+1 == v+0); a=a+1 end
316assert(a == 3)
317
318
319do -- init parameter in gmatch
320 local s = 0
321 for k in string.gmatch("10 20 30", "%d+", 3) do
322 s = s + tonumber(k)
323 end
324 assert(s == 50)
325
326 s = 0
327 for k in string.gmatch("11 21 31", "%d+", -4) do
328 s = s + tonumber(k)
329 end
330 assert(s == 32)
331
332 -- there is an empty string at the end of the subject
333 s = 0
334 for k in string.gmatch("11 21 31", "%w*", 9) do
335 s = s + 1
336 end
337 assert(s == 1)
338
339 -- there are no empty strings after the end of the subject
340 s = 0
341 for k in string.gmatch("11 21 31", "%w*", 10) do
342 s = s + 1
343 end
344 assert(s == 0)
345end
346
347
348-- tests for `%f' (`frontiers')
349
350assert(string.gsub("aaa aa a aaa a", "%f[%w]a", "x") == "xaa xa x xaa x")
351assert(string.gsub("[[]] [][] [[[[", "%f[[].", "x") == "x[]] x]x] x[[[")
352assert(string.gsub("01abc45de3", "%f[%d]", ".") == ".01abc.45de.3")
353assert(string.gsub("01abc45 de3x", "%f[%D]%w", ".") == "01.bc45 de3.")
354assert(string.gsub("function", "%f[\1-\255]%w", ".") == ".unction")
355assert(string.gsub("function", "%f[^\1-\255]", ".") == "function.")
356
357assert(string.find("a", "%f[a]") == 1)
358assert(string.find("a", "%f[^%z]") == 1)
359assert(string.find("a", "%f[^%l]") == 2)
360assert(string.find("aba", "%f[a%z]") == 3)
361assert(string.find("aba", "%f[%z]") == 4)
362assert(not string.find("aba", "%f[%l%z]"))
363assert(not string.find("aba", "%f[^%l%z]"))
364
365local i, e = string.find(" alo aalo allo", "%f[%S].-%f[%s].-%f[%S]")
366assert(i == 2 and e == 5)
367local k = string.match(" alo aalo allo", "%f[%S](.-%f[%s].-%f[%S])")
368assert(k == 'alo ')
369
370local a = {1, 5, 9, 14, 17,}
371for k in string.gmatch("alo alo th02 is 1hat", "()%f[%w%d]") do
372 assert(table.remove(a, 1) == k)
373end
374assert(#a == 0)
375
376
377-- malformed patterns
378local function malform (p, m)
379 m = m or "malformed"
380 local r, msg = pcall(string.find, "a", p)
381 assert(not r and string.find(msg, m))
382end
383
384malform("(.", "unfinished capture")
385malform(".)", "invalid pattern capture")
386malform("[a")
387malform("[]")
388malform("[^]")
389malform("[a%]")
390malform("[a%")
391malform("%b")
392malform("%ba")
393malform("%")
394malform("%f", "missing")
395
396-- \0 in patterns
397assert(string.match("ab\0\1\2c", "[\0-\2]+") == "\0\1\2")
398assert(string.match("ab\0\1\2c", "[\0-\0]+") == "\0")
399assert(string.find("b$a", "$\0?") == 2)
400assert(string.find("abc\0efg", "%\0") == 4)
401assert(string.match("abc\0efg\0\1e\1g", "%b\0\1") == "\0efg\0\1e\1")
402assert(string.match("abc\0\0\0", "%\0+") == "\0\0\0")
403assert(string.match("abc\0\0\0", "%\0%\0?") == "\0\0")
404
405-- magic char after \0
406assert(string.find("abc\0\0","\0.") == 4)
407assert(string.find("abcx\0\0abc\0abc","x\0\0abc\0a.") == 4)
408
409
410do -- test reuse of original string in gsub
411 local s = string.rep("a", 100)
412 local r = string.gsub(s, "b", "c") -- no match
413 assert(string.format("%p", s) == string.format("%p", r))
414
415 r = string.gsub(s, ".", {x = "y"}) -- no substitutions
416 assert(string.format("%p", s) == string.format("%p", r))
417
418 local count = 0
419 r = string.gsub(s, ".", function (x)
420 assert(x == "a")
421 count = count + 1
422 return nil -- no substitution
423 end)
424 r = string.gsub(r, ".", {b = 'x'}) -- "a" is not a key; no subst.
425 assert(count == 100)
426 assert(string.format("%p", s) == string.format("%p", r))
427
428 count = 0
429 r = string.gsub(s, ".", function (x)
430 assert(x == "a")
431 count = count + 1
432 return x -- substitution...
433 end)
434 assert(count == 100)
435 -- no reuse in this case
436 assert(r == s and string.format("%p", s) ~= string.format("%p", r))
437end
438
439print('OK')
440
diff --git a/zig-lua/lua-5.4.7/testes/sort.lua b/zig-lua/lua-5.4.7/testes/sort.lua
new file mode 100644
index 0000000..40bb2d8
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/sort.lua
@@ -0,0 +1,311 @@
1-- $Id: testes/sort.lua $
2-- See Copyright Notice in file all.lua
3
4print "testing (parts of) table library"
5
6print "testing unpack"
7
8local unpack = table.unpack
9
10local maxI = math.maxinteger
11local minI = math.mininteger
12
13
14local function checkerror (msg, f, ...)
15 local s, err = pcall(f, ...)
16 assert(not s and string.find(err, msg))
17end
18
19
20checkerror("wrong number of arguments", table.insert, {}, 2, 3, 4)
21
22local x,y,z,a,n
23a = {}; local lim = _soft and 200 or 2000
24for i=1, lim do a[i]=i end
25assert(select(lim, unpack(a)) == lim and select('#', unpack(a)) == lim)
26x = unpack(a)
27assert(x == 1)
28x = {unpack(a)}
29assert(#x == lim and x[1] == 1 and x[lim] == lim)
30x = {unpack(a, lim-2)}
31assert(#x == 3 and x[1] == lim-2 and x[3] == lim)
32x = {unpack(a, 10, 6)}
33assert(next(x) == nil) -- no elements
34x = {unpack(a, 11, 10)}
35assert(next(x) == nil) -- no elements
36x,y = unpack(a, 10, 10)
37assert(x == 10 and y == nil)
38x,y,z = unpack(a, 10, 11)
39assert(x == 10 and y == 11 and z == nil)
40a,x = unpack{1}
41assert(a==1 and x==nil)
42a,x = unpack({1,2}, 1, 1)
43assert(a==1 and x==nil)
44
45do
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)
71end
72
73do -- 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)
77end
78
79print "testing pack"
80
81a = table.pack()
82assert(a[1] == undef and a.n == 0)
83
84a = table.pack(table)
85assert(a[1] == table and a.n == 1)
86
87a = table.pack(nil, nil, nil, nil)
88assert(a[1] == nil and a.n == 4)
89
90
91-- testing move
92do
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)
161end
162
163do
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
180end
181
182checkerror("too many", table.move, {}, 0, maxI, 1)
183checkerror("too many", table.move, {}, -1, maxI - 1, 1)
184checkerror("too many", table.move, {}, minI, -1, 1)
185checkerror("too many", table.move, {}, minI, maxI, 1)
186checkerror("wrap around", table.move, {}, 1, maxI, 2)
187checkerror("wrap around", table.move, {}, 1, 2, maxI)
188checkerror("wrap around", table.move, {}, minI, -2, 2)
189
190
191print"testing sort"
192
193
194-- strange lengths
195local a = setmetatable({}, {__len = function () return -1 end})
196assert(#a == -1)
197table.sort(a, error) -- should not compare anything
198a = setmetatable({}, {__len = function () return maxI end})
199checkerror("too big", table.sort, a)
200
201-- test checks for invalid order functions
202local 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)
205end
206
207check{1,2,3,4}
208check{1,2,3,4,5}
209check{1,2,3,4,5,6}
210
211
212function 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
217end
218
219a = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
220 "Oct", "Nov", "Dec"}
221
222table.sort(a)
223check(a)
224
225local 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
238end
239
240perm{}
241perm{1}
242perm{1,2}
243perm{1,2,3}
244perm{1,2,3,4}
245perm{2,2,3,4}
246perm{1,2,3,4,5}
247perm{1,2,3,3,5}
248perm{1,2,3,4,5,6}
249perm{2,2,3,3,5,6}
250
251local 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)
258end
259
260local limit = 50000
261if _soft then limit = 5000 end
262
263a = {}
264for i=1,limit do
265 a[i] = math.random()
266end
267
268timesort(a, limit, nil, "random")
269
270timesort(a, limit, nil, "sorted", "re-")
271
272a = {}
273for i=1,limit do
274 a[i] = math.random()
275end
276
277local x = os.clock(); local i = 0
278table.sort(a, function(x,y) i=i+1; return y<x end)
279x = (os.clock() - x) * 1000
280print(string.format("Invert-sorting other %d elements in %.2f msec., with %i comparisons",
281 limit, x, i))
282check(a, function(x,y) return y<x end)
283
284
285table.sort{} -- empty array
286
287for i=1,limit do a[i] = false end
288timesort(a, limit, function(x,y) return nil end, "equal")
289
290for i,v in pairs(a) do assert(v == false) end
291
292AA = {"\xE1lo", "\0first :-)", "alo", "then this one", "45", "and a new"}
293table.sort(AA)
294check(AA)
295
296table.sort(AA, function (x, y)
297 load(string.format("AA[%q] = ''", x), "")()
298 collectgarbage()
299 return x<y
300 end)
301
302_G.AA = nil
303
304local tt = {__lt = function (a,b) return a.val < b.val end}
305a = {}
306for i=1,10 do a[i] = {val=math.random(100)}; setmetatable(a[i], tt); end
307table.sort(a)
308check(a, tt.__lt)
309check(a)
310
311print"OK"
diff --git a/zig-lua/lua-5.4.7/testes/strings.lua b/zig-lua/lua-5.4.7/testes/strings.lua
new file mode 100644
index 0000000..90983ed
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/strings.lua
@@ -0,0 +1,526 @@
1-- $Id: testes/strings.lua $
2-- See Copyright Notice in file all.lua
3
4-- ISO Latin encoding
5
6
7print('testing strings and string library')
8
9local maxi <const> = math.maxinteger
10local mini <const> = math.mininteger
11
12
13local function checkerror (msg, f, ...)
14 local s, err = pcall(f, ...)
15 assert(not s and string.find(err, msg))
16end
17
18
19-- testing string comparisons
20assert('alo' < 'alo1')
21assert('' < 'a')
22assert('alo\0alo' < 'alo\0b')
23assert('alo\0alo\0\0' > 'alo\0alo\0')
24assert('alo' < 'alo\0')
25assert('alo\0' > 'alo')
26assert('\0' < '\1')
27assert('\0\0' < '\0\1')
28assert('\1\0a\0a' <= '\1\0a\0a')
29assert(not ('\1\0a\0b' <= '\1\0a\0a'))
30assert('\0\0\0' < '\0\0\0\0')
31assert(not('\0\0\0\0' < '\0\0\0'))
32assert('\0\0\0' <= '\0\0\0\0')
33assert(not('\0\0\0\0' <= '\0\0\0'))
34assert('\0\0\0' <= '\0\0\0')
35assert('\0\0\0' >= '\0\0\0')
36assert(not ('\0\0b' < '\0\0a\0'))
37
38-- testing string.sub
39assert(string.sub("123456789",2,4) == "234")
40assert(string.sub("123456789",7) == "789")
41assert(string.sub("123456789",7,6) == "")
42assert(string.sub("123456789",7,7) == "7")
43assert(string.sub("123456789",0,0) == "")
44assert(string.sub("123456789",-10,10) == "123456789")
45assert(string.sub("123456789",1,9) == "123456789")
46assert(string.sub("123456789",-10,-20) == "")
47assert(string.sub("123456789",-1) == "9")
48assert(string.sub("123456789",-4) == "6789")
49assert(string.sub("123456789",-6, -4) == "456")
50assert(string.sub("123456789", mini, -4) == "123456")
51assert(string.sub("123456789", mini, maxi) == "123456789")
52assert(string.sub("123456789", mini, mini) == "")
53assert(string.sub("\000123456789",3,5) == "234")
54assert(("\000123456789"):sub(8) == "789")
55
56-- testing string.find
57assert(string.find("123456789", "345") == 3)
58local a,b = string.find("123456789", "345")
59assert(string.sub("123456789", a, b) == "345")
60assert(string.find("1234567890123456789", "345", 3) == 3)
61assert(string.find("1234567890123456789", "345", 4) == 13)
62assert(not string.find("1234567890123456789", "346", 4))
63assert(string.find("1234567890123456789", ".45", -9) == 13)
64assert(not string.find("abcdefg", "\0", 5, 1))
65assert(string.find("", "") == 1)
66assert(string.find("", "", 1) == 1)
67assert(not string.find("", "", 2))
68assert(not string.find('', 'aaa', 1))
69assert(('alo(.)alo'):find('(.)', 1, 1) == 4)
70
71assert(string.len("") == 0)
72assert(string.len("\0\0\0") == 3)
73assert(string.len("1234567890") == 10)
74
75assert(#"" == 0)
76assert(#"\0\0\0" == 3)
77assert(#"1234567890" == 10)
78
79-- testing string.byte/string.char
80assert(string.byte("a") == 97)
81assert(string.byte("\xe4") > 127)
82assert(string.byte(string.char(255)) == 255)
83assert(string.byte(string.char(0)) == 0)
84assert(string.byte("\0") == 0)
85assert(string.byte("\0\0alo\0x", -1) == string.byte('x'))
86assert(string.byte("ba", 2) == 97)
87assert(string.byte("\n\n", 2, -1) == 10)
88assert(string.byte("\n\n", 2, 2) == 10)
89assert(string.byte("") == nil)
90assert(string.byte("hi", -3) == nil)
91assert(string.byte("hi", 3) == nil)
92assert(string.byte("hi", 9, 10) == nil)
93assert(string.byte("hi", 2, 1) == nil)
94assert(string.char() == "")
95assert(string.char(0, 255, 0) == "\0\255\0")
96assert(string.char(0, string.byte("\xe4"), 0) == "\0\xe4\0")
97assert(string.char(string.byte("\xe4l\0óu", 1, -1)) == "\xe4l\0óu")
98assert(string.char(string.byte("\xe4l\0óu", 1, 0)) == "")
99assert(string.char(string.byte("\xe4l\0óu", -10, 100)) == "\xe4l\0óu")
100
101checkerror("out of range", string.char, 256)
102checkerror("out of range", string.char, -1)
103checkerror("out of range", string.char, math.maxinteger)
104checkerror("out of range", string.char, math.mininteger)
105
106assert(string.upper("ab\0c") == "AB\0C")
107assert(string.lower("\0ABCc%$") == "\0abcc%$")
108assert(string.rep('teste', 0) == '')
109assert(string.rep('tés\00tê', 2) == 'tés\0têtés\000tê')
110assert(string.rep('', 10) == '')
111
112if string.packsize("i") == 4 then
113 -- result length would be 2^31 (int overflow)
114 checkerror("too large", string.rep, 'aa', (1 << 30))
115 checkerror("too large", string.rep, 'a', (1 << 30), ',')
116end
117
118-- repetitions with separator
119assert(string.rep('teste', 0, 'xuxu') == '')
120assert(string.rep('teste', 1, 'xuxu') == 'teste')
121assert(string.rep('\1\0\1', 2, '\0\0') == '\1\0\1\0\0\1\0\1')
122assert(string.rep('', 10, '.') == string.rep('.', 9))
123assert(not pcall(string.rep, "aa", maxi // 2 + 10))
124assert(not pcall(string.rep, "", maxi // 2 + 10, "aa"))
125
126assert(string.reverse"" == "")
127assert(string.reverse"\0\1\2\3" == "\3\2\1\0")
128assert(string.reverse"\0001234" == "4321\0")
129
130for i=0,30 do assert(string.len(string.rep('a', i)) == i) end
131
132assert(type(tostring(nil)) == 'string')
133assert(type(tostring(12)) == 'string')
134assert(string.find(tostring{}, 'table:'))
135assert(string.find(tostring(print), 'function:'))
136assert(#tostring('\0') == 1)
137assert(tostring(true) == "true")
138assert(tostring(false) == "false")
139assert(tostring(-1203) == "-1203")
140assert(tostring(1203.125) == "1203.125")
141assert(tostring(-0.5) == "-0.5")
142assert(tostring(-32767) == "-32767")
143if math.tointeger(2147483647) then -- no overflow? (32 bits)
144 assert(tostring(-2147483647) == "-2147483647")
145end
146if math.tointeger(4611686018427387904) then -- no overflow? (64 bits)
147 assert(tostring(4611686018427387904) == "4611686018427387904")
148 assert(tostring(-4611686018427387904) == "-4611686018427387904")
149end
150
151if tostring(0.0) == "0.0" then -- "standard" coercion float->string
152 assert('' .. 12 == '12' and 12.0 .. '' == '12.0')
153 assert(tostring(-1203 + 0.0) == "-1203.0")
154else -- compatible coercion
155 assert(tostring(0.0) == "0")
156 assert('' .. 12 == '12' and 12.0 .. '' == '12')
157 assert(tostring(-1203 + 0.0) == "-1203")
158end
159
160do -- tests for '%p' format
161 -- not much to test, as C does not specify what '%p' does.
162 -- ("The value of the pointer is converted to a sequence of printing
163 -- characters, in an implementation-defined manner.")
164 local null = "(null)" -- nulls are formatted by Lua
165 assert(string.format("%p", 4) == null)
166 assert(string.format("%p", true) == null)
167 assert(string.format("%p", nil) == null)
168 assert(string.format("%p", {}) ~= null)
169 assert(string.format("%p", print) ~= null)
170 assert(string.format("%p", coroutine.running()) ~= null)
171 assert(string.format("%p", io.stdin) ~= null)
172 assert(string.format("%p", io.stdin) == string.format("%p", io.stdin))
173 assert(string.format("%p", print) == string.format("%p", print))
174 assert(string.format("%p", print) ~= string.format("%p", assert))
175
176 assert(#string.format("%90p", {}) == 90)
177 assert(#string.format("%-60p", {}) == 60)
178 assert(string.format("%10p", false) == string.rep(" ", 10 - #null) .. null)
179 assert(string.format("%-12p", 1.5) == null .. string.rep(" ", 12 - #null))
180
181 do
182 local t1 = {}; local t2 = {}
183 assert(string.format("%p", t1) ~= string.format("%p", t2))
184 end
185
186 do -- short strings are internalized
187 local s1 = string.rep("a", 10)
188 local s2 = string.rep("aa", 5)
189 assert(string.format("%p", s1) == string.format("%p", s2))
190 end
191
192 do -- long strings aren't internalized
193 local s1 = string.rep("a", 300); local s2 = string.rep("a", 300)
194 assert(string.format("%p", s1) ~= string.format("%p", s2))
195 end
196end
197
198local x = '"ílo"\n\\'
199assert(string.format('%q%s', x, x) == '"\\"ílo\\"\\\n\\\\""ílo"\n\\')
200assert(string.format('%q', "\0") == [["\0"]])
201assert(load(string.format('return %q', x))() == x)
202x = "\0\1\0023\5\0009"
203assert(load(string.format('return %q', x))() == x)
204assert(string.format("\0%c\0%c%x\0", string.byte("\xe4"), string.byte("b"), 140) ==
205 "\0\xe4\0b8c\0")
206assert(string.format('') == "")
207assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) ==
208 string.format("%1c%-c%-1c%c", 34, 48, 90, 100))
209assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be')
210assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023")
211assert(tonumber(string.format("%f", 10.3)) == 10.3)
212assert(string.format('"%-50s"', 'a') == '"a' .. string.rep(' ', 49) .. '"')
213
214assert(string.format("-%.20s.20s", string.rep("%", 2000)) ==
215 "-"..string.rep("%", 20)..".20s")
216assert(string.format('"-%20s.20s"', string.rep("%", 2000)) ==
217 string.format("%q", "-"..string.rep("%", 2000)..".20s"))
218
219do
220 local function checkQ (v)
221 local s = string.format("%q", v)
222 local nv = load("return " .. s)()
223 assert(v == nv and math.type(v) == math.type(nv))
224 end
225 checkQ("\0\0\1\255\u{234}")
226 checkQ(math.maxinteger)
227 checkQ(math.mininteger)
228 checkQ(math.pi)
229 checkQ(0.1)
230 checkQ(true)
231 checkQ(nil)
232 checkQ(false)
233 checkQ(math.huge)
234 checkQ(-math.huge)
235 assert(string.format("%q", 0/0) == "(0/0)") -- NaN
236 checkerror("no literal", string.format, "%q", {})
237end
238
239assert(string.format("\0%s\0", "\0\0\1") == "\0\0\0\1\0")
240checkerror("contains zeros", string.format, "%10s", "\0")
241
242-- format x tostring
243assert(string.format("%s %s", nil, true) == "nil true")
244assert(string.format("%s %.4s", false, true) == "false true")
245assert(string.format("%.3s %.3s", false, true) == "fal tru")
246local m = setmetatable({}, {__tostring = function () return "hello" end,
247 __name = "hi"})
248assert(string.format("%s %.10s", m, m) == "hello hello")
249getmetatable(m).__tostring = nil -- will use '__name' from now on
250assert(string.format("%.4s", m) == "hi: ")
251
252getmetatable(m).__tostring = function () return {} end
253checkerror("'__tostring' must return a string", tostring, m)
254
255
256assert(string.format("%x", 0.0) == "0")
257assert(string.format("%02x", 0.0) == "00")
258assert(string.format("%08X", 0xFFFFFFFF) == "FFFFFFFF")
259assert(string.format("%+08d", 31501) == "+0031501")
260assert(string.format("%+08d", -30927) == "-0030927")
261
262
263do -- longest number that can be formatted
264 local i = 1
265 local j = 10000
266 while i + 1 < j do -- binary search for maximum finite float
267 local m = (i + j) // 2
268 if 10^m < math.huge then i = m else j = m end
269 end
270 assert(10^i < math.huge and 10^j == math.huge)
271 local s = string.format('%.99f', -(10^i))
272 assert(string.len(s) >= i + 101)
273 assert(tonumber(s) == -(10^i))
274
275 -- limit for floats
276 assert(10^38 < math.huge)
277 local s = string.format('%.99f', -(10^38))
278 assert(string.len(s) >= 38 + 101)
279 assert(tonumber(s) == -(10^38))
280end
281
282
283-- testing large numbers for format
284do -- assume at least 32 bits
285 local max, min = 0x7fffffff, -0x80000000 -- "large" for 32 bits
286 assert(string.sub(string.format("%8x", -1), -8) == "ffffffff")
287 assert(string.format("%x", max) == "7fffffff")
288 assert(string.sub(string.format("%x", min), -8) == "80000000")
289 assert(string.format("%d", max) == "2147483647")
290 assert(string.format("%d", min) == "-2147483648")
291 assert(string.format("%u", 0xffffffff) == "4294967295")
292 assert(string.format("%o", 0xABCD) == "125715")
293
294 max, min = 0x7fffffffffffffff, -0x8000000000000000
295 if max > 2.0^53 then -- only for 64 bits
296 assert(string.format("%x", (2^52 | 0) - 1) == "fffffffffffff")
297 assert(string.format("0x%8X", 0x8f000003) == "0x8F000003")
298 assert(string.format("%d", 2^53) == "9007199254740992")
299 assert(string.format("%i", -2^53) == "-9007199254740992")
300 assert(string.format("%x", max) == "7fffffffffffffff")
301 assert(string.format("%x", min) == "8000000000000000")
302 assert(string.format("%d", max) == "9223372036854775807")
303 assert(string.format("%d", min) == "-9223372036854775808")
304 assert(string.format("%u", ~(-1 << 64)) == "18446744073709551615")
305 assert(tostring(1234567890123) == '1234567890123')
306 end
307end
308
309
310do print("testing 'format %a %A'")
311 local function matchhexa (n)
312 local s = string.format("%a", n)
313 -- result matches ISO C requirements
314 assert(string.find(s, "^%-?0x[1-9a-f]%.?[0-9a-f]*p[-+]?%d+$"))
315 assert(tonumber(s) == n) -- and has full precision
316 s = string.format("%A", n)
317 assert(string.find(s, "^%-?0X[1-9A-F]%.?[0-9A-F]*P[-+]?%d+$"))
318 assert(tonumber(s) == n)
319 end
320 for _, n in ipairs{0.1, -0.1, 1/3, -1/3, 1e30, -1e30,
321 -45/247, 1, -1, 2, -2, 3e-20, -3e-20} do
322 matchhexa(n)
323 end
324
325 assert(string.find(string.format("%A", 0.0), "^0X0%.?0*P%+?0$"))
326 assert(string.find(string.format("%a", -0.0), "^%-0x0%.?0*p%+?0$"))
327
328 if not _port then -- test inf, -inf, NaN, and -0.0
329 assert(string.find(string.format("%a", 1/0), "^inf"))
330 assert(string.find(string.format("%A", -1/0), "^%-INF"))
331 assert(string.find(string.format("%a", 0/0), "^%-?nan"))
332 assert(string.find(string.format("%a", -0.0), "^%-0x0"))
333 end
334
335 if not pcall(string.format, "%.3a", 0) then
336 (Message or print)("\n >>> modifiers for format '%a' not available <<<\n")
337 else
338 assert(string.find(string.format("%+.2A", 12), "^%+0X%x%.%x0P%+?%d$"))
339 assert(string.find(string.format("%.4A", -12), "^%-0X%x%.%x000P%+?%d$"))
340 end
341end
342
343
344-- testing some flags (all these results are required by ISO C)
345assert(string.format("%#12o", 10) == " 012")
346assert(string.format("%#10x", 100) == " 0x64")
347assert(string.format("%#-17X", 100) == "0X64 ")
348assert(string.format("%013i", -100) == "-000000000100")
349assert(string.format("%2.5d", -100) == "-00100")
350assert(string.format("%.u", 0) == "")
351assert(string.format("%+#014.0f", 100) == "+000000000100.")
352assert(string.format("%-16c", 97) == "a ")
353assert(string.format("%+.3G", 1.5) == "+1.5")
354assert(string.format("%.0s", "alo") == "")
355assert(string.format("%.s", "alo") == "")
356
357-- ISO C89 says that "The exponent always contains at least two digits",
358-- but unlike ISO C99 it does not ensure that it contains "only as many
359-- more digits as necessary".
360assert(string.match(string.format("% 1.0E", 100), "^ 1E%+0+2$"))
361assert(string.match(string.format("% .1g", 2^10), "^ 1e%+0+3$"))
362
363
364-- errors in format
365
366local function check (fmt, msg)
367 checkerror(msg, string.format, fmt, 10)
368end
369
370local aux = string.rep('0', 600)
371check("%100.3d", "invalid conversion")
372check("%1"..aux..".3d", "too long")
373check("%1.100d", "invalid conversion")
374check("%10.1"..aux.."004d", "too long")
375check("%t", "invalid conversion")
376check("%"..aux.."d", "too long")
377check("%d %d", "no value")
378check("%010c", "invalid conversion")
379check("%.10c", "invalid conversion")
380check("%0.34s", "invalid conversion")
381check("%#i", "invalid conversion")
382check("%3.1p", "invalid conversion")
383check("%0.s", "invalid conversion")
384check("%10q", "cannot have modifiers")
385check("%F", "invalid conversion") -- useless and not in C89
386
387
388assert(load("return 1\n--comment without ending EOL")() == 1)
389
390
391checkerror("table expected", table.concat, 3)
392checkerror("at index " .. maxi, table.concat, {}, " ", maxi, maxi)
393-- '%' escapes following minus signal
394checkerror("at index %" .. mini, table.concat, {}, " ", mini, mini)
395assert(table.concat{} == "")
396assert(table.concat({}, 'x') == "")
397assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2")
398local a = {}; for i=1,300 do a[i] = "xuxu" end
399assert(table.concat(a, "123").."123" == string.rep("xuxu123", 300))
400assert(table.concat(a, "b", 20, 20) == "xuxu")
401assert(table.concat(a, "", 20, 21) == "xuxuxuxu")
402assert(table.concat(a, "x", 22, 21) == "")
403assert(table.concat(a, "3", 299) == "xuxu3xuxu")
404assert(table.concat({}, "x", maxi, maxi - 1) == "")
405assert(table.concat({}, "x", mini + 1, mini) == "")
406assert(table.concat({}, "x", maxi, mini) == "")
407assert(table.concat({[maxi] = "alo"}, "x", maxi, maxi) == "alo")
408assert(table.concat({[maxi] = "alo", [maxi - 1] = "y"}, "-", maxi - 1, maxi)
409 == "y-alo")
410
411assert(not pcall(table.concat, {"a", "b", {}}))
412
413a = {"a","b","c"}
414assert(table.concat(a, ",", 1, 0) == "")
415assert(table.concat(a, ",", 1, 1) == "a")
416assert(table.concat(a, ",", 1, 2) == "a,b")
417assert(table.concat(a, ",", 2) == "b,c")
418assert(table.concat(a, ",", 3) == "c")
419assert(table.concat(a, ",", 4) == "")
420
421if not _port then
422
423 local locales = { "ptb", "pt_BR.iso88591", "ISO-8859-1" }
424 local function trylocale (w)
425 for i = 1, #locales do
426 if os.setlocale(locales[i], w) then
427 print(string.format("'%s' locale set to '%s'", w, locales[i]))
428 return locales[i]
429 end
430 end
431 print(string.format("'%s' locale not found", w))
432 return false
433 end
434
435 if trylocale("collate") then
436 assert("alo" < "álo" and "álo" < "amo")
437 end
438
439 if trylocale("ctype") then
440 assert(string.gsub("áéíóú", "%a", "x") == "xxxxx")
441 assert(string.gsub("áÁéÉ", "%l", "x") == "xÁxÉ")
442 assert(string.gsub("áÁéÉ", "%u", "x") == "áxéx")
443 assert(string.upper"áÁé{xuxu}ção" == "ÁÁÉ{XUXU}ÇÃO")
444 end
445
446 os.setlocale("C")
447 assert(os.setlocale() == 'C')
448 assert(os.setlocale(nil, "numeric") == 'C')
449
450end
451
452
453-- bug in Lua 5.3.2
454-- 'gmatch' iterator does not work across coroutines
455do
456 local f = string.gmatch("1 2 3 4 5", "%d+")
457 assert(f() == "1")
458 local co = coroutine.wrap(f)
459 assert(co() == "2")
460end
461
462
463if T==nil then
464 (Message or print)
465 ("\n >>> testC not active: skipping 'pushfstring' tests <<<\n")
466else
467
468 print"testing 'pushfstring'"
469
470 -- formats %U, %f, %I already tested elsewhere
471
472 local blen = 200 -- internal buffer length in 'luaO_pushfstring'
473
474 local function callpfs (op, fmt, n)
475 local x = {T.testC("pushfstring" .. op .. "; return *", fmt, n)}
476 -- stack has code, 'fmt', 'n', and result from operation
477 assert(#x == 4) -- make sure nothing else was left in the stack
478 return x[4]
479 end
480
481 local function testpfs (op, fmt, n)
482 assert(callpfs(op, fmt, n) == string.format(fmt, n))
483 end
484
485 testpfs("I", "", 0)
486 testpfs("I", string.rep("a", blen - 1), 0)
487 testpfs("I", string.rep("a", blen), 0)
488 testpfs("I", string.rep("a", blen + 1), 0)
489
490 local str = string.rep("ab", blen) .. "%d" .. string.rep("d", blen / 2)
491 testpfs("I", str, 2^14)
492 testpfs("I", str, -2^15)
493
494 str = "%d" .. string.rep("cd", blen)
495 testpfs("I", str, 2^14)
496 testpfs("I", str, -2^15)
497
498 str = string.rep("c", blen - 2) .. "%d"
499 testpfs("I", str, 2^14)
500 testpfs("I", str, -2^15)
501
502 for l = 12, 14 do
503 local str1 = string.rep("a", l)
504 for i = 0, 500, 13 do
505 for j = 0, 500, 13 do
506 str = string.rep("a", i) .. "%s" .. string.rep("d", j)
507 testpfs("S", str, str1)
508 testpfs("S", str, str)
509 end
510 end
511 end
512
513 str = "abc %c def"
514 testpfs("I", str, string.byte("A"))
515 testpfs("I", str, 255)
516
517 str = string.rep("a", blen - 1) .. "%p" .. string.rep("cd", blen)
518 testpfs("P", str, {})
519
520 str = string.rep("%%", 3 * blen) .. "%p" .. string.rep("%%", 2 * blen)
521 testpfs("P", str, {})
522end
523
524
525print('OK')
526
diff --git a/zig-lua/lua-5.4.7/testes/tpack.lua b/zig-lua/lua-5.4.7/testes/tpack.lua
new file mode 100644
index 0000000..bfa63fc
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/tpack.lua
@@ -0,0 +1,322 @@
1-- $Id: testes/tpack.lua $
2-- See Copyright Notice in file all.lua
3
4local pack = string.pack
5local packsize = string.packsize
6local unpack = string.unpack
7
8print "testing pack/unpack"
9
10-- maximum size for integers
11local NB = 16
12
13local sizeshort = packsize("h")
14local sizeint = packsize("i")
15local sizelong = packsize("l")
16local sizesize_t = packsize("T")
17local sizeLI = packsize("j")
18local sizefloat = packsize("f")
19local sizedouble = packsize("d")
20local sizenumber = packsize("n")
21local little = (pack("i2", 1) == "\1\0")
22local align = packsize("!xXi16")
23
24assert(1 <= sizeshort and sizeshort <= sizeint and sizeint <= sizelong and
25 sizefloat <= sizedouble)
26
27print("platform:")
28print(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))
33print("\t" .. (little and "little" or "big") .. " endian")
34print("\talignment: " .. align)
35
36
37-- check errors in arguments
38local function checkerror (msg, f, ...)
39 local status, err = pcall(f, ...)
40 -- print(status, err, msg)
41 assert(not status and string.find(err, msg))
42end
43
44-- minimum behavior for integer formats
45assert(unpack("B", pack("B", 0xff)) == 0xff)
46assert(unpack("b", pack("b", 0x7f)) == 0x7f)
47assert(unpack("b", pack("b", -0x80)) == -0x80)
48
49assert(unpack("H", pack("H", 0xffff)) == 0xffff)
50assert(unpack("h", pack("h", 0x7fff)) == 0x7fff)
51assert(unpack("h", pack("h", -0x8000)) == -0x8000)
52
53assert(unpack("L", pack("L", 0xffffffff)) == 0xffffffff)
54assert(unpack("l", pack("l", 0x7fffffff)) == 0x7fffffff)
55assert(unpack("l", pack("l", -0x80000000)) == -0x80000000)
56
57
58for 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)
71end
72
73do
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
92end
93
94for 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)
102end
103
104-- sign extension
105do
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
112end
113
114-- mixed endianness
115do
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))
120end
121
122print("testing invalid formats")
123
124checkerror("out of limits", pack, "i0", 0)
125checkerror("out of limits", pack, "i" .. NB + 1, 0)
126checkerror("out of limits", pack, "!" .. NB + 1, 0)
127checkerror("%(17%) out of limits %[1,16%]", pack, "Xi" .. NB + 1)
128checkerror("invalid format option 'r'", pack, "i3r", 0)
129checkerror("16%-byte integer", unpack, "i16", string.rep('\3', 16))
130checkerror("not power of 2", pack, "!4i3", 0);
131checkerror("missing size", pack, "c", "")
132checkerror("variable%-length format", packsize, "s")
133checkerror("variable%-length format", packsize, "z")
134
135-- overflow in option size (error will be in digit after limit)
136checkerror("invalid format", packsize, "c1" .. string.rep("0", 40))
137
138if 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)
145end
146
147-- overflow in packing
148for 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)
163end
164
165-- Lua integer size
166assert(unpack(">j", pack(">j", math.maxinteger)) == math.maxinteger)
167assert(unpack("<j", pack("<j", math.mininteger)) == math.mininteger)
168assert(unpack("<J", pack("<j", -1)) == -1) -- maximum unsigned integer
169
170if little then
171 assert(pack("f", 24) == pack("<f", 24))
172else
173 assert(pack("f", 24) == pack(">f", 24))
174end
175
176print "testing pack/unpack of floating-point numbers"
177
178for _, 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())
184end
185
186-- for non-native precisions, test only with "round" numbers
187for _, 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)
192end
193
194print "testing pack/unpack of strings"
195do
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
213end
214
215do
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")
220end
221
222do
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")
237end
238
239
240-- testing multiple types and sequence
241do
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)
247end
248
249print "testing alignment"
250do
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")
290end
291
292do -- 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, #x + 2)
318
319end
320
321print "OK"
322
diff --git a/zig-lua/lua-5.4.7/testes/tracegc.lua b/zig-lua/lua-5.4.7/testes/tracegc.lua
new file mode 100644
index 0000000..9c5c1b3
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/tracegc.lua
@@ -0,0 +1,40 @@
1-- track collections
2
3local M = {}
4
5-- import list
6local setmetatable, stderr, collectgarbage =
7 setmetatable, io.stderr, collectgarbage
8
9_ENV = nil
10
11local active = false
12
13
14-- each time a table is collected, remark it for finalization on next
15-- cycle
16local mt = {}
17function mt.__gc (o)
18 stderr:write'.' -- mark progress
19 if active then
20 setmetatable(o, mt) -- remark object for finalization
21 end
22end
23
24
25function M.start ()
26 if not active then
27 active = true
28 setmetatable({}, mt) -- create initial object
29 end
30end
31
32
33function M.stop ()
34 if active then
35 active = false
36 collectgarbage() -- call finalizer for the last time
37 end
38end
39
40return M
diff --git a/zig-lua/lua-5.4.7/testes/utf8.lua b/zig-lua/lua-5.4.7/testes/utf8.lua
new file mode 100644
index 0000000..efadbd5
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/utf8.lua
@@ -0,0 +1,259 @@
1-- $Id: testes/utf8.lua $
2-- See Copyright Notice in file all.lua
3
4-- UTF-8 file
5
6print "testing UTF-8 library"
7
8local utf8 = require'utf8'
9
10
11local function checkerror (msg, f, ...)
12 local s, err = pcall(f, ...)
13 assert(not s and string.find(err, msg))
14end
15
16
17local function len (s)
18 return #string.gsub(s, "[\x80-\xBF]", "")
19end
20
21
22local justone = "^" .. utf8.charpattern .. "$"
23
24-- 't' is the list of codepoints of 's'
25local function checksyntax (s, t)
26 -- creates a string "return '\u{t[1]}...\u{t[n]}'"
27 local ts = {"return '"}
28 for i = 1, #t do ts[i + 1] = string.format("\\u{%x}", t[i]) end
29 ts[#t + 2] = "'"
30 ts = table.concat(ts)
31 -- its execution should result in 's'
32 assert(assert(load(ts))() == s)
33end
34
35assert(not utf8.offset("alo", 5))
36assert(not utf8.offset("alo", -4))
37
38-- 'check' makes several tests over the validity of string 's'.
39-- 't' is the list of codepoints of 's'.
40local function check (s, t, nonstrict)
41 local l = utf8.len(s, 1, -1, nonstrict)
42 assert(#t == l and len(s) == l)
43 assert(utf8.char(table.unpack(t)) == s) -- 't' and 's' are equivalent
44
45 assert(utf8.offset(s, 0) == 1)
46
47 checksyntax(s, t)
48
49 -- creates new table with all codepoints of 's'
50 local t1 = {utf8.codepoint(s, 1, -1, nonstrict)}
51 assert(#t == #t1)
52 for i = 1, #t do assert(t[i] == t1[i]) end -- 't' is equal to 't1'
53
54 for i = 1, l do -- for all codepoints
55 local pi = utf8.offset(s, i) -- position of i-th char
56 local pi1 = utf8.offset(s, 2, pi) -- position of next char
57 assert(string.find(string.sub(s, pi, pi1 - 1), justone))
58 assert(utf8.offset(s, -1, pi1) == pi)
59 assert(utf8.offset(s, i - l - 1) == pi)
60 assert(pi1 - pi == #utf8.char(utf8.codepoint(s, pi, pi, nonstrict)))
61 for j = pi, pi1 - 1 do
62 assert(utf8.offset(s, 0, j) == pi)
63 end
64 for j = pi + 1, pi1 - 1 do
65 assert(not utf8.len(s, j))
66 end
67 assert(utf8.len(s, pi, pi, nonstrict) == 1)
68 assert(utf8.len(s, pi, pi1 - 1, nonstrict) == 1)
69 assert(utf8.len(s, pi, -1, nonstrict) == l - i + 1)
70 assert(utf8.len(s, pi1, -1, nonstrict) == l - i)
71 assert(utf8.len(s, 1, pi, nonstrict) == i)
72 end
73
74 local i = 0
75 for p, c in utf8.codes(s, nonstrict) do
76 i = i + 1
77 assert(c == t[i] and p == utf8.offset(s, i))
78 assert(utf8.codepoint(s, p, p, nonstrict) == c)
79 end
80 assert(i == #t)
81
82 i = 0
83 for c in string.gmatch(s, utf8.charpattern) do
84 i = i + 1
85 assert(c == utf8.char(t[i]))
86 end
87 assert(i == #t)
88
89 for i = 1, l do
90 assert(utf8.offset(s, i) == utf8.offset(s, i - l - 1, #s + 1))
91 end
92
93end
94
95
96do -- error indication in utf8.len
97 local function check (s, p)
98 local a, b = utf8.len(s)
99 assert(not a and b == p)
100 end
101 check("abc\xE3def", 4)
102 check("\xF4\x9F\xBF", 1)
103 check("\xF4\x9F\xBF\xBF", 1)
104 -- spurious continuation bytes
105 check("汉字\x80", #("汉字") + 1)
106 check("\x80hello", 1)
107 check("hel\x80lo", 4)
108 check("汉字\xBF", #("汉字") + 1)
109 check("\xBFhello", 1)
110 check("hel\xBFlo", 4)
111end
112
113-- errors in utf8.codes
114do
115 local function errorcodes (s)
116 checkerror("invalid UTF%-8 code",
117 function ()
118 for c in utf8.codes(s) do assert(c) end
119 end)
120 end
121 errorcodes("ab\xff")
122 errorcodes("\u{110000}")
123 errorcodes("in\x80valid")
124 errorcodes("\xbfinvalid")
125 errorcodes("αλφ\xBFα")
126
127 -- calling interation function with invalid arguments
128 local f = utf8.codes("")
129 assert(f("", 2) == nil)
130 assert(f("", -1) == nil)
131 assert(f("", math.mininteger) == nil)
132
133end
134
135-- error in initial position for offset
136checkerror("position out of bounds", utf8.offset, "abc", 1, 5)
137checkerror("position out of bounds", utf8.offset, "abc", 1, -4)
138checkerror("position out of bounds", utf8.offset, "", 1, 2)
139checkerror("position out of bounds", utf8.offset, "", 1, -1)
140checkerror("continuation byte", utf8.offset, "𦧺", 1, 2)
141checkerror("continuation byte", utf8.offset, "𦧺", 1, 2)
142checkerror("continuation byte", utf8.offset, "\x80", 1)
143
144-- error in indices for len
145checkerror("out of bounds", utf8.len, "abc", 0, 2)
146checkerror("out of bounds", utf8.len, "abc", 1, 4)
147
148
149local s = "hello World"
150local t = {string.byte(s, 1, -1)}
151for i = 1, utf8.len(s) do assert(t[i] == string.byte(s, i)) end
152check(s, t)
153
154check("汉字/漢字", {27721, 23383, 47, 28450, 23383,})
155
156do
157 local s = "áéí\128"
158 local t = {utf8.codepoint(s,1,#s - 1)}
159 assert(#t == 3 and t[1] == 225 and t[2] == 233 and t[3] == 237)
160 checkerror("invalid UTF%-8 code", utf8.codepoint, s, 1, #s)
161 checkerror("out of bounds", utf8.codepoint, s, #s + 1)
162 t = {utf8.codepoint(s, 4, 3)}
163 assert(#t == 0)
164 checkerror("out of bounds", utf8.codepoint, s, -(#s + 1), 1)
165 checkerror("out of bounds", utf8.codepoint, s, 1, #s + 1)
166 -- surrogates
167 assert(utf8.codepoint("\u{D7FF}") == 0xD800 - 1)
168 assert(utf8.codepoint("\u{E000}") == 0xDFFF + 1)
169 assert(utf8.codepoint("\u{D800}", 1, 1, true) == 0xD800)
170 assert(utf8.codepoint("\u{DFFF}", 1, 1, true) == 0xDFFF)
171 assert(utf8.codepoint("\u{7FFFFFFF}", 1, 1, true) == 0x7FFFFFFF)
172end
173
174assert(utf8.char() == "")
175assert(utf8.char(0, 97, 98, 99, 1) == "\0abc\1")
176
177assert(utf8.codepoint(utf8.char(0x10FFFF)) == 0x10FFFF)
178assert(utf8.codepoint(utf8.char(0x7FFFFFFF), 1, 1, true) == (1<<31) - 1)
179
180checkerror("value out of range", utf8.char, 0x7FFFFFFF + 1)
181checkerror("value out of range", utf8.char, -1)
182
183local function invalid (s)
184 checkerror("invalid UTF%-8 code", utf8.codepoint, s)
185 assert(not utf8.len(s))
186end
187
188-- UTF-8 representation for 0x11ffff (value out of valid range)
189invalid("\xF4\x9F\xBF\xBF")
190
191-- surrogates
192invalid("\u{D800}")
193invalid("\u{DFFF}")
194
195-- overlong sequences
196invalid("\xC0\x80") -- zero
197invalid("\xC1\xBF") -- 0x7F (should be coded in 1 byte)
198invalid("\xE0\x9F\xBF") -- 0x7FF (should be coded in 2 bytes)
199invalid("\xF0\x8F\xBF\xBF") -- 0xFFFF (should be coded in 3 bytes)
200
201
202-- invalid bytes
203invalid("\x80") -- continuation byte
204invalid("\xBF") -- continuation byte
205invalid("\xFE") -- invalid byte
206invalid("\xFF") -- invalid byte
207
208
209-- empty string
210check("", {})
211
212-- minimum and maximum values for each sequence size
213s = "\0 \x7F\z
214 \xC2\x80 \xDF\xBF\z
215 \xE0\xA0\x80 \xEF\xBF\xBF\z
216 \xF0\x90\x80\x80 \xF4\x8F\xBF\xBF"
217s = string.gsub(s, " ", "")
218check(s, {0,0x7F, 0x80,0x7FF, 0x800,0xFFFF, 0x10000,0x10FFFF})
219
220do
221 -- original UTF-8 values
222 local s = "\u{4000000}\u{7FFFFFFF}"
223 assert(#s == 12)
224 check(s, {0x4000000, 0x7FFFFFFF}, true)
225
226 s = "\u{200000}\u{3FFFFFF}"
227 assert(#s == 10)
228 check(s, {0x200000, 0x3FFFFFF}, true)
229
230 s = "\u{10000}\u{1fffff}"
231 assert(#s == 8)
232 check(s, {0x10000, 0x1FFFFF}, true)
233end
234
235local x = "日本語a-4\0éó"
236check(x, {26085, 26412, 35486, 97, 45, 52, 0, 233, 243})
237
238
239-- Supplementary Characters
240check("𣲷𠜎𠱓ð¡»ð µ¼ab𠺢",
241 {0x23CB7, 0x2070E, 0x20C53, 0x2107B, 0x20D7C, 0x61, 0x62, 0x20EA2,})
242
243check("𨳊𩶘𦧺𨳒𥄫𤓓\xF4\x8F\xBF\xBF",
244 {0x28CCA, 0x29D98, 0x269FA, 0x28CD2, 0x2512B, 0x244D3, 0x10ffff})
245
246
247local i = 0
248for p, c in string.gmatch(x, "()(" .. utf8.charpattern .. ")") do
249 i = i + 1
250 assert(utf8.offset(x, i) == p)
251 assert(utf8.len(x, p) == utf8.len(x) - i + 1)
252 assert(utf8.len(c) == 1)
253 for j = 1, #c - 1 do
254 assert(utf8.offset(x, 0, p + j - 1) == p)
255 end
256end
257
258print'ok'
259
diff --git a/zig-lua/lua-5.4.7/testes/vararg.lua b/zig-lua/lua-5.4.7/testes/vararg.lua
new file mode 100644
index 0000000..1b02510
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/vararg.lua
@@ -0,0 +1,151 @@
1-- $Id: testes/vararg.lua $
2-- See Copyright Notice in file all.lua
3
4print('testing vararg')
5
6local 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
10end
11
12local 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
18end
19
20local function vararg (...) return {n = select('#', ...), ...} end
21
22local call = function (f, args) return f(table.unpack(args, 1, args.n)) end
23
24assert(f() == 0)
25assert(f({1,2,3}, 1, 2, 3) == 3)
26assert(f({"alo", nil, 45, f, nil}, "alo", nil, 45, f, nil) == 5)
27
28assert(vararg().n == 0)
29assert(vararg(nil, nil).n == 2)
30
31assert(c12(1,2)==55)
32local a,b = assert(call(c12, {1,2}))
33assert(a == 55 and b == 2)
34a = call(c12, {1,2;n=2})
35assert(a == 55 and b == 2)
36a = call(c12, {1,2;n=1})
37assert(not a)
38assert(c12(1,2,3) == false)
39local a = vararg(call(next, {_G,nil;n=2}))
40local b,c = next(_G)
41assert(a[1] == b and a[2] == c and a.n == 2)
42a = vararg(call(call, {c12, {1,2}}))
43assert(a.n == 2 and a[1] == 55 and a[2] == 2)
44a = call(print, {'+'})
45assert(a == nil)
46
47local t = {1, 10}
48function t:f (...) local arg = {...}; return self[...]+#arg end
49assert(t:f(1,4) == 3 and t:f(2) == 11)
50print('+')
51
52local lim = 20
53local i, a = 1, {}
54while i <= lim do a[i] = i+0.3; i=i+1 end
55
56function 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])
60end
61
62local function g (a,b,c)
63 assert(a == 1.3 and b == 2.3 and c == 3.3)
64end
65
66call(f, a)
67call(g, a)
68
69a = {}
70i = 1
71while i <= lim do a[i] = i; i=i+1 end
72assert(call(math.max, a) == lim)
73
74print("+")
75
76
77-- new-style varargs
78
79local function oneless (a, ...) return ... end
80
81function 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
92end
93
94a,b,c,d,e = assert(f(10,5,4,3,2,1))
95assert(a==5 and b==4 and c==3 and d==2 and e==1)
96
97a,b,c,d,e = f(4)
98assert(a==nil and b==nil and c==nil and d==nil and e==nil)
99
100
101-- varargs for main chunks
102local f = load[[ return {...} ]]
103local x = f(2,3)
104assert(x[1] == 2 and x[2] == 3 and x[3] == undef)
105
106
107f = 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
114assert(f("a", "b", nil, {}, assert))
115assert(f())
116
117a = {select(3, table.unpack{10,20,30,40})}
118assert(#a == 2 and a[1] == 30 and a[2] == 40)
119a = {select(1)}
120assert(next(a) == nil)
121a = {select(-1, 3, 5, 7)}
122assert(a[1] == 7 and a[2] == undef)
123a = {select(-2, 3, 5, 7)}
124assert(a[1] == 5 and a[2] == 7 and a[3] == undef)
125pcall(select, 10000)
126pcall(select, -10000)
127
128
129-- bug in 5.2.2
130
131function f(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10,
132p11, p12, p13, p14, p15, p16, p17, p18, p19, p20,
133p21, p22, p23, p24, p25, p26, p27, p28, p29, p30,
134p31, p32, p33, p34, p35, p36, p37, p38, p39, p40,
135p41, 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
138end
139
140-- assertion fail here
141f()
142
143-- missing arguments in tail call
144do
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)
149end
150print('OK')
151
diff --git a/zig-lua/lua-5.4.7/testes/verybig.lua b/zig-lua/lua-5.4.7/testes/verybig.lua
new file mode 100644
index 0000000..250ea79
--- /dev/null
+++ b/zig-lua/lua-5.4.7/testes/verybig.lua
@@ -0,0 +1,152 @@
1-- $Id: testes/verybig.lua $
2-- See Copyright Notice in file all.lua
3
4print "testing RK"
5
6-- testing opcodes with RK arguments larger than K limit
7local 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)
44end
45
46
47foo()
48foo = nil
49
50if _soft then return 10 end
51
52print "testing large programs (>64k)"
53
54-- template to create a very big test file
55local prog = [[$
56
57local a,b
58
59b = {$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
80assert(b.a50008 == 25004 and b["a11"] == -5.5)
81assert(b.a33007 == -16503.5 and b.a50009 == -25004.5)
82assert(b["b"..30024] == -0xffffff)
83
84function b:xxx (a,b) return a+b end
85assert(b:xxx(10, 12) == 22) -- pushself with non-constant index
86b["xxx"] = undef
87
88local s = 0; local n=0
89for 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
91assert(81800000.0 < s and s < 81860000 and n == 70001)
92
93a = nil; b = nil
94print'+'
95
96local function f(x) b=x end
97
98a = f{$3$} or 10
99
100assert(a==10)
101assert(b[1] == "a10" and b[2] == 5 and b[#b-1] == "a50009")
102
103
104function xxxx (x) return b[x] end
105
106assert(xxxx(3) == "a11")
107
108a = nil; b=nil
109xxxx = nil
110
111return 10
112
113]]
114
115-- functions to fill in the $n$
116
117local function sig (x)
118 return (x % 2 == 0) and '' or '-'
119end
120
121local F = {
122function () -- $1$
123 for i=10,50009 do
124 io.write('a', i, ' = ', sig(i), 5+((i-10)/2), ',\n')
125 end
126end,
127
128function () -- $2$
129 for i=30026,50009 do
130 io.write('b', i, ' = ', sig(i), 15013+((i-30026)/2), ',\n')
131 end
132end,
133
134function () -- $3$
135 for i=10,50009 do
136 io.write('"a', i, '", ', sig(i), 5+((i-10)/2), ',\n')
137 end
138end,
139}
140
141local file = os.tmpname()
142io.output(file)
143for s in string.gmatch(prog, "$([^$]+)") do
144 local n = tonumber(s)
145 if not n then io.write(s) else F[n]() end
146end
147io.close()
148local result = dofile(file)
149assert(os.remove(file))
150print'OK'
151return result
152