db-mini.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. -- testing debug library
  2. local a =1
  3. local function multi_assert(expected,...)
  4. local arg = {...}
  5. for i = 1, #arg do
  6. assert(arg[i]==expected[i])
  7. end
  8. end
  9. local function test_locals(x,...)
  10. local b ="local b"
  11. assert(debug.getlocal(test_locals,1) == "x")
  12. multi_assert({"x",1},debug.getlocal(1,1))
  13. multi_assert({"b","local b"},debug.getlocal(1,2))
  14. multi_assert({"(vararg)",2},debug.getlocal(1,-1))
  15. multi_assert({"(vararg)",3},debug.getlocal(1,-2))
  16. multi_assert({"a",1},debug.getlocal(2,1))
  17. assert(debug.setlocal(2,1,"new a") == "a")
  18. end
  19. test_locals(1,2,3)
  20. assert(a == "new a")
  21. local function test_upvalues()
  22. local a =3
  23. local function f(x)
  24. local b = a + x
  25. local function g(y)
  26. local c = b + y
  27. local function h()
  28. return a+b+c
  29. end
  30. multi_assert({"a",3},debug.getupvalue(h,1))
  31. multi_assert({"b",4},debug.getupvalue(h,2))
  32. multi_assert({"c",6},debug.getupvalue(h,3))
  33. multi_assert({"b",4},debug.getupvalue(g,1))
  34. multi_assert({"a",3},debug.getupvalue(g,2))
  35. multi_assert({"a",3},debug.getupvalue(f,1))
  36. debug.setupvalue(h,1,10)
  37. debug.setupvalue(h,2,20)
  38. debug.setupvalue(h,3,30)
  39. assert(h() == 60)
  40. end
  41. g(2)
  42. end
  43. f(1)
  44. end
  45. test_upvalues()
  46. local mt = {
  47. __metatable = "my own metatable",
  48. __index = function (o, k)
  49. return o+k
  50. end
  51. }
  52. debug.setmetatable(10, mt)
  53. assert(debug.getmetatable(10) == mt)
  54. a = 10
  55. assert( a[3] == 13)
  56. assert(debug.traceback(print)==print)
  57. assert(debug.traceback(print)==print)
  58. assert(type(debug.getregistry())=="table")