1

I'm trying to make a function that searches through some code to find the line the search term is on, as well as the line's index. The code is a multi line string with new line characters. I was thinking of using gmatch to do this, but I have no clue how.

This is my code at the moment. It's awful, but I can't think of a way to make it any better:

local function search( code, term )
  local matches = {}
  local i = 0
  for line in string.gmatch( code, "[^\r\n]+" ) do
    i = i + 1
    if string.find( line, term, 1, true ) then
      table.insert( matches, { line = i, code = line } )
    end
  end
  return matches
end

Any help would be appreciated!

3
  • To correctly count empty lines: for line in string.gmatch( code, "([^\r\n]*)\r?\n?" ) do Commented Jul 17, 2017 at 12:11
  • Why do you find this code is awful? Commented Jul 17, 2017 at 13:21
  • @lhf it goes through every single line one by one just to see if one of the lines has the correct string, rather than looking at the lines as a whole, which I feel it could as it's a single string. Also, the part where I add 1 to I feels wrong. I'm used to k and v when looping. Commented Jul 17, 2017 at 13:25

1 Answer 1

2

Your solution seem fine to me. The problem with using a single gmactch loop is your requirement to report line numbers. The code below avoids this by embedding line numbers into the code. I've use @ to mark line numbers. You can use any char that does not appear in the source code, even something like \0.

function search(code,term)
    for a,b in code:gmatch("@(%d+):([^\n]-"..term.."[^\n]-)\n") do
        print(a)
        print(b)
    end
end

local n=0
code="\n"..code
code=code:gsub("\n", function () n=n+1 return "\n@"..n..":" end)

search(code,"matc")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.