我在写一个基于LPeg的解析器。我怎样才能让它解析错误返回nil, errmsg
?如何使用LPeg发出解析错误信号?
我知道我可以使用error()
,但据我所知,创建一个正常的错误,而不是nil, errmsg
。
的代码是pretty long,但相关的部分是:
local eof = lpeg.P(-1)
local nl = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n" + eof -- \r for winblows compat
local nlnoeof = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n"
local ws = lpeg.S(" \t")
local inlineComment = lpeg.P("`") * (1 - (lpeg.S("`") + nl * nl))^0 * lpeg.P("`")
local wsc = ws + inlineComment -- comments count as whitespace
local backslashEscaped
= lpeg.P("\\ ")/" " -- escaped spaces
+ lpeg.P("\\\\")/"\\" -- escaped escape character
+ lpeg.P("\\#")/"#"
+ lpeg.P("\\>")/">"
+ lpeg.P("\\`")/"`"
+ lpeg.P("\\n") -- \\n newlines count as backslash escaped
+ lpeg.P("\\") * lpeg.P(function(_, i)
error("Unknown backslash escape at position " .. i) -- this error() is what I wanna get rid of.
end)
local Line = lpeg.C((wsc + (backslashEscaped + 1 - nl))^0)/function(x) return x end * nl * lpeg.Cp()
我想Line:match(...)
返回nil, errmsg
当有一个无效的逃避。
你想达到什么目的?它是最小的例子吗?你尝试“返回”吗? – Jakuje
'error()'产生错误而不是'nil,errmsg'。如果反斜杠转义出现错误,我想'Line:match()'和'Data:match()'返回'nil,errmsg'。 – SoniEx2
@Jakuje实际上,我只需要'Line:match()'在无效转义时返回'nil,errmsg'。 – SoniEx2