200-examples.t.txt 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #! /usr/bin/lua
  2. --
  3. -- lua-TestMore : <http://fperrad.github.com/lua-TestMore/>
  4. --
  5. -- Copyright (C) 2009-2011, Perrad Francois
  6. --
  7. -- This code is licensed under the terms of the MIT/X11 license,
  8. -- like Lua itself.
  9. --
  10. --[[
  11. =head1 some Lua code examples
  12. =head2 Synopsis
  13. % prove 200-examples.t
  14. =head2 Description
  15. First tests in order to check infrastructure.
  16. =cut
  17. --]]
  18. require 'Test.More'
  19. plan(5)
  20. function factorial (n)
  21. if n == 0 then
  22. return 1
  23. else
  24. return n * factorial(n-1)
  25. end
  26. end
  27. is(factorial(7), 5040, "factorial (recursive)")
  28. local function local_factorial (n)
  29. if n == 0 then
  30. return 1
  31. else
  32. return n * local_factorial(n-1)
  33. end
  34. end
  35. is(local_factorial(7), 5040, "factorial (recursive)")
  36. function loop_factorial (n)
  37. local a = 1
  38. for i = 1, n, 1 do
  39. a = a*i
  40. end
  41. return a
  42. end
  43. is(loop_factorial(7), 5040, "factorial (loop)")
  44. function iter_factorial (n)
  45. local function iter (product, counter)
  46. if counter > n then
  47. return product
  48. else
  49. return iter(counter*product, counter+1)
  50. end
  51. end
  52. return iter(1, 1)
  53. end
  54. is(iter_factorial(7), 5040, "factorial (iter)")
  55. --[[
  56. Knuth's "man or boy" test.
  57. See http://en.wikipedia.org/wiki/Man_or_boy_test
  58. ]]
  59. local function A (k, x1, x2, x3, x4, x5)
  60. local function B ()
  61. k = k - 1
  62. return A(k, B, x1, x2, x3, x4)
  63. end
  64. if k <= 0 then
  65. return x4() + x5()
  66. else
  67. return B()
  68. end
  69. end
  70. is(A(10,
  71. function () return 1 end,
  72. function () return -1 end,
  73. function () return -1 end,
  74. function () return 1 end,
  75. function () return 0 end),
  76. -67,
  77. "man or boy"
  78. )
  79. -- Local Variables:
  80. -- mode: lua
  81. -- lua-indent-level: 4
  82. -- fill-column: 100
  83. -- End:
  84. -- vim: ft=lua expandtab shiftwidth=4: