Lua Regex 函数声明

我想从一个 Lua 文件中解析出所有 lua 函数的声明。例如,假设我有以下代码:

function foo(a, b, c)
    local d = a + b
    local e = b - c
    return d *e
end

function boo(person)
    if (person.age == 18) then
        print("成年人")
    else
        print("孩子")
    end

    if (person.money > 20000) then
        print("富人")
    else
        print("穷人")
    end
end

我希望得到这个结果:

第一组:
    local d = a + b
    local e = b - c
    return d *e

第二组:
    if (person.age == 18) then
        print("成年人")
    else
        print("孩子")
    end

    if (person.money > 20000) then
        print("富人")
    else
        print("穷人")
    end

基本上,我想要函数体,换句话说,从函数声明到最后一个 end 之间的所有内容。然而,我想到了这个:

(?<=function)(.*?)(?=end)

感谢你们的回答。

点赞
用户107090
用户107090

如果您的函数定义都从第一列开始并在第一列结束,则这将起作用:

L=[[

function foo(a, b, c)
    local d = a + b
    local e = b - c
    return d *e
end

function boo(person)
    if (person.age == 18) then
        print("Adult")
    else
        print("Kid")
    end

    if (person.money > 20000) then
        print("Rich")
    else
        print("poor")
    end
end
]]

for b in L:gmatch("\nfunction.-\n(.-)\nend") do
    print("------------------")
    print(b)
end

请注意,您需要在您的代码顶部插入一个空行以查找第一个函数。

2017-02-13 19:17:44