lua

A copy of the Lua development repository
Log | Files | Refs | README

api.lua (45968B)


      1 -- $Id: testes/api.lua $
      2 -- See Copyright Notice in file all.lua
      3 
      4 if T==nil then
      5   (Message or print)('\n >>> testC not active: skipping API tests <<<\n')
      6   return
      7 end
      8 
      9 local debug = require "debug"
     10 
     11 local pack = table.pack
     12 
     13 
     14 -- standard error message for memory errors
     15 local MEMERRMSG = "not enough memory"
     16 
     17 local 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
     20 end
     21 
     22 
     23 local function checkerr (msg, f, ...)
     24   local stat, err = pcall(f, ...)
     25   assert(not stat and string.find(err, msg))
     26 end
     27 
     28 
     29 print('testing C API')
     30 
     31 local a = T.testC("pushvalue R; return 1")
     32 assert(a == debug.getregistry())
     33 
     34 
     35 -- absindex
     36 assert(T.testC("settop 10; absindex -1; return 1") == 10)
     37 assert(T.testC("settop 5; absindex -5; return 1") == 1)
     38 assert(T.testC("settop 10; absindex 1; return 1") == 1)
     39 assert(T.testC("settop 10; absindex R; return 1") < -10)
     40 
     41 -- testing alignment
     42 a = T.d2s(12458954321123.0)
     43 assert(a == string.pack("d", 12458954321123.0))
     44 assert(T.s2d(a) == 12458954321123.0)
     45 
     46 local a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2")
     47 assert(a == 2 and b == 3 and not c)
     48 
     49 local f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2")
     50 a,b,c = f()
     51 assert(a == 2 and b == 3 and not c)
     52 
     53 -- test that all trues are equal
     54 a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3")
     55 assert(a == b and a == true and c == false)
     56 a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\
     57                       tobool -3; tobool -3; tobool -3; return 3"
     58 assert(a==false and b==true and c==false)
     59 
     60 
     61 a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40)
     62 assert(a == 40 and b == 5 and not c)
     63 
     64 local t = pack(T.testC("settop 5; return *", 2, 3))
     65 tcheck(t, {n=4,2,3})
     66 
     67 t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23))
     68 assert(t.n == 10 and t[1] == nil and t[10] == nil)
     69 
     70 t = pack(T.testC("remove -2; return *", 2, 3, 4))
     71 tcheck(t, {n=2,2,4})
     72 
     73 t = pack(T.testC("insert -1; return *", 2, 3))
     74 tcheck(t, {n=2,2,3})
     75 
     76 t = pack(T.testC("insert 3; return *", 2, 3, 4, 5))
     77 tcheck(t, {n=4,2,5,3,4})
     78 
     79 t = pack(T.testC("replace 2; return *", 2, 3, 4, 5))
     80 tcheck(t, {n=3,5,3,4})
     81 
     82 t = pack(T.testC("replace -2; return *", 2, 3, 4, 5))
     83 tcheck(t, {n=3,2,3,5})
     84 
     85 t = pack(T.testC("remove 3; return *", 2, 3, 4, 5))
     86 tcheck(t, {n=3,2,4,5})
     87 
     88 t = pack(T.testC("copy 3 4; return *", 2, 3, 4, 5))
     89 tcheck(t, {n=4,2,3,3,5})
     90 
     91 t = pack(T.testC("copy -3 -1; return *", 2, 3, 4, 5))
     92 tcheck(t, {n=4,2,3,4,3})
     93 
     94 do   -- 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})
    115 end
    116 
    117 
    118 -- testing warnings
    119 T.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
    129 do
    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 
    143 end
    144 
    145 t = 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))
    149 tcheck(t, {n=7,2,3,4,5,10,40,90})
    150 
    151 t = pack(T.testC("concat 5; return *", "alo", 2, 3, "joao", 12))
    152 tcheck(t, {n=1,"alo23joao12"})
    153 
    154 -- testing MULTRET
    155 t = pack(T.testC("call 2,-1; return *",
    156      function (a,b) return 1,2,3,4,a,b end, "alo", "joao"))
    157 tcheck(t, {n=6,1,2,3,4,"alo", "joao"})
    158 
    159 do  -- 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")
    165 end
    166 
    167 
    168 do  -- testing multipe returns
    169   local function foo (n)
    170     if n > 0 then return n, foo(n - 1) end
    171   end
    172 
    173   local t = {T.testC("call 1 10; return 10", foo, 20)}
    174   assert(t[1] == 20 and t[10] == 11 and t[11] == nil)
    175 
    176   local t = table.pack(T.testC("call 1 10; return 10", foo, 2))
    177   assert(t[1] == 2 and t[2] == 1 and t[3] == nil and t.n == 10)
    178 
    179   local t = {T.testC([[
    180     checkstack 300 "error"; call 1 250; return 250]], foo, 250)}
    181   assert(t[1] == 250 and t[250] == 1 and t[251] == nil)
    182 end
    183 
    184 
    185 -- testing globals
    186 _G.AA = 14; _G.BB = "a31"
    187 local a = {T.testC[[
    188   getglobal AA;
    189   getglobal BB;
    190   getglobal BB;
    191   setglobal AA;
    192   return *
    193 ]]}
    194 assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.AA == "a31")
    195 
    196 _G.AA, _G.BB = nil
    197 
    198 -- testing arith
    199 assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5)
    200 assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10)
    201 assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200)
    202 assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000)
    203 assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5)
    204 assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10)
    205 assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200)
    206 assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000)
    207 assert(T.testC("arith /; return 1", 2, 0) == 10.0/0)
    208 a = T.testC("pushnum 10; pushint 3; arith \\; return 1")
    209 assert(a == 3.0 and math.type(a) == "float")
    210 a = T.testC("pushint 10; pushint 3; arith \\; return 1")
    211 assert(a == 3 and math.type(a) == "integer")
    212 a = assert(T.testC("pushint 10; pushint 3; arith +; return 1"))
    213 assert(a == 13 and math.type(a) == "integer")
    214 a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1"))
    215 assert(a == 13 and math.type(a) == "float")
    216 a,b,c = T.testC([[pushnum 1;
    217                   pushstring 10; arith _;
    218                   pushstring 5; return 3]])
    219 assert(a == 1 and b == -10 and c == "5")
    220 local mt = {
    221       __add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end,
    222       __mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end,
    223       __unm = function (a) return setmetatable({a[1]* 2}, mt) end}
    224 a,b,c = setmetatable({4}, mt),
    225         setmetatable({8}, mt),
    226         setmetatable({-3}, mt)
    227 local x,y,z = T.testC("arith +; return 2", 10, a, b)
    228 assert(x == 10 and y[1] == 12 and z == nil)
    229 assert(T.testC("arith %; return 1", a, c)[1] == 4%-3)
    230 assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] ==
    231                8 % (4 + (-3)*2))
    232 
    233 -- errors in arithmetic
    234 checkerr("divide by zero", T.testC, "arith \\", 10, 0)
    235 checkerr("%%0", T.testC, "arith %", 10, 0)
    236 
    237 
    238 -- testing lessthan and lessequal
    239 assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2))
    240 assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2))
    241 assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2))
    242 assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2))
    243 assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2))
    244 assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2"))
    245 assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2"))
    246 
    247 -- non-valid indices produce false
    248 assert(not T.testC("compare LT 1 4, return 1"))
    249 assert(not T.testC("compare LE 9 1, return 1"))
    250 assert(not T.testC("compare EQ 9 9, return 1"))
    251 
    252 local b = {__lt = function (a,b) return a[1] < b[1] end}
    253 local a1,a3,a4 = setmetatable({1}, b),
    254                  setmetatable({3}, b),
    255                  setmetatable({4}, b)
    256 assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2))
    257 assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2))
    258 assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2))
    259 a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20)
    260 assert(a == 20 and b == false)
    261 a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20)
    262 assert(a == 20 and b == false)
    263 a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20)
    264 assert(a == 20 and b == true)
    265 
    266 
    267 do  -- testing lessthan and lessequal with metamethods
    268   local mt = {__lt = function (a,b) return a[1] < b[1] end,
    269               __le = function (a,b) return a[1] <= b[1] end,
    270               __eq = function (a,b) return a[1] == b[1] end}
    271   local function O (x)
    272     return setmetatable({x}, mt)
    273   end
    274 
    275   local a, b = T.testC("compare LT 2 3; pushint 10; return 2", O(1), O(2))
    276   assert(a == true and b == 10)
    277   local a, b = T.testC("compare LE 2 3; pushint 10; return 2", O(3), O(2))
    278   assert(a == false and b == 10)
    279   local a, b = T.testC("compare EQ 2 3; pushint 10; return 2", O(3), O(3))
    280   assert(a == true and b == 10)
    281 end
    282 
    283 -- testing length
    284 local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
    285 a,b,c = T.testC([[
    286    len 2;
    287    Llen 2;
    288    objsize 2;
    289    return 3
    290 ]], t)
    291 assert(a == 20 and b == 20 and c == 0)
    292 
    293 t.x = "234"; t[1] = 20
    294 a,b,c = T.testC([[
    295    len 2;
    296    Llen 2;
    297    objsize 2;
    298    return 3
    299 ]], t)
    300 assert(a == "234" and b == 234 and c == 1)
    301 
    302 t.x = print; t[1] = 20
    303 a,c = T.testC([[
    304    len 2;
    305    objsize 2;
    306    return 2
    307 ]], t)
    308 assert(a == print and c == 1)
    309 
    310 
    311 -- testing __concat
    312 
    313 a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end})
    314 x,y = T.testC([[
    315   pushnum 5
    316   pushvalue 2;
    317   pushvalue 2;
    318   concat 2;
    319   pushvalue -2;
    320   return 2;
    321 ]], a, a)
    322 assert(x == a..a and y == 5)
    323 
    324 -- concat with 0 elements
    325 assert(T.testC("concat 0; return 1") == "")
    326 
    327 -- concat with 1 element
    328 assert(T.testC("concat 1; return 1", "xuxu") == "xuxu")
    329 
    330 
    331 
    332 -- testing lua_is
    333 
    334 local function B (x) return x and 1 or 0 end
    335 
    336 local function count (x, n)
    337   n = n or 2
    338   local prog = [[
    339     isnumber %d;
    340     isstring %d;
    341     isfunction %d;
    342     iscfunction %d;
    343     istable %d;
    344     isuserdata %d;
    345     isnil %d;
    346     isnull %d;
    347     return 8
    348   ]]
    349   prog = string.format(prog, n, n, n, n, n, n, n, n)
    350   local a,b,c,d,e,f,g,h = T.testC(prog, x)
    351   return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h))
    352 end
    353 
    354 assert(count(3) == 2)
    355 assert(count('alo') == 1)
    356 assert(count('32') == 2)
    357 assert(count({}) == 1)
    358 assert(count(print) == 2)
    359 assert(count(function () end) == 1)
    360 assert(count(nil) == 1)
    361 assert(count(io.stdin) == 1)
    362 assert(count(nil, 15) == 100)
    363 
    364 
    365 -- testing lua_to...
    366 
    367 local function to (s, x, n)
    368   n = n or 2
    369   return T.testC(string.format("%s %d; return 1", s, n), x)
    370 end
    371 
    372 local null = T.pushuserdata(0)
    373 local hfunc = string.gmatch("", "")    -- a "heavy C function" (with upvalues)
    374 assert(debug.getupvalue(hfunc, 1))
    375 assert(to("tostring", {}) == nil)
    376 assert(to("tostring", "alo") == "alo")
    377 assert(to("tostring", 12) == "12")
    378 assert(to("tostring", 12, 3) == nil)
    379 assert(to("objsize", {}) == 0)
    380 assert(to("objsize", {1,2,3}) == 3)
    381 assert(to("objsize", "alo\0\0a") == 6)
    382 assert(to("objsize", T.newuserdata(0)) == 0)
    383 assert(to("objsize", T.newuserdata(101)) == 101)
    384 assert(to("objsize", 124) == 0)
    385 assert(to("objsize", true) == 0)
    386 assert(to("tonumber", {}) == 0)
    387 assert(to("tonumber", "12") == 12)
    388 assert(to("tonumber", "s2") == 0)
    389 assert(to("tonumber", 1, 20) == 0)
    390 assert(to("topointer", 10) == null)
    391 assert(to("topointer", true) == null)
    392 assert(to("topointer", nil) == null)
    393 assert(to("topointer", "abc") ~= null)
    394 assert(to("topointer", string.rep("x", 10)) ==
    395        to("topointer", string.rep("x", 10)))    -- short strings
    396 do    -- long strings
    397   local s1 = string.rep("x", 300)
    398   local s2 = string.rep("x", 300)
    399   assert(to("topointer", s1) ~= to("topointer", s2))
    400 end
    401 assert(to("topointer", T.pushuserdata(20)) ~= null)
    402 assert(to("topointer", io.read) ~= null)           -- light C function
    403 assert(to("topointer", hfunc) ~= null)        -- "heavy" C function
    404 assert(to("topointer", function () end) ~= null)   -- Lua function
    405 assert(to("topointer", io.stdin) ~= null)   -- full userdata
    406 assert(to("func2num", 20) == 0)
    407 assert(to("func2num", T.pushuserdata(10)) == 0)
    408 assert(to("func2num", io.read) ~= 0)     -- light C function
    409 assert(to("func2num", hfunc) ~= 0)  -- "heavy" C function (with upvalue)
    410 a = to("tocfunction", math.deg)
    411 assert(a(3) == math.deg(3) and a == math.deg)
    412 
    413 
    414 print("testing panic function")
    415 do
    416   -- trivial error
    417   assert(T.checkpanic("pushstring hi; error") == "hi")
    418 
    419  -- thread status inside panic (bug in 5.4.4)
    420   assert(T.checkpanic("pushstring hi; error", "threadstatus; return 2") ==
    421          "ERRRUN")
    422 
    423   -- using the stack inside panic
    424   assert(T.checkpanic("pushstring hi; error;",
    425     [[checkstack 5 XX
    426       pushstring ' alo'
    427       pushstring ' mundo'
    428       concat 3]]) == "hi alo mundo")
    429 
    430   -- "argerror" without frames
    431   assert(T.checkpanic("loadstring 4 name bt") ==
    432       "bad argument #4 (string expected, got no value)")
    433 
    434 
    435   -- memory error
    436   T.totalmem(T.totalmem()+10000)   -- set low memory limit (+10k)
    437   assert(T.checkpanic("newuserdata 20000") == MEMERRMSG)
    438   T.totalmem(0)          -- restore high limit
    439 
    440   -- memory error + thread status
    441   local x = T.checkpanic(
    442     [[ alloccount 0    # force a memory error in next line
    443        newtable
    444     ]],
    445     [[
    446        alloccount -1   # allow free allocations again
    447        pushstring XX
    448        threadstatus
    449        concat 2     # to make sure message came from here
    450        return 1
    451     ]])
    452   T.alloccount()
    453   assert(x == "XX" .. "not enough memory")
    454 
    455   -- stack error
    456   if not _soft then
    457     local msg = T.checkpanic[[
    458       pushstring "function f() f() end"
    459       loadstring -1 name t; call 0 0
    460       getglobal f; call 0 0
    461     ]]
    462     assert(string.find(msg, "stack overflow"))
    463   end
    464 
    465   -- exit in panic still close to-be-closed variables
    466   assert(T.checkpanic([[
    467     pushstring "return {__close = function () Y = 'ho'; end}"
    468     newtable
    469     loadstring -2 name t
    470     call 0 1
    471     setmetatable -2
    472     toclose -1
    473     pushstring "hi"
    474     error
    475   ]],
    476   [[
    477     getglobal Y
    478     concat 2         # concat original error with global Y
    479   ]]) == "hiho")
    480 
    481 
    482 end
    483 
    484 -- testing deep C stack
    485 if not _soft then
    486   print("testing stack overflow")
    487   collectgarbage("stop")
    488   checkerr("XXXX", T.testC, "checkstack 1000023 XXXX")   -- too deep
    489   -- too deep (with no message)
    490   checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''")
    491   local s = string.rep("pushnil;checkstack 1 XX;", 1000000)
    492   checkerr("overflow", T.testC, s)
    493   collectgarbage("restart")
    494   print'+'
    495 end
    496 
    497 
    498 
    499 local lim = _soft and 500 or 12000
    500 local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"}
    501 for i = 1,lim do
    502   prog[#prog + 1] = "pushnum " .. i
    503   prog[#prog + 1] = "pushnum " .. i * 10
    504 end
    505 
    506 prog[#prog + 1] = "rawgeti R !G"  -- get global table in registry
    507 prog[#prog + 1] = "insert " .. -(2*lim + 2)
    508 
    509 for i = 1,lim do
    510   prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1)
    511 end
    512 
    513 prog[#prog + 1] = "return 2"
    514 
    515 prog = table.concat(prog, ";")
    516 local g, t = T.testC(prog)
    517 assert(g == _G)
    518 for i = 1,lim do assert(t[i] == i*10); t[i] = undef end
    519 assert(next(t) == nil)
    520 prog, g, t = nil
    521 
    522 do   -- shrink stack
    523   local m1, m2 = 0, collectgarbage"count" * 1024
    524   while m1 ~= m2 do    -- repeat until stable
    525     collectgarbage()
    526     m1 = m2
    527     m2 = collectgarbage"count" * 1024
    528   end
    529 end
    530 
    531 
    532 -- testing errors
    533 
    534 a = T.testC([[
    535   loadstring 2 name t; pcall 0 1 0;
    536   pushvalue 3; insert -2; pcall 1 1 0;
    537   pcall 0 0 0;
    538   return 1
    539 ]], "XX=150", function (a) assert(a==nil); return 3 end)
    540 
    541 assert(type(a) == 'string' and XX == 150)
    542 _G.XX = nil
    543 
    544 local function check3(p, ...)
    545   local arg = {...}
    546   assert(#arg == 3)
    547   assert(string.find(arg[3], p))
    548 end
    549 check3(":1:", T.testC("loadstring 2 name t; return *", "x="))
    550 check3("%.", T.testC("loadfile 2; return *", "."))
    551 check3("xxxx", T.testC("loadfile 2; return *", "xxxx"))
    552 
    553 -- test errors in non protected threads
    554 local function checkerrnopro (code, msg)
    555   local th = coroutine.create(function () end)  -- create new thread
    556   local stt, err = pcall(T.testC, th, code)   -- run code there
    557   assert(not stt and string.find(err, msg))
    558 end
    559 
    560 
    561 do
    562   print("testing load of binaries in fixed buffers")
    563   local source = {}
    564   local N = 1000
    565   -- create a somewhat "large" source
    566   for i = 1, N do source[i] = "X = X + 1; " end
    567   -- add a long string to the source
    568   source[#source + 1] = string.format("Y = '%s'", string.rep("a", N));
    569   source = table.concat(source)
    570   -- give chunk an explicit name to avoid using source as name
    571   source = load(source, "name1")
    572   -- dump without debug information
    573   source = string.dump(source, true)
    574   -- each "X=X+1" generates 4 opcodes with 4 bytes each, plus the string
    575   assert(#source > N * 4 * 4 + N)
    576   collectgarbage(); collectgarbage()
    577   local m1 = collectgarbage"count" * 1024
    578   -- load dump using fixed buffer
    579   local code = T.testC([[
    580     loadstring 2 name B;
    581     return 1
    582   ]], source)
    583   collectgarbage()
    584   local m2 = collectgarbage"count" * 1024
    585   -- load used fewer than 400 bytes. Code alone has more than 3*N bytes,
    586   -- and string literal has N bytes. Both were not loaded.
    587   assert(m2 > m1 and m2 - m1 < 400)
    588   X = 0; code(); assert(X == N and Y == string.rep("a", N))
    589   X = nil; Y = nil
    590 
    591   -- testing debug info in fixed buffers
    592   source = {"X = 0"}
    593   for i = 2, 300 do source[i] = "X = X + 1" end
    594   source[#source + 1] = "X = X + {}"   -- error in last line
    595   source = table.concat(source, "\n")
    596   source = load(source, "name1")
    597   source = string.dump(source)
    598   -- load dump using fixed buffer
    599   local code = T.testC([[
    600     loadstring 2 name B;
    601     return 1
    602   ]], source)
    603   checkerr(":301:", code)    -- correct line information
    604 end
    605 
    606 
    607 if not _soft then
    608   collectgarbage("stop")   -- avoid __gc with full stack
    609   checkerrnopro("pushnum 3; call 0 0", "attempt to call")
    610   print"testing stack overflow in unprotected thread"
    611   function F () F() end
    612   checkerrnopro("getglobal 'F'; call 0 0;", "stack overflow")
    613   F = nil
    614   collectgarbage("restart")
    615 end
    616 print"+"
    617 
    618 
    619 -- testing table access
    620 
    621 do   -- getp/setp
    622   local a = {}
    623   local a1 = T.testC("rawsetp 2 1; return 1", a, 20)
    624   assert(a == a1)
    625   assert(a[T.pushuserdata(1)] == 20)
    626   local a1, res = T.testC("rawgetp -1 1; return 2", a)
    627   assert(a == a1 and res == 20)
    628 end
    629 
    630 
    631 do  -- using the table itself as index
    632   local a = {}
    633   a[a] = 10
    634   local prog = "gettable -1; return *"
    635   local res = {T.testC(prog, a)}
    636   assert(#res == 2 and res[1] == prog and res[2] == 10)
    637 
    638   local prog = "settable -2; return *"
    639   local res = {T.testC(prog, a, 20)}
    640   assert(a[a] == 20)
    641   assert(#res == 1 and res[1] == prog)
    642 
    643   -- raw
    644   a[a] = 10
    645   local prog = "rawget -1; return *"
    646   local res = {T.testC(prog, a)}
    647   assert(#res == 2 and res[1] == prog and res[2] == 10)
    648 
    649   local prog = "rawset -2; return *"
    650   local res = {T.testC(prog, a, 20)}
    651   assert(a[a] == 20)
    652   assert(#res == 1 and res[1] == prog)
    653 
    654   -- using the table as the value to set
    655   local prog = "rawset -1; return *"
    656   local res = {T.testC(prog, 30, a)}
    657   assert(a[30] == a)
    658   assert(#res == 1 and res[1] == prog)
    659 
    660   local prog = "settable -1; return *"
    661   local res = {T.testC(prog, 40, a)}
    662   assert(a[40] == a)
    663   assert(#res == 1 and res[1] == prog)
    664 
    665   local prog = "rawseti -1 100; return *"
    666   local res = {T.testC(prog, a)}
    667   assert(a[100] == a)
    668   assert(#res == 1 and res[1] == prog)
    669 
    670   local prog = "seti -1 200; return *"
    671   local res = {T.testC(prog, a)}
    672   assert(a[200] == a)
    673   assert(#res == 1 and res[1] == prog)
    674 end
    675 
    676 a = {x=0, y=12}
    677 x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2",
    678                 a, 3, "y", 4, "x")
    679 assert(x == 0 and y == 12)
    680 T.testC("settable -5", a, 3, 4, "x", 15)
    681 assert(a.x == 15)
    682 a[a] = print
    683 x = T.testC("gettable 2; return 1", a)  -- table and key are the same object!
    684 assert(x == print)
    685 T.testC("settable 2", a, "x")    -- table and key are the same object!
    686 assert(a[a] == "x")
    687 
    688 b = setmetatable({p = a}, {})
    689 getmetatable(b).__index = function (t, i) return t.p[i] end
    690 local k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x")
    691 assert(x == 15 and k == 35)
    692 k = T.testC("getfield 2 y, return 1", b)
    693 assert(k == 12)
    694 getmetatable(b).__index = function (t, i) return a[i] end
    695 getmetatable(b).__newindex = function (t, i,v ) a[i] = v end
    696 y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b)
    697 assert(y == 12)
    698 k = T.testC("settable -5, return 1", b, 3, 4, "x", 16)
    699 assert(a.x == 16 and k == 4)
    700 a[b] = 'xuxu'
    701 y = T.testC("gettable 2, return 1", b)
    702 assert(y == 'xuxu')
    703 T.testC("settable 2", b, 19)
    704 assert(a[b] == 19)
    705 
    706 --
    707 do   -- testing getfield/setfield with long keys
    708   local t = {_012345678901234567890123456789012345678901234567890123456789 = 32}
    709   local a = T.testC([[
    710     getfield 2 _012345678901234567890123456789012345678901234567890123456789
    711     return 1
    712   ]], t)
    713   assert(a == 32)
    714   local a = T.testC([[
    715     pushnum 33
    716     setglobal _012345678901234567890123456789012345678901234567890123456789
    717   ]])
    718   assert(_012345678901234567890123456789012345678901234567890123456789 == 33)
    719   _012345678901234567890123456789012345678901234567890123456789 = nil
    720 end
    721 
    722 -- testing next
    723 a = {}
    724 t = pack(T.testC("next; return *", a, nil))
    725 tcheck(t, {n=1,a})
    726 a = {a=3}
    727 t = pack(T.testC("next; return *", a, nil))
    728 tcheck(t, {n=3,a,'a',3})
    729 t = pack(T.testC("next; pop 1; next; return *", a, nil))
    730 tcheck(t, {n=1,a})
    731 
    732 
    733 
    734 -- testing upvalues
    735 
    736 do
    737   local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
    738   t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]])
    739   assert(b == 10 and c == 20 and type(t) == 'table')
    740   a, b = A([[tostring U3; tonumber U4; return 2]])
    741   assert(a == nil and b == 0)
    742   A([[pushnum 100; pushnum 200; replace U2; replace U1]])
    743   b, c = A([[pushvalue U1; pushvalue U2; return 2]])
    744   assert(b == 100 and c == 200)
    745   A([[replace U2; replace U1]], {x=1}, {x=2})
    746   b, c = A([[pushvalue U1; pushvalue U2; return 2]])
    747   assert(b.x == 1 and c.x == 2)
    748   T.checkmemory()
    749 end
    750 
    751 
    752 -- testing absent upvalues from C-function pointers
    753 assert(T.testC[[isnull U1; return 1]] == true)
    754 assert(T.testC[[isnull U100; return 1]] == true)
    755 assert(T.testC[[pushvalue U1; return 1]] == nil)
    756 
    757 local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
    758 assert(T.upvalue(f, 1) == 10 and
    759        T.upvalue(f, 2) == 20 and
    760        T.upvalue(f, 3) == nil)
    761 T.upvalue(f, 2, "xuxu")
    762 assert(T.upvalue(f, 2) == "xuxu")
    763 
    764 
    765 -- large closures
    766 do
    767   local A = "checkstack 300 msg;" ..
    768             string.rep("pushnum 10;", 255) ..
    769             "pushcclosure 255; return 1"
    770   A = T.testC(A)
    771   for i=1,255 do
    772     assert(A(("pushvalue U%d; return 1"):format(i)) == 10)
    773   end
    774   assert(A("isnull U256; return 1"))
    775   assert(not A("isnil U256; return 1"))
    776 end
    777 
    778 
    779 
    780 -- testing get/setuservalue
    781 -- bug in 5.1.2
    782 checkerr("got number", debug.setuservalue, 3, {})
    783 checkerr("got nil", debug.setuservalue, nil, {})
    784 checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {})
    785 
    786 -- testing multiple user values
    787 local b = T.newuserdata(0, 10)
    788 for i = 1, 10 do
    789   local v, p = debug.getuservalue(b, i)
    790   assert(v == nil and p)
    791 end
    792 do   -- indices out of range
    793   local v, p = debug.getuservalue(b, -2)
    794   assert(v == nil and not p)
    795   local v, p = debug.getuservalue(b, 11)
    796   assert(v == nil and not p)
    797 end
    798 local t = {true, false, 4.56, print, {}, b, "XYZ"}
    799 for k, v in ipairs(t) do
    800   debug.setuservalue(b, v, k)
    801 end
    802 for k, v in ipairs(t) do
    803   local v1, p = debug.getuservalue(b, k)
    804   assert(v1 == v and p)
    805 end
    806 
    807 assert(not debug.getuservalue(4))
    808 
    809 debug.setuservalue(b, function () return 10 end, 10)
    810 collectgarbage()   -- function should not be collected
    811 assert(debug.getuservalue(b, 10)() == 10)
    812 
    813 debug.setuservalue(b, 134)
    814 collectgarbage()   -- number should not be a problem for collector
    815 assert(debug.getuservalue(b) == 134)
    816 
    817 
    818 -- test barrier for uservalues
    819 do
    820   local oldmode = collectgarbage("incremental")
    821   T.gcstate("enteratomic")
    822   assert(T.gccolor(b) == "black")
    823   debug.setuservalue(b, {x = 100})
    824   T.gcstate("pause")  -- complete collection
    825   assert(debug.getuservalue(b).x == 100)  -- uvalue should be there
    826   collectgarbage(oldmode)
    827 end
    828 
    829 -- long chain of userdata
    830 for i = 1, 1000 do
    831   local bb = T.newuserdata(0, 1)
    832   debug.setuservalue(bb, b)
    833   b = bb
    834 end
    835 collectgarbage()     -- nothing should not be collected
    836 for i = 1, 1000 do
    837   b = debug.getuservalue(b)
    838 end
    839 assert(debug.getuservalue(b).x == 100)
    840 b = nil
    841 
    842 
    843 -- testing locks (refs)
    844 
    845 -- reuse of references
    846 local i = T.ref{}
    847 T.unref(i)
    848 assert(T.ref{} == i)
    849 
    850 local Arr = {}
    851 local Lim = 100
    852 for i=1,Lim do   -- lock many objects
    853   Arr[i] = T.ref({})
    854 end
    855 
    856 assert(T.ref(nil) == -1 and T.getref(-1) == nil)
    857 T.unref(-1); T.unref(-1)
    858 
    859 for i=1,Lim do   -- unlock all them
    860   T.unref(Arr[i])
    861 end
    862 
    863 local function printlocks ()
    864   local f = T.makeCfunc("gettable R; return 1")
    865   local n = f("n")
    866   print("n", n)
    867   for i=0,n do
    868     print(i, f(i))
    869   end
    870 end
    871 
    872 
    873 for i=1,Lim do   -- lock many objects
    874   Arr[i] = T.ref({})
    875 end
    876 
    877 for i=1,Lim,2 do   -- unlock half of them
    878   T.unref(Arr[i])
    879 end
    880 
    881 assert(type(T.getref(Arr[2])) == 'table')
    882 
    883 
    884 assert(T.getref(-1) == nil)
    885 
    886 
    887 a = T.ref({})
    888 
    889 collectgarbage()
    890 
    891 assert(type(T.getref(a)) == 'table')
    892 
    893 
    894 -- colect in cl the `val' of all collected userdata
    895 local tt = {}
    896 local cl = {n=0}
    897 A = nil; B = nil
    898 local F
    899 F = function (x)
    900   local udval = T.udataval(x)
    901   table.insert(cl, udval)
    902   local d = T.newuserdata(100)   -- create garbage
    903   d = nil
    904   assert(debug.getmetatable(x).__gc == F)
    905   assert(load("table.insert({}, {})"))()   -- create more garbage
    906   assert(not collectgarbage())    -- GC during GC (no op)
    907   local dummy = {}    -- create more garbage during GC
    908   if A ~= nil then
    909     assert(type(A) == "userdata")
    910     assert(T.udataval(A) == B)
    911     debug.getmetatable(A)    -- just access it
    912   end
    913   A = x   -- ressurect userdata
    914   B = udval
    915   return 1,2,3
    916 end
    917 tt.__gc = F
    918 
    919 
    920 -- test whether udate collection frees memory in the right time
    921 do
    922   collectgarbage();
    923   collectgarbage();
    924   local x = collectgarbage("count");
    925   local a = T.newuserdata(5001)
    926   assert(T.testC("objsize 2; return 1", a) == 5001)
    927   assert(collectgarbage("count") >= x+4)
    928   a = nil
    929   collectgarbage();
    930   assert(collectgarbage("count") <= x+1)
    931   -- udata without finalizer
    932   x = collectgarbage("count")
    933   collectgarbage("stop")
    934   for i=1,1000 do T.newuserdata(0) end
    935   assert(collectgarbage("count") > x+10)
    936   collectgarbage()
    937   assert(collectgarbage("count") <= x+1)
    938   -- udata with finalizer
    939   collectgarbage()
    940   x = collectgarbage("count")
    941   collectgarbage("stop")
    942   a = {__gc = function () end}
    943   for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end
    944   assert(collectgarbage("count") >= x+10)
    945   collectgarbage()  -- this collection only calls TM, without freeing memory
    946   assert(collectgarbage("count") >= x+10)
    947   collectgarbage()  -- now frees memory
    948   assert(collectgarbage("count") <= x+1)
    949   collectgarbage("restart")
    950 end
    951 
    952 
    953 collectgarbage("stop")
    954 
    955 -- create 3 userdatas with tag `tt'
    956 a = T.newuserdata(0); debug.setmetatable(a, tt); local na = T.udataval(a)
    957 b = T.newuserdata(0); debug.setmetatable(b, tt); local nb = T.udataval(b)
    958 c = T.newuserdata(0); debug.setmetatable(c, tt); local nc = T.udataval(c)
    959 
    960 -- create userdata without meta table
    961 x = T.newuserdata(4)
    962 y = T.newuserdata(0)
    963 
    964 checkerr("FILE%* expected, got userdata", io.input, a)
    965 checkerr("FILE%* expected, got userdata", io.input, x)
    966 
    967 assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil)
    968 
    969 -- Test references in an arbitrary table
    970 local reftable = {}
    971 local d = T.ref(a, reftable);
    972 local e = T.ref(b, reftable);
    973 local f = T.ref(c, reftable);
    974 t = {T.getref(d, reftable), T.getref(e, reftable), T.getref(f, reftable)}
    975 assert(t[1] == a and t[2] == b and t[3] == c)
    976 
    977 t=nil; a=nil; c=nil;
    978 T.unref(e, reftable); T.unref(f, reftable)
    979 
    980 collectgarbage()
    981 
    982 -- check that unref objects have been collected
    983 assert(#cl == 1 and cl[1] == nc)
    984 
    985 x = T.getref(d, reftable)
    986 assert(type(x) == 'userdata' and debug.getmetatable(x) == tt)
    987 x =nil
    988 tt.b = b  -- create cycle
    989 tt=nil    -- frees tt for GC
    990 A = nil
    991 b = nil
    992 T.unref(d, reftable);
    993 local n5 = T.newuserdata(0)
    994 debug.setmetatable(n5, {__gc=F})
    995 n5 = T.udataval(n5)
    996 collectgarbage()
    997 assert(#cl == 4)
    998 -- check order of collection
    999 assert(cl[2] == n5 and cl[3] == nb and cl[4] == na)
   1000 
   1001 -- reuse a reference in 'reftable'
   1002 T.unref(T.ref(23, reftable), reftable)
   1003 
   1004 do  -- check reftable
   1005   local count = 0
   1006   local i = 1
   1007   while reftable[i] ~= 0 do
   1008     i = reftable[i]  -- traverse linked list of free references
   1009     count = count + 1
   1010   end
   1011   -- maximum number of simultaneously locked objects was 3
   1012   assert(count == 3 and #reftable  == 3 + 1)  -- +1 for reserved [1]
   1013 end
   1014 
   1015 
   1016 collectgarbage"restart"
   1017 
   1018 
   1019 a, na = {}, {}
   1020 for i=30,1,-1 do
   1021   a[i] = T.newuserdata(0)
   1022   debug.setmetatable(a[i], {__gc=F})
   1023   na[i] = T.udataval(a[i])
   1024 end
   1025 cl = {}
   1026 a = nil; collectgarbage()
   1027 assert(#cl == 30)
   1028 for i=1,30 do assert(cl[i] == na[i]) end
   1029 na = nil
   1030 
   1031 
   1032 for i=2,Lim,2 do   -- unlock the other half
   1033   T.unref(Arr[i])
   1034 end
   1035 
   1036 x = T.newuserdata(41); debug.setmetatable(x, {__gc=F})
   1037 assert(T.testC("objsize 2; return 1", x) == 41)
   1038 cl = {}
   1039 a = {[x] = 1}
   1040 x = T.udataval(x)
   1041 collectgarbage()
   1042 -- old `x' cannot be collected (`a' still uses it)
   1043 assert(#cl == 0)
   1044 for n in pairs(a) do a[n] = undef end
   1045 collectgarbage()
   1046 assert(#cl == 1 and cl[1] == x)   -- old `x' must be collected
   1047 
   1048 -- testing lua_equal
   1049 assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20))
   1050 assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo"))
   1051 assert(T.testC("compare EQ 2 3; return 1", nil, nil))
   1052 assert(not T.testC("compare EQ 2 3; return 1", {}, {}))
   1053 assert(not T.testC("compare EQ 2 3; return 1"))
   1054 assert(not T.testC("compare EQ 2 3; return 1", 3))
   1055 
   1056 -- testing lua_equal with fallbacks
   1057 do
   1058   local map = {}
   1059   local t = {__eq = function (a,b) return map[a] == map[b] end}
   1060   local function f(x)
   1061     local u = T.newuserdata(0)
   1062     debug.setmetatable(u, t)
   1063     map[u] = x
   1064     return u
   1065   end
   1066   assert(f(10) == f(10))
   1067   assert(f(10) ~= f(11))
   1068   assert(T.testC("compare EQ 2 3; return 1", f(10), f(10)))
   1069   assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20)))
   1070   t.__eq = nil
   1071   assert(f(10) ~= f(10))
   1072 end
   1073 
   1074 print'+'
   1075 
   1076 
   1077 
   1078 -- testing changing hooks during hooks
   1079 _G.TT = {}
   1080 T.sethook([[
   1081   # set a line hook after 3 count hooks
   1082   sethook 4 0 '
   1083     getglobal TT;
   1084     pushvalue -3; append -2
   1085     pushvalue -2; append -2
   1086   ']], "c", 3)
   1087 local a = 1   -- counting
   1088 a = 1   -- counting
   1089 a = 1   -- count hook (set line hook)
   1090 a = 1   -- line hook
   1091 a = 1   -- line hook
   1092 debug.sethook()
   1093 local t = _G.TT
   1094 assert(t[1] == "line")
   1095 local line = t[2]
   1096 assert(t[3] == "line" and t[4] == line + 1)
   1097 assert(t[5] == "line" and t[6] == line + 2)
   1098 assert(t[7] == nil)
   1099 _G.TT = nil
   1100 
   1101 
   1102 -------------------------------------------------------------------------
   1103 do   -- testing errors during GC
   1104   warn("@off")
   1105   collectgarbage("stop")
   1106   local a = {}
   1107   for i=1,20 do
   1108     a[i] = T.newuserdata(i)   -- creates several udata
   1109   end
   1110   for i=1,20,2 do   -- mark half of them to raise errors during GC
   1111     debug.setmetatable(a[i],
   1112       {__gc = function (x) error("@expected error in gc") end})
   1113   end
   1114   for i=2,20,2 do   -- mark the other half to count and to create more garbage
   1115     debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end})
   1116   end
   1117   a = nil
   1118   _G.A = 0
   1119   collectgarbage()
   1120   assert(A == 10)  -- number of normal collections
   1121   collectgarbage("restart")
   1122   warn("@on")
   1123 end
   1124 _G.A = nil
   1125 -------------------------------------------------------------------------
   1126 -- test for userdata vals
   1127 do
   1128   local a = {}; local lim = 30
   1129   for i=0,lim do a[i] = T.pushuserdata(i) end
   1130   for i=0,lim do assert(T.udataval(a[i]) == i) end
   1131   for i=0,lim do assert(T.pushuserdata(i) == a[i]) end
   1132   for i=0,lim do a[a[i]] = i end
   1133   for i=0,lim do a[T.pushuserdata(i)] = i end
   1134   assert(type(tostring(a[1])) == "string")
   1135 end
   1136 
   1137 
   1138 -------------------------------------------------------------------------
   1139 -- testing multiple states
   1140 T.closestate(T.newstate());
   1141 L1 = T.newstate()
   1142 assert(L1)
   1143 
   1144 assert(T.doremote(L1, "X='a'; return 'a'") == 'a')
   1145 
   1146 
   1147 assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0)
   1148 
   1149 a, b = T.doremote(L1, "return f()")
   1150 assert(a == 'alo' and b == '3')
   1151 
   1152 T.doremote(L1, "_ERRORMESSAGE = nil")
   1153 -- error: `sin' is not defined
   1154 a, b, c = T.doremote(L1, "return sin(1)")
   1155 assert(a == nil and c == 2)   -- 2 == run-time error
   1156 
   1157 -- error: syntax error
   1158 a, b, c = T.doremote(L1, "return a+")
   1159 assert(a == nil and c == 3 and type(b) == "string")   -- 3 == syntax error
   1160 
   1161 T.loadlib(L1, 2, ~2)    -- load only 'package', preload all others
   1162 a, b, c = T.doremote(L1, [[
   1163   string = require'string'
   1164   local initialG = _G   -- not loaded yet
   1165   local a = require'_G'; assert(a == _G and require("_G") == a)
   1166   assert(initialG == nil and io == nil)   -- now we have 'assert'
   1167   io = require'io'; assert(type(io.read) == "function")
   1168   assert(require("io") == io)
   1169   a = require'table'; assert(type(a.insert) == "function")
   1170   a = require'debug'; assert(type(a.getlocal) == "function")
   1171   a = require'math'; assert(type(a.sin) == "function")
   1172   return string.sub('okinama', 1, 2)
   1173 ]])
   1174 assert(a == "ok")
   1175 
   1176 T.closestate(L1);
   1177 
   1178 
   1179 L1 = T.newstate()
   1180 T.loadlib(L1, 0, 0)
   1181 T.doremote(L1, "a = {}")
   1182 T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1;
   1183              settable -3]])
   1184 assert(T.doremote(L1, "return a.x") == "1")
   1185 
   1186 T.closestate(L1)
   1187 
   1188 L1 = nil
   1189 
   1190 print('+')
   1191 -------------------------------------------------------------------------
   1192 -- testing to-be-closed variables
   1193 -------------------------------------------------------------------------
   1194 print"testing to-be-closed variables"
   1195 
   1196 do
   1197   local openresource = {}
   1198 
   1199   local function newresource ()
   1200     local x = setmetatable({10}, {__close = function(y)
   1201       assert(openresource[#openresource] == y)
   1202       openresource[#openresource] = nil
   1203       y[1] = y[1] + 1
   1204     end})
   1205     openresource[#openresource + 1] = x
   1206     return x
   1207   end
   1208 
   1209   local a, b = T.testC([[
   1210     call 0 1   # create resource
   1211     pushnil
   1212     toclose -2  # mark call result to be closed
   1213     toclose -1  # mark nil to be closed (will be ignored)
   1214     return 2
   1215   ]], newresource)
   1216   assert(a[1] == 11 and b == nil)
   1217   assert(#openresource == 0)    -- was closed
   1218 
   1219   -- repeat the test, but calling function in a 'multret' context
   1220   local a = {T.testC([[
   1221     call 0 1   # create resource
   1222     toclose 2 # mark it to be closed
   1223     return 2
   1224   ]], newresource)}
   1225   assert(type(a[1]) == "string" and a[2][1] == 11)
   1226   assert(#openresource == 0)    -- was closed
   1227 
   1228   -- closing by error
   1229   local a, b = pcall(T.makeCfunc[[
   1230     call 0 1   # create resource
   1231     toclose -1 # mark it to be closed
   1232     pushvalue -1  # replicate it as error object
   1233     error       # resource right after error object
   1234   ]], newresource)
   1235   assert(a == false and b[1] == 11)
   1236   assert(#openresource == 0)    -- was closed
   1237 
   1238   -- non-closable value
   1239   local a, b = pcall(T.makeCfunc[[
   1240     newtable   # create non-closable object
   1241     toclose -1 # mark it to be closed (should raise an error)
   1242     abort  # will not be executed
   1243   ]])
   1244   assert(a == false and
   1245     string.find(b, "non%-closable value"))
   1246 
   1247   local function check (n)
   1248     assert(#openresource == n)
   1249   end
   1250 
   1251   -- closing resources with 'closeslot'
   1252   _ENV.xxx = true
   1253   local a = T.testC([[
   1254     pushvalue 2  # stack: S, NR, CH, NR
   1255     call 0 1   # create resource; stack: S, NR, CH, R
   1256     toclose -1 # mark it to be closed
   1257     pushvalue 2  #  stack: S, NR, CH, R, NR
   1258     call 0 1   # create another resource; stack: S, NR, CH, R, R
   1259     toclose -1 # mark it to be closed
   1260     pushvalue 3  # stack: S, NR, CH, R, R, CH
   1261     pushint 2   # there should be two open resources
   1262     call 1 0  #  stack: S, NR, CH, R, R
   1263     closeslot -1   # close second resource
   1264     pushvalue 3  # stack: S, NR, CH, R, R, CH
   1265     pushint 1   # there should be one open resource
   1266     call 1 0  # stack: S, NR, CH, R, R
   1267     closeslot 4
   1268     setglobal "xxx"  # previous op. erased the slot
   1269     pop 1       # pop other resource from the stack
   1270     pushint *
   1271     return 1    # return stack size
   1272   ]], newresource, check)
   1273   assert(a == 3 and _ENV.xxx == nil)   -- no extra items left in the stack
   1274 
   1275   -- closing resources with 'pop'
   1276   local a = T.testC([[
   1277     pushvalue 2  # stack: S, NR, CH, NR
   1278     call 0 1   # create resource; stack: S, NR, CH, R
   1279     toclose -1 # mark it to be closed
   1280     pushvalue 2  #  stack: S, NR, CH, R, NR
   1281     call 0 1   # create another resource; stack: S, NR, CH, R, R
   1282     toclose -1 # mark it to be closed
   1283     pushvalue 3  # stack: S, NR, CH, R, R, CH
   1284     pushint 2   # there should be two open resources
   1285     call 1 0  #  stack: S, NR, CH, R, R
   1286     pop 1   # pop second resource
   1287     pushvalue 3  # stack: S, NR, CH, R, CH
   1288     pushint 1   # there should be one open resource
   1289     call 1 0  # stack: S, NR, CH, R
   1290     pop 1       # pop other resource from the stack
   1291     pushvalue 3  # stack: S, NR, CH, CH
   1292     pushint 0   # there should be no open resources
   1293     call 1 0  # stack: S, NR, CH
   1294     pushint *
   1295     return 1    # return stack size
   1296   ]], newresource, check)
   1297   assert(a == 3)   -- no extra items left in the stack
   1298 
   1299   -- non-closable value
   1300   local a, b = pcall(T.makeCfunc[[
   1301     pushint 32
   1302     toclose -1
   1303   ]])
   1304   assert(not a and string.find(b, "(C temporary)"))
   1305 
   1306 end
   1307 
   1308 
   1309 --[[
   1310 ** {==================================================================
   1311 ** Testing memory limits
   1312 ** ===================================================================
   1313 --]]
   1314 
   1315 print("memory-allocation errors")
   1316 
   1317 checkerr("block too big", T.newuserdata, math.maxinteger)
   1318 collectgarbage()
   1319 local f = load"local a={}; for i=1,100000 do a[i]=i end"
   1320 T.alloccount(10)
   1321 checkerr(MEMERRMSG, f)
   1322 T.alloccount()          -- remove limit
   1323 
   1324 
   1325 -- test memory errors; increase limit for maximum memory by steps,
   1326 -- o that we get memory errors in all allocations of a given
   1327 -- task, until there is enough memory to complete the task without
   1328 -- errors.
   1329 local function testbytes (s, f)
   1330   collectgarbage()
   1331   local M = T.totalmem()
   1332   local oldM = M
   1333   local a,b = nil
   1334   while true do
   1335     collectgarbage(); collectgarbage()
   1336     T.totalmem(M)
   1337     a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
   1338     T.totalmem(0)  -- remove limit
   1339     if a and b == "OK" then break end       -- stop when no more errors
   1340     if b ~= "OK" and b ~= MEMERRMSG then    -- not a memory error?
   1341       error(a, 0)   -- propagate it
   1342     end
   1343     M = M + 7   -- increase memory limit
   1344   end
   1345   print(string.format("minimum memory for %s: %d bytes", s, M - oldM))
   1346   return a
   1347 end
   1348 
   1349 -- test memory errors; increase limit for number of allocations one
   1350 -- by one, so that we get memory errors in all allocations of a given
   1351 -- task, until there is enough allocations to complete the task without
   1352 -- errors.
   1353 
   1354 local function testalloc (s, f)
   1355   collectgarbage()
   1356   local M = 0
   1357   local a,b = nil
   1358   while true do
   1359     collectgarbage(); collectgarbage()
   1360     T.alloccount(M)
   1361     a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
   1362     T.alloccount()  -- remove limit
   1363     if a and b == "OK" then break end       -- stop when no more errors
   1364     if b ~= "OK" and b ~= MEMERRMSG then    -- not a memory error?
   1365       error(a, 0)   -- propagate it
   1366     end
   1367     M = M + 1   -- increase allocation limit
   1368   end
   1369   print(string.format("minimum allocations for %s: %d allocations", s, M))
   1370   return a
   1371 end
   1372 
   1373 
   1374 local function testamem (s, f)
   1375   testalloc(s, f)
   1376   return testbytes(s, f)
   1377 end
   1378 
   1379 
   1380 -- doing nothing
   1381 b = testamem("doing nothing", function () return 10 end)
   1382 assert(b == 10)
   1383 
   1384 -- testing memory errors when creating a new state
   1385 
   1386 testamem("state creation", function ()
   1387   local st = T.newstate()
   1388   if st then T.closestate(st) end   -- close new state
   1389   return st
   1390 end)
   1391 
   1392 testamem("empty-table creation", function ()
   1393   return {}
   1394 end)
   1395 
   1396 testamem("string creation", function ()
   1397   return "XXX" .. "YYY"
   1398 end)
   1399 
   1400 testamem("coroutine creation", function()
   1401            return coroutine.create(print)
   1402 end)
   1403 
   1404 
   1405 -- testing to-be-closed variables
   1406 testamem("to-be-closed variables", function()
   1407   local flag
   1408   do
   1409     local x <close> =
   1410               setmetatable({}, {__close = function () flag = true end})
   1411     flag = false
   1412     local x = {}
   1413   end
   1414   return flag
   1415 end)
   1416 
   1417 
   1418 -- testing threads
   1419 
   1420 -- get main thread from registry
   1421 local mt = T.testC("rawgeti R !M; return 1")
   1422 assert(type(mt) == "thread" and coroutine.running() == mt)
   1423 
   1424 
   1425 
   1426 local function expand (n,s)
   1427   if n==0 then return "" end
   1428   local e = string.rep("=", n)
   1429   return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n",
   1430                               e, s, expand(n-1,s), e)
   1431 end
   1432 
   1433 G=0; collectgarbage(); a =collectgarbage("count")
   1434 load(expand(20,"G=G+1"))()
   1435 assert(G==20); collectgarbage();  -- assert(gcinfo() <= a+1)
   1436 G = nil
   1437 
   1438 testamem("running code on new thread", function ()
   1439   return T.doonnewstack("local x=1") == 0  -- try to create thread
   1440 end)
   1441 
   1442 
   1443 -- testing memory x compiler
   1444 
   1445 testamem("loadstring", function ()
   1446   return load("x=1")  -- try to do load a string
   1447 end)
   1448 
   1449 
   1450 local testprog = [[
   1451 local function foo () return end
   1452 local t = {"x"}
   1453 AA = "aaa"
   1454 for i = 1, #t do AA = AA .. t[i] end
   1455 return true
   1456 ]]
   1457 
   1458 -- testing memory x dofile
   1459 _G.AA = nil
   1460 local t =os.tmpname()
   1461 local f = assert(io.open(t, "w"))
   1462 f:write(testprog)
   1463 f:close()
   1464 testamem("dofile", function ()
   1465   local a = loadfile(t)
   1466   return a and a()
   1467 end)
   1468 assert(os.remove(t))
   1469 assert(_G.AA == "aaax")
   1470 
   1471 
   1472 -- other generic tests
   1473 
   1474 testamem("gsub", function ()
   1475   local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end)
   1476   return (a == 'ablo ablo')
   1477 end)
   1478 
   1479 testamem("dump/undump", function ()
   1480   local a = load(testprog)
   1481   local b = a and string.dump(a)
   1482   a = b and load(b)
   1483   return a and a()
   1484 end)
   1485 
   1486 _G.AA = nil
   1487 
   1488 local t = os.tmpname()
   1489 testamem("file creation", function ()
   1490   local f = assert(io.open(t, 'w'))
   1491   assert (not io.open"nomenaoexistente")
   1492   io.close(f);
   1493   return not loadfile'nomenaoexistente'
   1494 end)
   1495 assert(os.remove(t))
   1496 
   1497 testamem("table creation", function ()
   1498   local a, lim = {}, 10
   1499   for i=1,lim do a[i] = i; a[i..'a'] = {} end
   1500   return (type(a[lim..'a']) == 'table' and a[lim] == lim)
   1501 end)
   1502 
   1503 testamem("constructors", function ()
   1504   local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5}
   1505   return (type(a) == 'table' and a.e == 5)
   1506 end)
   1507 
   1508 local a = 1
   1509 local close = nil
   1510 testamem("closure creation", function ()
   1511   function close (b)
   1512    return function (x) return b + x end
   1513   end
   1514   return (close(2)(4) == 6)
   1515 end)
   1516 
   1517 testamem("using coroutines", function ()
   1518   local a = coroutine.wrap(function ()
   1519               coroutine.yield(string.rep("a", 10))
   1520               return {}
   1521             end)
   1522   assert(string.len(a()) == 10)
   1523   return a()
   1524 end)
   1525 
   1526 do   -- auxiliary buffer
   1527   local lim = 100
   1528   local a = {}; for i = 1, lim do a[i] = "01234567890123456789" end
   1529   testamem("auxiliary buffer", function ()
   1530     return (#table.concat(a, ",") == 20*lim + lim - 1)
   1531   end)
   1532 end
   1533 
   1534 testamem("growing stack", function ()
   1535   local function foo (n)
   1536     if n == 0 then return 1 else return 1 + foo(n - 1) end
   1537   end
   1538   return foo(100)
   1539 end)
   1540 
   1541 -- }==================================================================
   1542 
   1543 
   1544 do   -- testing failing in 'lua_checkstack'
   1545   local res = T.testC([[rawcheckstack 500000; return 1]])
   1546   assert(res == false)
   1547   local L = T.newstate()
   1548   T.alloccount(0)   -- will be unable to reallocate the stack
   1549   res = T.testC(L, [[rawcheckstack 5000; return 1]])
   1550   T.alloccount()
   1551   T.closestate(L)
   1552   assert(res == false)
   1553 end
   1554 
   1555 do   -- closing state with no extra memory
   1556   local L = T.newstate()
   1557   T.alloccount(0)
   1558   T.closestate(L)
   1559   T.alloccount()
   1560 end
   1561 
   1562 do   -- garbage collection with no extra memory
   1563   local L = T.newstate()
   1564   T.loadlib(L, 1 | 2, 0)   -- load _G and 'package'
   1565   local res = (T.doremote(L, [[
   1566     _ENV = _G
   1567     assert(string == nil)
   1568     local a = {}
   1569     for i = 1, 1000 do a[i] = 'i' .. i end    -- grow string table
   1570     local stsize, stuse = T.querystr()
   1571     assert(stuse > 1000)
   1572     local function foo (n)
   1573       if n > 0 then foo(n - 1) end
   1574     end
   1575     foo(180)    -- grow stack
   1576     local _, stksize = T.stacklevel()
   1577     assert(stksize > 180)
   1578     a = nil
   1579     T.alloccount(0)
   1580     collectgarbage()
   1581     T.alloccount()
   1582     -- stack and string table could not be reallocated,
   1583     -- so they kept their sizes (without errors)
   1584     assert(select(2, T.stacklevel()) == stksize)
   1585     assert(T.querystr() == stsize)
   1586     return 'ok'
   1587   ]]))
   1588   assert(res == 'ok')
   1589   T.closestate(L)
   1590 end
   1591 
   1592 print'+'
   1593 
   1594 -- testing some auxlib functions
   1595 local function gsub (a, b, c)
   1596   a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c)
   1597   assert(b == 5)
   1598   return a
   1599 end
   1600 
   1601 assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//")
   1602 assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.")
   1603 assert(gsub("", "alo", "//") == "")
   1604 assert(gsub("...", ".", "/.") == "/././.")
   1605 assert(gsub("...", "...", "") == "")
   1606 
   1607 
   1608 -- testing luaL_newmetatable
   1609 local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3")
   1610 assert(type(mt_xuxu) == "table" and res and top == 3)
   1611 local d, res, top = T.testC("newmetatable xuxu; gettop; return 3")
   1612 assert(mt_xuxu == d and not res and top == 3)
   1613 d, res, top = T.testC("newmetatable xuxu1; gettop; return 3")
   1614 assert(mt_xuxu ~= d and res and top == 3)
   1615 
   1616 x = T.newuserdata(0);
   1617 y = T.newuserdata(0);
   1618 T.testC("pushstring xuxu; gettable R; setmetatable 2", x)
   1619 assert(getmetatable(x) == mt_xuxu)
   1620 
   1621 -- testing luaL_testudata
   1622 -- correct metatable
   1623 local res1, res2, top = T.testC([[testudata -1 xuxu
   1624    	 			  testudata 2 xuxu
   1625 				  gettop
   1626 				  return 3]], x)
   1627 assert(res1 and res2 and top == 4)
   1628 
   1629 -- wrong metatable
   1630 res1, res2, top = T.testC([[testudata -1 xuxu1
   1631 			    testudata 2 xuxu1
   1632 			    gettop
   1633 			    return 3]], x)
   1634 assert(not res1 and not res2 and top == 4)
   1635 
   1636 -- non-existent type
   1637 res1, res2, top = T.testC([[testudata -1 xuxu2
   1638 			    testudata 2 xuxu2
   1639 			    gettop
   1640 			    return 3]], x)
   1641 assert(not res1 and not res2 and top == 4)
   1642 
   1643 -- userdata has no metatable
   1644 res1, res2, top = T.testC([[testudata -1 xuxu
   1645 			    testudata 2 xuxu
   1646 			    gettop
   1647 			    return 3]], y)
   1648 assert(not res1 and not res2 and top == 4)
   1649 
   1650 -- erase metatables
   1651 do
   1652   local r = debug.getregistry()
   1653   assert(r.xuxu == mt_xuxu and r.xuxu1 == d)
   1654   r.xuxu = nil; r.xuxu1 = nil
   1655 end
   1656 
   1657 print'OK'
   1658