2016年11月4日金曜日

Lua 例外処理 try-catch

Luaには、直接的な例外処理はないみたいなので
pcallを応用して、try-catch的なものを代替わり案としてみる。

--
-- try-catch関数
--

function try_catch(what)
  local status, result = pcall(what.try)
  if not status then
    what.catch(result)
  end
  return result
end


--
-- 使い方
--
  try_catch{
    try=function()
      -- 何か実行する
    end,
    catch=function(error)
      print("caught error " .. error)
    end
  }

0 件のコメント: