aff10c46c786a0b029d3d64bcda56dbf7cfe2dce
[metalua.git] / src / samples / trycatch_test.mlua
blobaff10c46c786a0b029d3d64bcda56dbf7cfe2dce
1 -{ extension 'trycatch' }
4 ----------------------------------------------------------------------
5 print "1) no error"
6 try
7    print("   Hi")
8 end
11 ----------------------------------------------------------------------
12 print "2) caught error"
13 try
14    error "some_error"
15 catch x then
16    printf("   Successfully caught %q", x)
17 end
20 -- [[
21 ----------------------------------------------------------------------
22 print "3) no error, with a finally"
23 try
24    print "   Hi"
25 finally
26    print "   Finally OK"
27 end
30 ----------------------------------------------------------------------
31 print "4) error, with a finally"
32 try
33    print "   Hi"
34    error "bang"
35 catch "bang"/_ then
36    print "   Bang caught"
37 finally
38    print "   Finally OK"
39 end
42 ----------------------------------------------------------------------
43 print "5) nested catchers"
44 try
45    try
46       error "some_error"
47    catch "some_other_error" then
48       assert (false, "mismatch, this must not happen")
49    end
50 catch "some_error"/x then
51    printf("   Successfully caught %q across a try that didn't catch", x)
52 catch x then
53    assert (false, "We shouldn't reach this catch-all")
54 end
57 ----------------------------------------------------------------------
58 print "6) nested catchers, with a 'finally in the inner one"
59 try
60    try
61       error "some_error"
62    catch "some_other_error" then
63       assert (false, "mismatch, this must not happen")
64    finally
65       print "   Leaving the inner try-catch"
66    end
67 catch "some_error"/{x} then
68    printf("   Successfully caught %q across a try that didn't catch", x)
69 catch x then
70    assert (false, "We shouldn't reach this catch-all")
71 end
74 ----------------------------------------------------------------------
75 print "7) 'finally' intercepts a return from a function"
76 function f()
77    try
78       print "   into f:"
79       return "F_RESULT"
80       assert (false, "I'll never go there")
81    catch _ then
82       assert (false, "No exception should be thrown")
83    finally
84       print "   I do the finally before leaving f()"
85    end
86 end
87 local fr = f()
88 printf("   f returned %q", fr)
91 ----------------------------------------------------------------------
92 print "8) don't be fooled by nested functions"
93 function f()
94    try
95       local function g() return "from g" end
96       printf("   g() returns %q", g())
97       return "from f"
98    catch _ then
99       assert (false, "No exception should be thrown")
100    end
102 local fr = f()
103 printf("   f returned %q", fr)
105 ----------------------------------------------------------------------
106 print "*) done."
108 --]]