Search code examples
luapattern-matchinglua-patternsluajit

Applying quantifier to a sentence in Lua pattern


So I am trying to parse out #define statements out of a C file using Lua patterns, but there is the case on multiline defines, where you might escape the newline character with a backslash.

In order for me to know where the define ends, I need to be able to define backslash + linebreak as if it were a single character so I can get the complement of that and then use the * quantifier on it and then count until the first non-escaped linebreak.

How do I do that?


Solution

  • You cannot simply replace all occurrences of "\\\n" with some temporary symbol, because a problem will arise with the line "c\\\\\n" in the following example.
    Instead, you should implement mini-scanner for C source files:

    local str = [[
    #define x y
    #define a b\
    c\\
    d();
    #define z
    ]]
    
    -- Print all #defines found in the text
    local line = ""
    for char in str:gmatch"\\?." do
       if char == "\n" then
          if line:sub(1, #"#define") == "#define" then
             print(line)
          end
          line = ""
       else
          line = line..char
       end
    end
    

    Output:

    #define x y
    #define a b\
    c\\
    #define z