[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: How to make sure some operations in ANY situation? (aka: with statement in Python)
- From: Xavier Wang <weasley.wx@...>
- Date: Sat, 18 Jun 2011 12:20:02 +0800
hi all :)
I just found that the error/pcall/xpcall in lua is just like exceptions, you can report a error, and catch it like this:
function foo()
...
if notReady then error"not ready" end
...
end
if pcall(foo) then
...
end
but I still have some question about this Idiom:
1. how can I make sure some operations MUST happen?
xpcall may be can do this, but the errfunc may not called if f call success.
some pseudo-code:
local f = io.open("file")
-- do something maybe call error, but I don't want to catch the error, just want error spread outside of me, but I want f:close tobe called:
do
foo()
finally
f:close()
end
all I want is if (whatever) error in foo is throwing, the f:close will be called, but the error will still throw out of here.
2. how to re-throw err to outside?
if you call error in err function in xpcall, the err function will called again, and i can't spread err outside.
xpcall(function()
error"abc"
end, function(e)
print(e)
error(e)
end)
will call err function a lot of times. and the stack overflow...
3. how to handle multi return value of f?
how can I do this (pseudo-code):
function f() return 1, 2, 3 end
local status, retv... = pcall(f)
if status then
-- do sth with retv...
print(retv...)
else
print("error: ", retv...)
end
(to assign multiret into a "tuple", and extract it in other place)?
if error/pcall/xpcall can:
- make exception safe,
- rethow error outside, or process error but not touch it,
- handle function return value safely (don't miss any values).
I think we can use it to split normal process code and error process code, just like exceptions does.