Added Lua towers_of_hanoi example
[langlearn/.git] / towers_of_hanoi / lua / MaximumGeeker / hanoi.lua
1 --[[ Towers of hanoi - Lua 5.1 ]]--
2
3 local move = function(a, b)
4   print( a, '->', b )
5 end
6
7 local hanoi
8 hanoi = function(n, orig, pivot, dest)
9   if n < 1 then
10     return
11   end
12
13   if n == 1 then
14     move( orig, dest )
15     return
16   end
17
18   if n == 2 then
19     move( orig, pivot )
20     move( orig, dest )
21     move( pivot, dest )
22     return
23   end
24
25   hanoi(n-2, orig, pivot, dest)
26   move( orig, pivot )
27   hanoi(n-2, dest, orig, pivot)
28   move( orig, dest )
29   hanoi(n-1, pivot, orig, dest)
30 end
31
32 io.write "Value of N: "
33 local n = io.read "*n"
34
35 if type(n) == 'number' then
36   n = math.floor(n)
37 else
38   io.stderr "Value given is not a number.\n"
39   os.exit(1)
40 end
41
42 hanoi(n, 'Left', 'Center', 'Right')