2017-04-06 53 views
1

有没有办法在try/catch块中包装赋值表达式。包装异常代码

Window = {} 
Window.mt = {} 
Window.mt.__newindex =function(t,k,v) 
     if k=="x" or k=="y" then error("Readonly field", 2) end 
     t[k]=v 
end 
--w is a window 'type' 
--try/catch this assignment 
w.x = 50 

感谢 EM

+0

https://www.lua.org/manual/5.3/manual.html#2.3也https://www.lua.org/manual/ 5.3/manual.html#2.4您发布的代码不会像这样运行。 w是零,因此不能被索引,并且你没有在任何地方设置Window的metatable。 – Piglet

回答

2

Lua中没有try/catch块,但提供pcall函数接受一个函数作为它的参数(可选参数)和渔获量/报告运行时错误的该功能。

所以,你可能有这样的东西if not pcall(function() w.x = 50 end) then ... end(假设错误以你期望的方式触发)。

0

我这样想通了:

local w = Window.new{height=150, Area=54}  
function setValues(win)       
    --force an error        
    win.x = 50          
end          

local status, err = pcall(setValues, w) 
if err then 
    print('Error',err) 
else 
    print('No errors') 
end