Вы можете использовать функцию поиска простой строки, чтобы вам не приходилось заботиться о экранировании магических символов.
https://www.lua.org/manual/5.3/manual.html#pdf-string.find
-- input: str, string to seperate
-- b1, border symbol 1
-- b2, border symbol 2
-- incl, true to include the border symbols in the returned value
-- return: sub, the substring between the border symbols
-- or nil if the border symbols don't appear in str
local function border(str, b1, b2, incl)
local sub
local i = str:find(b1, 1, true) -- using 'plain' means no escaping of magic
if i == nil then return nil end -- characters
local j = str:find(b2, i+1, true)
if j == nil then return nil end
if incl then
sub = str:sub(i, j)
else
sub = str:sub(i+1,j-1)
end
return sub
end
local test1 = "hello(world)"
local test2 = "(hello] world"
local test3 = "(hello-)(+world)"
local test4 = "hello, world"
print()
print(border(test1, '(', ')', true))
print(border(test1, '(', ')', false),"\n")
print(border(test2, '(', ']', true))
print(border(test2, '(', ']', false),"\n")
print(border(test3, '-', '+', true))
print(border(test3, '-', '+', false),"\n")
print(border(test4, ',', ',', true))
print(border(test4, ',', ',', false),"\n")
выведет:
> lua border.lua
(world)
world
(hello]
hello
-)(+
)(
nil
nil