2017-10-14 29 views
1

我試圖解析Lua 5.3字符串。但是,我遇到了一個問題。例如,解析Lua字符串,更具體地說是換行

$ 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詞法分析器是如何工作的,但我可能是錯的)。

我有這樣的代碼,它應該這樣做:

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一個例程的一部分:用於重複的Lua腳本的線

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 
+0

'crlf' is總是'nil',因爲'eaten:gmatch('()[\ r \ n]')'只返回一次捕獲。可能你想讓你的模式成爲'()([\ r \ n])'? –

+0

@EgorSkriptunoff解決了它,但我不能接受評論作爲答案。 – SoniEx2

+0

是的,這是SO的一個臭名昭着的錯誤特徵:評論是不允許被接受的,儘管可能包含一個答案:-) –

回答

0

緊湊代碼:

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 

高效代碼用於重複的Lua腳本的行:

local text = "First\n\r\n\r\r\n\n\nSixth" 
local sub = string.sub 
local ln = 1 
for line, newline in text:gmatch'([^\r\n]*)([\r\n]*)' do 
    print(ln, line) 
    local pos, max_pos = 1, #newline 
    while pos <= max_pos do 
     local crlf = sub(newline, pos, pos + 1) 
     if crlf == "\r\n" or crlf == "\n\r" then 
     pos = pos + 2 
     else 
     pos = pos + 1 
     end 
     ln = ln + 1 
    end 
end 
+0

這是爲了緊湊,但效率如何?我不是迭代Lua腳本的行,而是解析字符串。 – SoniEx2

+0

我喜歡你的解決方案。這就是說,這不是我用例的最佳解決方案。看到我更新的問題。 – SoniEx2