I'm currently creating a search function in lua which basically just goes through a list of items and processes the items that match the input string in a specific way.
I use string.find(sourceString, inputString)
to identify the items.
The function is called whenever a user types something into a text field so if he t开发者_如何学运维ries to enter a pattern it happens that when using sets or captures the function is called when the search string just contains a [
or a
( without the closing equivalent which of cause throws an error.
The best way to go around this problem I think is to validate the input as beeing a valid pattern, but I've got no idea how to do this. Lua itself doesn't seem to contain a method for this and I am a bit confused of how to check it in a more or less performant way myself. Thanks for your help and ideas in advance :)
You should wrap the call to string.find
with pcall
to capture the error.
local status, result = pcall(string.find, sourceString, inputString)
if not status then
-- bad pattern logic, error message is in result
else
-- good pattern logic, result contains the start index
end
See this for pattern escape function (taken from somewhere in Lua Users wiki, I think). You may convert it to the validation function if you need.
精彩评论