2007年 05月 04日

Lua try catch

pcall とかいう安全な関数呼出なんていう関数があるんだけど、つかいにくい。

ok, err = pcall(function ()
end)
if not ok then exit end

みたいな。

function try(tryFun)
	local suc, err = pcall(tryFun)
	return {
		catch = function (catchFun)
			if not suc then
				catchFun(err)
			end
		end
	}
end


try(function ()
	print "hoge"
	error("error")
end).catch(function (e)
	print(e)
	print "Catched"
end)

とかやってみる。Io の try catch に似てる構造