github.com/hirochachacha/plua@v0.0.0-20170217012138-c82f520cc725/testdata/lua-5.3.3-tests/api.lua (about)

     1  -- $Id: api.lua,v 1.146 2016/01/07 16:45:45 roberto Exp $
     2  
     3  if T==nil then
     4    (Message or print)('\n >>> testC not active: skipping API tests <<<\n')
     5    return
     6  end
     7  
     8  local debug = require "debug"
     9  
    10  local pack = table.pack
    11  
    12  
    13  function tcheck (t1, t2)
    14    assert(t1.n == (t2.n or #t2) + 1)
    15    for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end
    16  end
    17  
    18  
    19  local function checkerr (msg, f, ...)
    20    local stat, err = pcall(f, ...)
    21    assert(not stat and string.find(err, msg))
    22  end
    23  
    24  
    25  print('testing C API')
    26  
    27  a = T.testC("pushvalue R; return 1")
    28  assert(a == debug.getregistry())
    29  
    30  
    31  -- absindex
    32  assert(T.testC("settop 10; absindex -1; return 1") == 10)
    33  assert(T.testC("settop 5; absindex -5; return 1") == 1)
    34  assert(T.testC("settop 10; absindex 1; return 1") == 1)
    35  assert(T.testC("settop 10; absindex R; return 1") < -10)
    36  
    37  -- testing alignment
    38  a = T.d2s(12458954321123.0)
    39  assert(a == string.pack("d", 12458954321123.0))
    40  assert(T.s2d(a) == 12458954321123.0)
    41  
    42  a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2")
    43  assert(a == 2 and b == 3 and not c)
    44  
    45  f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2")
    46  a,b,c = f()
    47  assert(a == 2 and b == 3 and not c)
    48  
    49  -- test that all trues are equal
    50  a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3")
    51  assert(a == b and a == true and c == false)
    52  a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\
    53                        tobool -3; tobool -3; tobool -3; return 3"
    54  assert(a==false and b==true and c==false)
    55  
    56  
    57  a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40)
    58  assert(a == 40 and b == 5 and not c)
    59  
    60  t = pack(T.testC("settop 5; return *", 2, 3))
    61  tcheck(t, {n=4,2,3})
    62  
    63  t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23))
    64  assert(t.n == 10 and t[1] == nil and t[10] == nil)
    65  
    66  t = pack(T.testC("remove -2; return *", 2, 3, 4))
    67  tcheck(t, {n=2,2,4})
    68  
    69  t = pack(T.testC("insert -1; return *", 2, 3))
    70  tcheck(t, {n=2,2,3})
    71  
    72  t = pack(T.testC("insert 3; return *", 2, 3, 4, 5))
    73  tcheck(t, {n=4,2,5,3,4})
    74  
    75  t = pack(T.testC("replace 2; return *", 2, 3, 4, 5))
    76  tcheck(t, {n=3,5,3,4})
    77  
    78  t = pack(T.testC("replace -2; return *", 2, 3, 4, 5))
    79  tcheck(t, {n=3,2,3,5})
    80  
    81  t = pack(T.testC("remove 3; return *", 2, 3, 4, 5))
    82  tcheck(t, {n=3,2,4,5})
    83  
    84  t = pack(T.testC("copy 3 4; return *", 2, 3, 4, 5))
    85  tcheck(t, {n=4,2,3,3,5})
    86  
    87  t = pack(T.testC("copy -3 -1; return *", 2, 3, 4, 5))
    88  tcheck(t, {n=4,2,3,4,3})
    89  
    90  do   -- testing 'rotate'
    91    local t = {10, 20, 30, 40, 50, 60}
    92    for i = -6, 6 do
    93      local s = string.format("rotate 2 %d; return 7", i)
    94      local t1 = pack(T.testC(s, 10, 20, 30, 40, 50, 60))
    95      tcheck(t1, t)
    96      table.insert(t, 1, table.remove(t))
    97    end
    98  
    99    t = pack(T.testC("rotate -2 1; return *", 10, 20, 30, 40))
   100    tcheck(t, {10, 20, 40, 30})
   101    t = pack(T.testC("rotate -2 -1; return *", 10, 20, 30, 40))
   102    tcheck(t, {10, 20, 40, 30})
   103  
   104    -- some corner cases
   105    t = pack(T.testC("rotate -1 0; return *", 10, 20, 30, 40))
   106    tcheck(t, {10, 20, 30, 40})
   107    t = pack(T.testC("rotate -1 1; return *", 10, 20, 30, 40))
   108    tcheck(t, {10, 20, 30, 40})
   109    t = pack(T.testC("rotate 5 -1; return *", 10, 20, 30, 40))
   110    tcheck(t, {10, 20, 30, 40})
   111  end
   112  
   113  -- testing non-function message handlers
   114  do
   115    local f = T.makeCfunc[[
   116      getglobal error
   117      pushstring bola
   118      pcall 1 1 1   # call 'error' with given handler
   119      pushstatus
   120      return 2     # return error message and status
   121    ]]
   122  
   123    local msg, st = f({})     -- invalid handler
   124    assert(st == "ERRERR" and string.find(msg, "error handling"))
   125    local msg, st = f(nil)     -- invalid handler
   126    assert(st == "ERRERR" and string.find(msg, "error handling"))
   127  
   128    local a = setmetatable({}, {__call = function (_, x) return x:upper() end})
   129    local msg, st = f(a)   -- callable handler
   130    assert(st == "ERRRUN" and msg == "BOLA")
   131  end
   132  
   133  t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \
   134                    insert 2; pushvalue 1; remove 1; insert 1; \
   135        insert -2; pushvalue -2; remove -3; return *",
   136        2, 3, 4, 5, 10, 40, 90))
   137  tcheck(t, {n=7,2,3,4,5,10,40,90})
   138  
   139  t = pack(T.testC("concat 5; return *", "alo", 2, 3, "joao", 12))
   140  tcheck(t, {n=1,"alo23joao12"})
   141  
   142  -- testing MULTRET
   143  t = pack(T.testC("call 2,-1; return *",
   144       function (a,b) return 1,2,3,4,a,b end, "alo", "joao"))
   145  tcheck(t, {n=6,1,2,3,4,"alo", "joao"})
   146  
   147  do  -- test returning more results than fit in the caller stack
   148    local a = {}
   149    for i=1,1000 do a[i] = true end; a[999] = 10
   150    local b = T.testC([[pcall 1 -1 0; pop 1; tostring -1; return 1]],
   151                      table.unpack, a)
   152    assert(b == "10")
   153  end
   154  
   155  
   156  -- testing globals
   157  _G.a = 14; _G.b = "a31"
   158  local a = {T.testC[[
   159    getglobal a;
   160    getglobal b;
   161    getglobal b;
   162    setglobal a;
   163    return *
   164  ]]}
   165  assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.a == "a31")
   166  
   167  
   168  -- testing arith
   169  assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5)
   170  assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10)
   171  assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200)
   172  assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000)
   173  assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5)
   174  assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10)
   175  assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200)
   176  assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000)
   177  assert(T.testC("arith /; return 1", 2, 0) == 10.0/0)
   178  a = T.testC("pushnum 10; pushint 3; arith \\; return 1")
   179  assert(a == 3.0 and math.type(a) == "float")
   180  a = T.testC("pushint 10; pushint 3; arith \\; return 1")
   181  assert(a == 3 and math.type(a) == "integer")
   182  a = assert(T.testC("pushint 10; pushint 3; arith +; return 1"))
   183  assert(a == 13 and math.type(a) == "integer")
   184  a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1"))
   185  assert(a == 13 and math.type(a) == "float")
   186  a,b,c = T.testC([[pushnum 1;
   187                    pushstring 10; arith _;
   188                    pushstring 5; return 3]])
   189  assert(a == 1 and b == -10 and c == "5")
   190  mt = {__add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end,
   191        __mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end,
   192        __unm = function (a) return setmetatable({a[1]* 2}, mt) end}
   193  a,b,c = setmetatable({4}, mt),
   194          setmetatable({8}, mt),
   195          setmetatable({-3}, mt)
   196  x,y,z = T.testC("arith +; return 2", 10, a, b)
   197  assert(x == 10 and y[1] == 12 and z == nil)
   198  assert(T.testC("arith %; return 1", a, c)[1] == 4%-3)
   199  assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] ==
   200                 8 % (4 + (-3)*2))
   201  
   202  -- errors in arithmetic
   203  checkerr("divide by zero", T.testC, "arith \\", 10, 0)
   204  checkerr("%%0", T.testC, "arith %", 10, 0)
   205  
   206  
   207  -- testing lessthan and lessequal
   208  assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2))
   209  assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2))
   210  assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2))
   211  assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2))
   212  assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2))
   213  assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2"))
   214  assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2"))
   215  
   216  -- non-valid indices produce false
   217  assert(not T.testC("compare LT 1 4, return 1"))
   218  assert(not T.testC("compare LE 9 1, return 1"))
   219  assert(not T.testC("compare EQ 9 9, return 1"))
   220  
   221  local b = {__lt = function (a,b) return a[1] < b[1] end}
   222  local a1,a3,a4 = setmetatable({1}, b),
   223                   setmetatable({3}, b),
   224                   setmetatable({4}, b)
   225  assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2))
   226  assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2))
   227  assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2))
   228  a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20)
   229  assert(a == 20 and b == false)
   230  a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20)
   231  assert(a == 20 and b == false)
   232  a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20)
   233  assert(a == 20 and b == true)
   234  
   235  -- testing length
   236  local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
   237  a,b,c = T.testC([[
   238     len 2;
   239     Llen 2;
   240     objsize 2;
   241     return 3
   242  ]], t)
   243  assert(a == 20 and b == 20 and c == 0)
   244  
   245  t.x = "234"; t[1] = 20
   246  a,b,c = T.testC([[
   247     len 2;
   248     Llen 2;
   249     objsize 2;
   250     return 3
   251  ]], t)
   252  assert(a == "234" and b == 234 and c == 1)
   253  
   254  t.x = print; t[1] = 20
   255  a,c = T.testC([[
   256     len 2;
   257     objsize 2;
   258     return 2
   259  ]], t)
   260  assert(a == print and c == 1)
   261  
   262  
   263  -- testing __concat
   264  
   265  a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end})
   266  x,y = T.testC([[
   267    pushnum 5
   268    pushvalue 2;
   269    pushvalue 2;
   270    concat 2;
   271    pushvalue -2;
   272    return 2;
   273  ]], a, a)
   274  assert(x == a..a and y == 5)
   275  
   276  -- concat with 0 elements
   277  assert(T.testC("concat 0; return 1") == "")
   278  
   279  -- concat with 1 element
   280  assert(T.testC("concat 1; return 1", "xuxu") == "xuxu")
   281  
   282  
   283  
   284  -- testing lua_is
   285  
   286  function B(x) return x and 1 or 0 end
   287  
   288  function count (x, n)
   289    n = n or 2
   290    local prog = [[
   291      isnumber %d;
   292      isstring %d;
   293      isfunction %d;
   294      iscfunction %d;
   295      istable %d;
   296      isuserdata %d;
   297      isnil %d;
   298      isnull %d;
   299      return 8
   300    ]]
   301    prog = string.format(prog, n, n, n, n, n, n, n, n)
   302    local a,b,c,d,e,f,g,h = T.testC(prog, x)
   303    return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h))
   304  end
   305  
   306  assert(count(3) == 2)
   307  assert(count('alo') == 1)
   308  assert(count('32') == 2)
   309  assert(count({}) == 1)
   310  assert(count(print) == 2)
   311  assert(count(function () end) == 1)
   312  assert(count(nil) == 1)
   313  assert(count(io.stdin) == 1)
   314  assert(count(nil, 15) == 100)
   315  
   316  
   317  -- testing lua_to...
   318  
   319  function to (s, x, n)
   320    n = n or 2
   321    return T.testC(string.format("%s %d; return 1", s, n), x)
   322  end
   323  
   324  local hfunc = string.gmatch("", "")    -- a "heavy C function" (with upvalues)
   325  assert(debug.getupvalue(hfunc, 1))
   326  assert(to("tostring", {}) == nil)
   327  assert(to("tostring", "alo") == "alo")
   328  assert(to("tostring", 12) == "12")
   329  assert(to("tostring", 12, 3) == nil)
   330  assert(to("objsize", {}) == 0)
   331  assert(to("objsize", {1,2,3}) == 3)
   332  assert(to("objsize", "alo\0\0a") == 6)
   333  assert(to("objsize", T.newuserdata(0)) == 0)
   334  assert(to("objsize", T.newuserdata(101)) == 101)
   335  assert(to("objsize", 124) == 0)
   336  assert(to("objsize", true) == 0)
   337  assert(to("tonumber", {}) == 0)
   338  assert(to("tonumber", "12") == 12)
   339  assert(to("tonumber", "s2") == 0)
   340  assert(to("tonumber", 1, 20) == 0)
   341  assert(to("topointer", 10) == 0)
   342  assert(to("topointer", true) == 0)
   343  assert(to("topointer", T.pushuserdata(20)) == 20)
   344  assert(to("topointer", io.read) ~= 0)           -- light C function
   345  assert(to("topointer", hfunc) ~= 0)        -- "heavy" C function
   346  assert(to("topointer", function () end) ~= 0)   -- Lua function
   347  assert(to("topointer", io.stdin) ~= 0)   -- full userdata
   348  assert(to("func2num", 20) == 0)
   349  assert(to("func2num", T.pushuserdata(10)) == 0)
   350  assert(to("func2num", io.read) ~= 0)     -- light C function
   351  assert(to("func2num", hfunc) ~= 0)  -- "heavy" C function (with upvalue)
   352  a = to("tocfunction", math.deg)
   353  assert(a(3) == math.deg(3) and a == math.deg)
   354  
   355  
   356  print("testing panic function")
   357  do
   358    -- trivial error
   359    assert(T.checkpanic("pushstring hi; error") == "hi")
   360  
   361    -- using the stack inside panic
   362    assert(T.checkpanic("pushstring hi; error;",
   363      [[checkstack 5 XX
   364        pushstring ' alo'
   365        pushstring ' mundo'
   366        concat 3]]) == "hi alo mundo")
   367  
   368    -- "argerror" without frames
   369    assert(T.checkpanic("loadstring 4") ==
   370        "bad argument #4 (string expected, got no value)")
   371    
   372  
   373    -- memory error
   374    T.totalmem(T.totalmem()+10000)   -- set low memory limit (+10k)
   375    assert(T.checkpanic("newuserdata 20000") == "not enough memory")
   376    T.totalmem(0)          -- restore high limit
   377  
   378    -- stack error
   379    if not _soft then
   380      local msg = T.checkpanic[[
   381        pushstring "function f() f() end"
   382        loadstring -1; call 0 0
   383        getglobal f; call 0 0
   384      ]]
   385      assert(string.find(msg, "stack overflow"))
   386    end
   387  
   388  end
   389  
   390  -- testing deep C stack
   391  if not _soft then
   392    print("testing stack overflow")
   393    collectgarbage("stop")
   394    checkerr("XXXX", T.testC, "checkstack 1000023 XXXX")   -- too deep
   395    -- too deep (with no message)
   396    checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''")
   397    local s = string.rep("pushnil;checkstack 1 XX;", 1000000)
   398    checkerr("overflow", T.testC, s)
   399    collectgarbage("restart")
   400    print'+'
   401  end
   402  
   403  local lim = _soft and 500 or 12000
   404  local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"}
   405  for i = 1,lim do
   406    prog[#prog + 1] = "pushnum " .. i
   407    prog[#prog + 1] = "pushnum " .. i * 10
   408  end
   409  
   410  prog[#prog + 1] = "rawgeti R 2"   -- get global table in registry
   411  prog[#prog + 1] = "insert " .. -(2*lim + 2)
   412  
   413  for i = 1,lim do
   414    prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1)
   415  end
   416  
   417  prog[#prog + 1] = "return 2"
   418  
   419  prog = table.concat(prog, ";")
   420  local g, t = T.testC(prog)
   421  assert(g == _G)
   422  for i = 1,lim do assert(t[i] == i*10); t[i] = nil end
   423  assert(next(t) == nil)
   424  prog, g, t = nil
   425  
   426  -- testing errors
   427  
   428  a = T.testC([[
   429    loadstring 2; pcall 0 1 0;
   430    pushvalue 3; insert -2; pcall 1 1 0;
   431    pcall 0 0 0;
   432    return 1
   433  ]], "x=150", function (a) assert(a==nil); return 3 end)
   434  
   435  assert(type(a) == 'string' and x == 150)
   436  
   437  function check3(p, ...)
   438    local arg = {...}
   439    assert(#arg == 3)
   440    assert(string.find(arg[3], p))
   441  end
   442  check3(":1:", T.testC("loadstring 2; return *", "x="))
   443  check3("%.", T.testC("loadfile 2; return *", "."))
   444  check3("xxxx", T.testC("loadfile 2; return *", "xxxx"))
   445  
   446  -- test errors in non protected threads
   447  function checkerrnopro (code, msg)
   448    local th = coroutine.create(function () end)  -- create new thread
   449    local stt, err = pcall(T.testC, th, code)   -- run code there
   450    assert(not stt and string.find(err, msg))
   451  end
   452  
   453  if not _soft then
   454    checkerrnopro("pushnum 3; call 0 0", "attempt to call")
   455    print"testing stack overflow in unprotected thread"
   456    function f () f() end
   457    checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow")
   458  end
   459  print"+"
   460  
   461  
   462  -- testing table access
   463  
   464  do   -- getp/setp
   465    local a = {}
   466    T.testC("rawsetp 2 1", a, 20)
   467    assert(a[T.pushuserdata(1)] == 20)
   468    assert(T.testC("rawgetp 2 1; return 1", a) == 20)
   469  end
   470  
   471  a = {x=0, y=12}
   472  x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2",
   473                  a, 3, "y", 4, "x")
   474  assert(x == 0 and y == 12)
   475  T.testC("settable -5", a, 3, 4, "x", 15)
   476  assert(a.x == 15)
   477  a[a] = print
   478  x = T.testC("gettable 2; return 1", a)  -- table and key are the same object!
   479  assert(x == print)
   480  T.testC("settable 2", a, "x")    -- table and key are the same object!
   481  assert(a[a] == "x")
   482  
   483  b = setmetatable({p = a}, {})
   484  getmetatable(b).__index = function (t, i) return t.p[i] end
   485  k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x")
   486  assert(x == 15 and k == 35)
   487  k = T.testC("getfield 2 y, return 1", b)
   488  assert(k == 12)
   489  getmetatable(b).__index = function (t, i) return a[i] end
   490  getmetatable(b).__newindex = function (t, i,v ) a[i] = v end
   491  y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b)
   492  assert(y == 12)
   493  k = T.testC("settable -5, return 1", b, 3, 4, "x", 16)
   494  assert(a.x == 16 and k == 4)
   495  a[b] = 'xuxu'
   496  y = T.testC("gettable 2, return 1", b)
   497  assert(y == 'xuxu')
   498  T.testC("settable 2", b, 19)
   499  assert(a[b] == 19)
   500  
   501  --
   502  do   -- testing getfield/setfield with long keys
   503    local t = {_012345678901234567890123456789012345678901234567890123456789 = 32}
   504    local a = T.testC([[
   505      getfield 2 _012345678901234567890123456789012345678901234567890123456789
   506      return 1
   507    ]], t)
   508    assert(a == 32)
   509    local a = T.testC([[
   510      pushnum 33
   511      setglobal _012345678901234567890123456789012345678901234567890123456789
   512    ]])
   513    assert(_012345678901234567890123456789012345678901234567890123456789 == 33)
   514    _012345678901234567890123456789012345678901234567890123456789 = nil
   515  end
   516  
   517  -- testing next
   518  a = {}
   519  t = pack(T.testC("next; return *", a, nil))
   520  tcheck(t, {n=1,a})
   521  a = {a=3}
   522  t = pack(T.testC("next; return *", a, nil))
   523  tcheck(t, {n=3,a,'a',3})
   524  t = pack(T.testC("next; pop 1; next; return *", a, nil))
   525  tcheck(t, {n=1,a})
   526  
   527  
   528  
   529  -- testing upvalues
   530  
   531  do
   532    local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
   533    t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]])
   534    assert(b == 10 and c == 20 and type(t) == 'table')
   535    a, b = A([[tostring U3; tonumber U4; return 2]])
   536    assert(a == nil and b == 0)
   537    A([[pushnum 100; pushnum 200; replace U2; replace U1]])
   538    b, c = A([[pushvalue U1; pushvalue U2; return 2]])
   539    assert(b == 100 and c == 200)
   540    A([[replace U2; replace U1]], {x=1}, {x=2})
   541    b, c = A([[pushvalue U1; pushvalue U2; return 2]])
   542    assert(b.x == 1 and c.x == 2)
   543    T.checkmemory()
   544  end
   545  
   546  
   547  -- testing absent upvalues from C-function pointers
   548  assert(T.testC[[isnull U1; return 1]] == true)
   549  assert(T.testC[[isnull U100; return 1]] == true)
   550  assert(T.testC[[pushvalue U1; return 1]] == nil)
   551  
   552  local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]]
   553  assert(T.upvalue(f, 1) == 10 and
   554         T.upvalue(f, 2) == 20 and
   555         T.upvalue(f, 3) == nil)
   556  T.upvalue(f, 2, "xuxu")
   557  assert(T.upvalue(f, 2) == "xuxu")
   558  
   559  
   560  -- large closures
   561  do
   562    local A = "checkstack 300 msg;" ..
   563              string.rep("pushnum 10;", 255) ..
   564              "pushcclosure 255; return 1"
   565    A = T.testC(A)
   566    for i=1,255 do
   567      assert(A(("pushvalue U%d; return 1"):format(i)) == 10)
   568    end
   569    assert(A("isnull U256; return 1"))
   570    assert(not A("isnil U256; return 1"))
   571  end
   572  
   573  
   574  
   575  -- testing get/setuservalue
   576  -- bug in 5.1.2
   577  checkerr("got number", debug.setuservalue, 3, {})
   578  checkerr("got nil", debug.setuservalue, nil, {})
   579  checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {})
   580  
   581  local b = T.newuserdata(0)
   582  assert(debug.getuservalue(b) == nil)
   583  for _, v in pairs{true, false, 4.56, print, {}, b, "XYZ"} do
   584    assert(debug.setuservalue(b, v) == b)
   585    assert(debug.getuservalue(b) == v)
   586  end
   587  
   588  assert(debug.getuservalue(4) == nil)
   589  
   590  debug.setuservalue(b, function () return 10 end)
   591  collectgarbage()   -- function should not be collected
   592  assert(debug.getuservalue(b)() == 10)
   593  
   594  debug.setuservalue(b, 134)
   595  collectgarbage()   -- number should not be a problem for collector
   596  assert(debug.getuservalue(b) == 134)
   597  
   598  -- test barrier for uservalues
   599  T.gcstate("atomic")
   600  assert(T.gccolor(b) == "black")
   601  debug.setuservalue(b, {x = 100})
   602  T.gcstate("pause")  -- complete collection
   603  assert(debug.getuservalue(b).x == 100)  -- uvalue should be there
   604  
   605  -- long chain of userdata
   606  for i = 1, 1000 do
   607    local bb = T.newuserdata(0)
   608    debug.setuservalue(bb, b)
   609    b = bb
   610  end
   611  collectgarbage()     -- nothing should not be collected
   612  for i = 1, 1000 do
   613    b = debug.getuservalue(b)
   614  end
   615  assert(debug.getuservalue(b).x == 100)
   616  b = nil
   617  
   618  
   619  -- testing locks (refs)
   620  
   621  -- reuse of references
   622  local i = T.ref{}
   623  T.unref(i)
   624  assert(T.ref{} == i)
   625  
   626  Arr = {}
   627  Lim = 100
   628  for i=1,Lim do   -- lock many objects
   629    Arr[i] = T.ref({})
   630  end
   631  
   632  assert(T.ref(nil) == -1 and T.getref(-1) == nil)
   633  T.unref(-1); T.unref(-1)
   634  
   635  for i=1,Lim do   -- unlock all them
   636    T.unref(Arr[i])
   637  end
   638  
   639  function printlocks ()
   640    local f = T.makeCfunc("gettable R; return 1")
   641    local n = f("n")
   642    print("n", n)
   643    for i=0,n do
   644      print(i, f(i))
   645    end
   646  end
   647  
   648  
   649  for i=1,Lim do   -- lock many objects
   650    Arr[i] = T.ref({})
   651  end
   652  
   653  for i=1,Lim,2 do   -- unlock half of them
   654    T.unref(Arr[i])
   655  end
   656  
   657  assert(type(T.getref(Arr[2])) == 'table')
   658  
   659  
   660  assert(T.getref(-1) == nil)
   661  
   662  
   663  a = T.ref({})
   664  
   665  collectgarbage()
   666  
   667  assert(type(T.getref(a)) == 'table')
   668  
   669  
   670  -- colect in cl the `val' of all collected userdata
   671  tt = {}
   672  cl = {n=0}
   673  A = nil; B = nil
   674  local F
   675  F = function (x)
   676    local udval = T.udataval(x)
   677    table.insert(cl, udval)
   678    local d = T.newuserdata(100)   -- cria lixo
   679    d = nil
   680    assert(debug.getmetatable(x).__gc == F)
   681    assert(load("table.insert({}, {})"))()   -- cria mais lixo
   682    collectgarbage()   -- forca coleta de lixo durante coleta!
   683    assert(debug.getmetatable(x).__gc == F)   -- coleta anterior nao melou isso?
   684    local dummy = {}    -- cria lixo durante coleta
   685    if A ~= nil then
   686      assert(type(A) == "userdata")
   687      assert(T.udataval(A) == B)
   688      debug.getmetatable(A)    -- just acess it
   689    end
   690    A = x   -- ressucita userdata
   691    B = udval
   692    return 1,2,3
   693  end
   694  tt.__gc = F
   695  
   696  -- test whether udate collection frees memory in the right time
   697  do
   698    collectgarbage();
   699    collectgarbage();
   700    local x = collectgarbage("count");
   701    local a = T.newuserdata(5001)
   702    assert(T.testC("objsize 2; return 1", a) == 5001)
   703    assert(collectgarbage("count") >= x+4)
   704    a = nil
   705    collectgarbage();
   706    assert(collectgarbage("count") <= x+1)
   707    -- udata without finalizer
   708    x = collectgarbage("count")
   709    collectgarbage("stop")
   710    for i=1,1000 do T.newuserdata(0) end
   711    assert(collectgarbage("count") > x+10)
   712    collectgarbage()
   713    assert(collectgarbage("count") <= x+1)
   714    -- udata with finalizer
   715    collectgarbage()
   716    x = collectgarbage("count")
   717    collectgarbage("stop")
   718    a = {__gc = function () end}
   719    for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end
   720    assert(collectgarbage("count") >= x+10)
   721    collectgarbage()  -- this collection only calls TM, without freeing memory
   722    assert(collectgarbage("count") >= x+10)
   723    collectgarbage()  -- now frees memory
   724    assert(collectgarbage("count") <= x+1)
   725    collectgarbage("restart")
   726  end
   727  
   728  
   729  collectgarbage("stop")
   730  
   731  -- create 3 userdatas with tag `tt'
   732  a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a)
   733  b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b)
   734  c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c)
   735  
   736  -- create userdata without meta table
   737  x = T.newuserdata(4)
   738  y = T.newuserdata(0)
   739  
   740  checkerr("FILE%* expected, got userdata", io.input, a)
   741  checkerr("FILE%* expected, got userdata", io.input, x)
   742  
   743  assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil)
   744  
   745  d=T.ref(a);
   746  e=T.ref(b);
   747  f=T.ref(c);
   748  t = {T.getref(d), T.getref(e), T.getref(f)}
   749  assert(t[1] == a and t[2] == b and t[3] == c)
   750  
   751  t=nil; a=nil; c=nil;
   752  T.unref(e); T.unref(f)
   753  
   754  collectgarbage()
   755  
   756  -- check that unref objects have been collected
   757  assert(#cl == 1 and cl[1] == nc)
   758  
   759  x = T.getref(d)
   760  assert(type(x) == 'userdata' and debug.getmetatable(x) == tt)
   761  x =nil
   762  tt.b = b  -- create cycle
   763  tt=nil    -- frees tt for GC
   764  A = nil
   765  b = nil
   766  T.unref(d);
   767  n5 = T.newuserdata(0)
   768  debug.setmetatable(n5, {__gc=F})
   769  n5 = T.udataval(n5)
   770  collectgarbage()
   771  assert(#cl == 4)
   772  -- check order of collection
   773  assert(cl[2] == n5 and cl[3] == nb and cl[4] == na)
   774  
   775  collectgarbage"restart"
   776  
   777  
   778  a, na = {}, {}
   779  for i=30,1,-1 do
   780    a[i] = T.newuserdata(0)
   781    debug.setmetatable(a[i], {__gc=F})
   782    na[i] = T.udataval(a[i])
   783  end
   784  cl = {}
   785  a = nil; collectgarbage()
   786  assert(#cl == 30)
   787  for i=1,30 do assert(cl[i] == na[i]) end
   788  na = nil
   789  
   790  
   791  for i=2,Lim,2 do   -- unlock the other half
   792    T.unref(Arr[i])
   793  end
   794  
   795  x = T.newuserdata(41); debug.setmetatable(x, {__gc=F})
   796  assert(T.testC("objsize 2; return 1", x) == 41)
   797  cl = {}
   798  a = {[x] = 1}
   799  x = T.udataval(x)
   800  collectgarbage()
   801  -- old `x' cannot be collected (`a' still uses it)
   802  assert(#cl == 0)
   803  for n in pairs(a) do a[n] = nil end
   804  collectgarbage()
   805  assert(#cl == 1 and cl[1] == x)   -- old `x' must be collected
   806  
   807  -- testing lua_equal
   808  assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20))
   809  assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo"))
   810  assert(T.testC("compare EQ 2 3; return 1", nil, nil))
   811  assert(not T.testC("compare EQ 2 3; return 1", {}, {}))
   812  assert(not T.testC("compare EQ 2 3; return 1"))
   813  assert(not T.testC("compare EQ 2 3; return 1", 3))
   814  
   815  -- testing lua_equal with fallbacks
   816  do
   817    local map = {}
   818    local t = {__eq = function (a,b) return map[a] == map[b] end}
   819    local function f(x)
   820      local u = T.newuserdata(0)
   821      debug.setmetatable(u, t)
   822      map[u] = x
   823      return u
   824    end
   825    assert(f(10) == f(10))
   826    assert(f(10) ~= f(11))
   827    assert(T.testC("compare EQ 2 3; return 1", f(10), f(10)))
   828    assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20)))
   829    t.__eq = nil
   830    assert(f(10) ~= f(10))
   831  end
   832  
   833  print'+'
   834  
   835  
   836  
   837  -- testing changing hooks during hooks
   838  _G.t = {}
   839  T.sethook([[
   840    # set a line hook after 3 count hooks
   841    sethook 4 0 '
   842      getglobal t;
   843      pushvalue -3; append -2
   844      pushvalue -2; append -2
   845    ']], "c", 3)
   846  local a = 1   -- counting
   847  a = 1   -- counting
   848  a = 1   -- count hook (set line hook)
   849  a = 1   -- line hook
   850  a = 1   -- line hook
   851  debug.sethook()
   852  t = _G.t
   853  assert(t[1] == "line")
   854  line = t[2]
   855  assert(t[3] == "line" and t[4] == line + 1)
   856  assert(t[5] == "line" and t[6] == line + 2)
   857  assert(t[7] == nil)
   858  
   859  
   860  -------------------------------------------------------------------------
   861  do   -- testing errors during GC
   862    local a = {}
   863    for i=1,20 do
   864      a[i] = T.newuserdata(i)   -- creates several udata
   865    end
   866    for i=1,20,2 do   -- mark half of them to raise errors during GC
   867      debug.setmetatable(a[i], {__gc = function (x) error("error inside gc") end})
   868    end
   869    for i=2,20,2 do   -- mark the other half to count and to create more garbage
   870      debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end})
   871    end
   872    _G.A = 0
   873    a = 0
   874    while 1 do
   875      local stat, msg = pcall(collectgarbage)
   876      if stat then
   877        break   -- stop when no more errors
   878      else
   879        a = a + 1
   880        assert(string.find(msg, "__gc"))
   881      end
   882    end
   883    assert(a == 10)  -- number of errors
   884  
   885    assert(A == 10)  -- number of normal collections
   886  end
   887  -------------------------------------------------------------------------
   888  -- test for userdata vals
   889  do
   890    local a = {}; local lim = 30
   891    for i=0,lim do a[i] = T.pushuserdata(i) end
   892    for i=0,lim do assert(T.udataval(a[i]) == i) end
   893    for i=0,lim do assert(T.pushuserdata(i) == a[i]) end
   894    for i=0,lim do a[a[i]] = i end
   895    for i=0,lim do a[T.pushuserdata(i)] = i end
   896    assert(type(tostring(a[1])) == "string")
   897  end
   898  
   899  
   900  -------------------------------------------------------------------------
   901  -- testing multiple states
   902  T.closestate(T.newstate());
   903  L1 = T.newstate()
   904  assert(L1)
   905  
   906  assert(T.doremote(L1, "X='a'; return 'a'") == 'a')
   907  
   908  
   909  assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0)
   910  
   911  a, b = T.doremote(L1, "return f()")
   912  assert(a == 'alo' and b == '3')
   913  
   914  T.doremote(L1, "_ERRORMESSAGE = nil")
   915  -- error: `sin' is not defined
   916  a, _, b = T.doremote(L1, "return sin(1)")
   917  assert(a == nil and b == 2)   -- 2 == run-time error
   918  
   919  -- error: syntax error
   920  a, b, c = T.doremote(L1, "return a+")
   921  assert(a == nil and c == 3 and type(b) == "string")   -- 3 == syntax error
   922  
   923  T.loadlib(L1)
   924  a, b, c = T.doremote(L1, [[
   925    string = require'string'
   926    a = require'_G'; assert(a == _G and require("_G") == a)
   927    io = require'io'; assert(type(io.read) == "function")
   928    assert(require("io") == io)
   929    a = require'table'; assert(type(a.insert) == "function")
   930    a = require'debug'; assert(type(a.getlocal) == "function")
   931    a = require'math'; assert(type(a.sin) == "function")
   932    return string.sub('okinama', 1, 2)
   933  ]])
   934  assert(a == "ok")
   935  
   936  T.closestate(L1);
   937  
   938  
   939  L1 = T.newstate()
   940  T.loadlib(L1)
   941  T.doremote(L1, "a = {}")
   942  T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1;
   943               settable -3]])
   944  assert(T.doremote(L1, "return a.x") == "1")
   945  
   946  T.closestate(L1)
   947  
   948  L1 = nil
   949  
   950  print('+')
   951  
   952  -------------------------------------------------------------------------
   953  -- testing memory limits
   954  -------------------------------------------------------------------------
   955  checkerr("block too big", T.newuserdata, math.maxinteger)
   956  collectgarbage()
   957  T.totalmem(T.totalmem()+5000)   -- set low memory limit (+5k)
   958  checkerr("not enough memory", load"local a={}; for i=1,100000 do a[i]=i end")
   959  T.totalmem(0)          -- restore high limit
   960  
   961  -- test memory errors; increase memory limit in small steps, so that
   962  -- we get memory errors in different parts of a given task, up to there
   963  -- is enough memory to complete the task without errors
   964  function testamem (s, f)
   965    collectgarbage(); collectgarbage()
   966    local M = T.totalmem()
   967    local oldM = M
   968    local a,b = nil
   969    while 1 do
   970      M = M+7   -- increase memory limit in small steps
   971      T.totalmem(M)
   972      a, b = pcall(f)
   973      T.totalmem(0)  -- restore high limit
   974      if a and b then break end       -- stop when no more errors
   975      collectgarbage()
   976      if not a and not    -- `real' error?
   977        (string.find(b, "memory") or string.find(b, "overflow")) then
   978        error(b, 0)   -- propagate it
   979      end
   980    end
   981    print("\nlimit for " .. s .. ": " .. M-oldM)
   982    return b
   983  end
   984  
   985  
   986  -- testing memory errors when creating a new state
   987  
   988  b = testamem("state creation", T.newstate)
   989  T.closestate(b);  -- close new state
   990  
   991  
   992  -- testing threads
   993  
   994  -- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1)
   995  mt = T.testC("rawgeti R 1; return 1")
   996  assert(type(mt) == "thread" and coroutine.running() == mt)
   997  
   998  
   999  
  1000  function expand (n,s)
  1001    if n==0 then return "" end
  1002    local e = string.rep("=", n)
  1003    return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n",
  1004                                e, s, expand(n-1,s), e)
  1005  end
  1006  
  1007  G=0; collectgarbage(); a =collectgarbage("count")
  1008  load(expand(20,"G=G+1"))()
  1009  assert(G==20); collectgarbage();  -- assert(gcinfo() <= a+1)
  1010  
  1011  testamem("thread creation", function ()
  1012    return T.doonnewstack("x=1") == 0  -- try to create thread
  1013  end)
  1014  
  1015  
  1016  -- testing memory x compiler
  1017  
  1018  testamem("loadstring", function ()
  1019    return load("x=1")  -- try to do load a string
  1020  end)
  1021  
  1022  
  1023  local testprog = [[
  1024  local function foo () return end
  1025  local t = {"x"}
  1026  a = "aaa"
  1027  for i = 1, #t do a=a..t[i] end
  1028  return true
  1029  ]]
  1030  
  1031  -- testing memory x dofile
  1032  _G.a = nil
  1033  local t =os.tmpname()
  1034  local f = assert(io.open(t, "w"))
  1035  f:write(testprog)
  1036  f:close()
  1037  testamem("dofile", function ()
  1038    local a = loadfile(t)
  1039    return a and a()
  1040  end)
  1041  assert(os.remove(t))
  1042  assert(_G.a == "aaax")
  1043  
  1044  
  1045  -- other generic tests
  1046  
  1047  testamem("string creation", function ()
  1048    local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end)
  1049    return (a == 'ablo ablo')
  1050  end)
  1051  
  1052  testamem("dump/undump", function ()
  1053    local a = load(testprog)
  1054    local b = a and string.dump(a)
  1055    a = b and load(b)
  1056    return a and a()
  1057  end)
  1058  
  1059  local t = os.tmpname()
  1060  testamem("file creation", function ()
  1061    local f = assert(io.open(t, 'w'))
  1062    assert (not io.open"nomenaoexistente")
  1063    io.close(f);
  1064    return not loadfile'nomenaoexistente'
  1065  end)
  1066  assert(os.remove(t))
  1067  
  1068  testamem("table creation", function ()
  1069    local a, lim = {}, 10
  1070    for i=1,lim do a[i] = i; a[i..'a'] = {} end
  1071    return (type(a[lim..'a']) == 'table' and a[lim] == lim)
  1072  end)
  1073  
  1074  testamem("constructors", function ()
  1075    local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5}
  1076    return (type(a) == 'table' and a.e == 5)
  1077  end)
  1078  
  1079  local a = 1
  1080  close = nil
  1081  testamem("closure creation", function ()
  1082    function close (b,c)
  1083     return function (x) return a+b+c+x end
  1084    end
  1085    return (close(2,3)(4) == 10)
  1086  end)
  1087  
  1088  testamem("coroutines", function ()
  1089    local a = coroutine.wrap(function ()
  1090                coroutine.yield(string.rep("a", 10))
  1091                return {}
  1092              end)
  1093    assert(string.len(a()) == 10)
  1094    return a()
  1095  end)
  1096  
  1097  do   -- auxiliary buffer
  1098    local lim = 100
  1099    local a = {}; for i = 1, lim do a[i] = "01234567890123456789" end
  1100    testamem("auxiliary buffer", function ()
  1101      return (#table.concat(a, ",") == 20*lim + lim - 1)
  1102    end)
  1103  end
  1104  
  1105  print'+'
  1106  
  1107  -- testing some auxlib functions
  1108  local function gsub (a, b, c)
  1109    a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c)
  1110    assert(b == 5)
  1111    return a
  1112  end
  1113  
  1114  assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//")
  1115  assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.")
  1116  assert(gsub("", "alo", "//") == "")
  1117  assert(gsub("...", ".", "/.") == "/././.")
  1118  assert(gsub("...", "...", "") == "")
  1119  
  1120  
  1121  -- testing luaL_newmetatable
  1122  local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3")
  1123  assert(type(mt_xuxu) == "table" and res and top == 3)
  1124  local d, res, top = T.testC("newmetatable xuxu; gettop; return 3")
  1125  assert(mt_xuxu == d and not res and top == 3)
  1126  d, res, top = T.testC("newmetatable xuxu1; gettop; return 3")
  1127  assert(mt_xuxu ~= d and res and top == 3)
  1128  
  1129  x = T.newuserdata(0);
  1130  y = T.newuserdata(0);
  1131  T.testC("pushstring xuxu; gettable R; setmetatable 2", x)
  1132  assert(getmetatable(x) == mt_xuxu)
  1133  
  1134  -- testing luaL_testudata
  1135  -- correct metatable
  1136  local res1, res2, top = T.testC([[testudata -1 xuxu
  1137     	 			  testudata 2 xuxu
  1138  				  gettop
  1139  				  return 3]], x)
  1140  assert(res1 and res2 and top == 4)
  1141  
  1142  -- wrong metatable
  1143  res1, res2, top = T.testC([[testudata -1 xuxu1
  1144  			    testudata 2 xuxu1
  1145  			    gettop
  1146  			    return 3]], x)
  1147  assert(not res1 and not res2 and top == 4)
  1148  
  1149  -- non-existent type
  1150  res1, res2, top = T.testC([[testudata -1 xuxu2
  1151  			    testudata 2 xuxu2
  1152  			    gettop
  1153  			    return 3]], x)
  1154  assert(not res1 and not res2 and top == 4)
  1155  
  1156  -- userdata has no metatable
  1157  res1, res2, top = T.testC([[testudata -1 xuxu
  1158  			    testudata 2 xuxu
  1159  			    gettop
  1160  			    return 3]], y)
  1161  assert(not res1 and not res2 and top == 4)
  1162  
  1163  -- erase metatables
  1164  do
  1165    local r = debug.getregistry()
  1166    assert(r.xuxu == mt_xuxu and r.xuxu1 == d)
  1167    r.xuxu = nil; r.xuxu1 = nil
  1168  end
  1169  
  1170  print'OK'
  1171