lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Thu, Feb 10, 2022 at 12:34 AM Rodrigo Azevedo <rodrigoams@gmail.com> wrote:
Dear,
I have a small tool that uses a Lua pattern to select lines from a file.
Is there any way to test if the pattern string is indeed a valid Lua pattern and won't blow up string.find() ? Btw, is string.find() concerned about it?
--
Rodrigo

string.find and the other search functions do not validate the complete pattern before the match starts, so there's no magic way to determine whether the pattern is bad or not. Example:

Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
> string.find("", "a[")
nil
> string.find("aaa", "a[")
stdin:1: malformed pattern (missing ']')
stack traceback:
[C]: in function 'string.find'
stdin:1: in main chunk
[C]: in ?

What you can do is catch any error with 'pcall' or 'xpcall', but that's about it I think.

--