主要思想:搜索相邻的山雀()()
!
local line_no = 12
local str = [[
print("foo")
local nif_nif
= FUNCTION (
FUNCTION 'beta' { 'gamma' } ()
and 'epsilon'
or 'zeta'
)
{
'eta'
}
local nuf_nuf
= FUNCTION ( -- this is line#12
FUNCTION 'beta' { 'gamma' } ()
and 'epsilon'
or 'zeta'
)
{
'eta'
} -- should be cut from here
local naf_naf
= FUNCTION (
FUNCTION 'beta' { 'gamma' } ()
and 'epsilon'
or 'zeta'
)
{
'eta'
}
print("bar")
]]
-- cut all text before target "local" keyword
str = str:gsub('\n','\0',line_no):gsub('^.*(local.-%z)','%1'):gsub('%z','\n')
-- enclose string literals and table constructors into temporary parentheses
str = str:gsub('%b""','(\0%0\0)')
:gsub("%b''",'(\0%0\0)')
:gsub("%b{}",'(\0%0\0)')
-- replace text in parentheses with links to it
local n, t = 0, {}
str = str:gsub('%b()', function(s) n=n+1 t[n..'']=s return'<\0'..n..'>' end)
-- search for first chained function call and cut it out
str = str:gsub('^.-<%z%d+>%s*<%z%d+>', '')
repeat
local ctr
str, ctr = str:gsub('^%s*<%z%d+>', '')
until ctr == 0
-- replace links with original text
t, str = nil, str:gsub('<%z(%d+)>', t)
-- remove temporary parentheses
str = str:gsub('%(%z', ''):gsub('%z%)', '')
print(str)
输出:
-- should be cut from here
local naf_naf
= FUNCTION (
FUNCTION 'beta' { 'gamma' } ()
and 'epsilon'
or 'zeta'
)
{
'eta'
}
print("bar")