解析Lua字符串,更具体地说是换行符

时间:2017-10-14 16:24:12

标签: parsing lua

我正在尝试解析Lua 5.3字符串。但是,我遇到了一个问题。例如,

$ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> print(load('return "\\z \n\r \n\r \r\n \n \n \\x"', "@test"))
nil test:6: hexadecimal digit expected near '"\x"'
> 
> print(load('return "\\z\n\r\n\r\r\n\n\n\\x"', "@test"))
nil test:6: hexadecimal digit expected near '"\x"'

第6行上的这两个错误,以及背后的逻辑非常简单:如果它们与当前字符不同,请使用换行符(\ r或\ n)(我相信这是对如何准确描述lua lexer工作,但我可能错了。)

我有这个代码,应该这样做:

local ln = 1
local skip = false
local mode = 0
local prev
for at, crlf in eaten:gmatch('()[\r\n]') do
  local last = eaten:sub(at-1, at-1)
  if skip and prev == last and last ~= crlf then
    skip = false
  else
    skip = true
    ln = ln + 1
  end
  prev = crlf
end

它决定是否根据之前的字符吃掉换行符。现在,从我所知道的,这个应该工作,但无论我做什么它似乎都不起作用。其他尝试使其报告5行,而这一行使其报告9(!)。我在这里错过了什么?我在Lua 5.2.4上运行它。

这是解析\z的例程的一部分:

local function parse52(s)
  local startChar = string.sub(s,1,1)
  if startChar~="'" and startChar~='"' then
    error("not a string", 0)
  end
  local c = 0
  local ln = 1
  local t = {}
  local nj = 1
  local eos = #s
  local pat = "^(.-)([\\" .. startChar .. "\r\n])"
  local mkerr = function(emsg, ...)
    error(string.format('[%s]:%d: ' .. emsg, s, ln, ...), 0)
  end
  local lnj
  repeat
    lnj = nj
    local i, j, part, k = string.find(s, pat, nj + 1, false)
    if i then
      c = c + 1
      t[c] = part
      if simpleEscapes[v] then
        --[[ some code, some elseifs, some more code ]]
      elseif v == "z" then
        local eaten, np = s:match("^([\t\n\v\f\r ]*)%f[^\t\n\v\f\r ]()", nj+1)
        local p=np
        nj = p-1
        --[[ the newline counting routine above ]]
        --[[ some other elseifs ]]
      end
    else
      nj = nil
    end
  until not nj
  if s:sub(-1, -1) ~= startChar then
    mkerr("unfinished string near <eof>")
  end
  return table.concat(t)
end

1 个答案:

答案 0 :(得分:1)

用于迭代Lua脚本行的紧凑代码:

application

迭代Lua脚本行的高效代码:

local text = "First\n\r\n\r\r\n\n\nSixth"
local ln = 1
for line, newline in text:gmatch"([^\r\n]*)([\r\n]*)" do
   print(ln, line)
   ln = ln + #newline:gsub("\n+", "\0%0\0"):gsub(".%z.", "."):gsub("%z", "")
end