|
于 2014-1-18 0:33, Elias Barrionovo 写道:
On Fri, Jan 17, 2014 at 2:19 PM, Andrew Starks <andrew.starks@trms.com> wrote:Seems like it would be nicer if assert respected __tostring, as error does. Whenever I think this, someone explains a great answer for it. In three, two, one...I always thought assert() called error() internally. Why isn't it the case? Apart maybe from the stacktrace, isn't the following function equivalent to assert()? -- untested function myAssert(cond, ...) if cond then return cond, ... else error(...) end end
IMHO, `assert' and `error' have quite different semantics and use cases. For me, it is prefered to use `error' together with `pcall/xpcall' to express the protected (and mostly expectable or recoverable) semantic like the try/catch constructs of exception handling mechanisms in some other languages. On the other hand, I would use `assert' to express contracts that must be met, otherwize it _must_ fail aloud and not expected to be protected or recovered. So, it is quite reasonable for me that `assert' only accept a string message, since it is to give the (interactive session) user some clue about what went wrong, instead of to give `pcall' the `error object' to examine (and maybe to retry or recover) in a programamtic way, in which case `error' should be used.