github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/lib/base/lua/xpcall.lua (about) 1 -- A function that produces an error 2 function foo(x) bar(x) end 3 function bar(x) baz(x) end 4 function baz(x) error(x, 0) end 5 6 -- A dummy error handler 7 function bye() return "bye" end 8 9 print(xpcall(foo, print, "hello")) 10 --> =hello 11 --> =false nil 12 13 print(xpcall(foo, bye, "hello")) 14 --> =false bye 15 16 -- pcall within xpcall 17 18 print(xpcall(pcall, print, foo, "hello")) 19 --> =true false hello 20 21 -- xpcall within pcall 22 23 print(pcall(xpcall, foo, print, "hello")) 24 --> =hello 25 --> =true false nil 26 27 -- Nested xpcalls 28 print(xpcall( 29 function() 30 print(xpcall(foo, bye, "hi")) 31 foo("bonjour") 32 end, 33 print 34 )) 35 --> =false bye 36 --> =bonjour 37 --> =false nil 38 39 -- error in message handler, we eventually bail out 40 print(xpcall(error, error, "foo")) 41 --> =false error in error handling 42 43 -- It tries handling the error at least 10 times but at most 100 times 44 45 n = 0 46 function err(e) 47 n = n + 1 48 error(e) 49 end 50 51 print(xpcall(error, err, "hello")) 52 --> =false error in error handling 53 print(n >= 10 and n <= 100) 54 --> =true 55 56 -- Error handlers are just called once. 57 t = {} 58 debug.setmetatable(t, {__index=function() error("abc", 0) end}) 59 60 function p(x) 61 print("debug", x) 62 return x 63 end 64 65 print(xpcall(function() return t[1] end, p)) 66 --> =debug abc 67 --> =false abc