Main Menu

Custom text parsing

Started by SpencerWhite, Oct 07, 2018, 03:26 AM

Previous topic - Next topic

SpencerWhite

So, I made a simple text parser that can interpret one function (very simple, since this was just a proof of concept).
local methods = {
  {
    pattern = '^text (%d+) (%d+) (.+)',
    method  = function(a)
      x, y, text = unpack(a)

      x = tonumber(x)
      y = tonumber(y)
      text = tostring(text)

      term.setCursorPos(x,y)
      print(text)
    end
  }
}

function parseLine(line)
  for i = 1, #methods do
    local m = {line:match(methods[i].pattern)}
    if m ~= nil then
      methods[i].method(m)
      return
    end
  end
  error("Unrecognized function at line " .. lineNumber)
end

line = file.readLine()
while (line ~= nil)
  parseLine(line)
  line = file.readLine();
  lineNumber = lineNumber + 1
end

So, this is okay enough for what it does but it isn't very expandable. For example, if I wanted to write "text 1 1 6", it would work fine and just write 6 to the screen.. However, something such as "text 1 1 (string)3+3" would need an entirely different definition, even though it would technically do the same thing. Is there a way to let Lua interpret both examples?

KingofGamesYami

You'll want to avoid pattern matching and process the text one character at a time.  That's how real compilers do it.  What you want to do is called tokenizing.
I'm a ComputerCraft veteran with over 3k posts on the old ComputerCraft Forum.  I'm mostly inactive in CC having moved on to bigger, more interesting projects but still contribute to the community.