包装异常代码

是否有一种方法可以将赋值表达式包装在try/catch块中。

Window = {}
Window.mt = {}
Window.mt.__newindex =function(t,k,v)
         if k=="x" or k=="y" then error("只读字段", 2) end
         t[k]=v
end
--w是窗口 '类型'
--尝试捕捉此赋值
w.x = 50

谢谢 EM

点赞
用户1442917
用户1442917

Lua没有try/catch块,但提供pcall函数,该函数接受一个函数作为其参数(以及可选参数),并捕获/报告该函数中的运行时错误。

因此,您可能有类似于if not pcall(function() w.x = 50 end) then ... end的东西(假设错误以您期望的方式触发)。

2017-04-07 04:26:52
用户5787683
用户5787683

我是通过以下方式解决的:

local w = Window.new{height=150, Area=54}
function setValues(win)
  --强制错误
  win.x = 50
end

local status, err = pcall(setValues, w)
if err then
   print('错误',err)
else
   print('没有错误')
end
2017-04-11 19:42:44