2015-08-16 57 views
1

我找到了一個代碼,當我在MUD上玩筆記時想用。每個音符的線條長度只能爲79個字符,因此除非您要計算字符,否則有時會寫一個音符很麻煩。代碼如下:Lua線包裹不包含某些字符

function wrap(str, limit, indent, indent1) 
    indent = indent or "" 
    indent1 = indent1 or indent 
    limit = limit or 79 
    local here = 1-#indent1 
    return indent1..str:gsub("(%s+)()(%S+)()", 
          function(sp, st, word, fi) 
          if fi-here > limit then 
           here = st - #indent 
           return "\n"..indent..word 
          end 
          end) 
end 

這會工作得很好;我可以輸入一個300字符的行,並將它格式化爲79個字符,尊重整個單詞。

我遇到的問題,我似乎無法弄清楚如何解決,有時候,我想爲行添加顏色代碼,並且顏色代碼不計算在字數上。例如:

@GThis is a colour-coded @Yline that should @Bbreak off at 79 @Mcharacters, but ignore @Rthe colour codes (@G, @Y, @B, @M, @R, etc) when doing so. 

從本質上講,它會去掉顏色代碼並適當地打破行,但不會丟失顏色代碼。

編輯包括它應該檢查什麼,以及最終輸出應該是什麼。

該功能只檢查下面的換行符的字符串:

This is a colour-coded line that should break off at 79 characters, but ignore the colour codes (, , , , , etc) when doing so. 

,但實際上將返回:

@GThis is a colour-coded @Yline that should @Bbreak off at 79 @Ncharacters, but ignore 
the colour codes (@G, @Y, @B, @M, @R, etc) when doing so. 

更爲複雜的是,我們也有xterm的顏色代碼,這是類似,但看起來像這樣:

@x123 

它是總是@x後跟一個3位數字。最後,爲了使事情進一步複雜化,我不希望它去除目的顏色代碼(這將是@@ R,@ @ x123等)。

有沒有一個乾淨的方式做到這一點,我失蹤了?

+0

我有點被你的意思是「忽略」了什麼感到困惑。你能提供你期望的輸出嗎? –

+0

可以在同一個單詞中使用多種顏色(例如'@ RL @ Gu @ Ba')? –

+0

@EgorSkriptunoff,是的。如果我想要的話,我可以爲每個字母使用不同的顏色代碼。例如'@ x123L @ Ru @ x032a'。 – Josh

回答

1
function(sp, st, word, fi) 
    local delta = 0 
    word:gsub('@([@%a])', 
    function(c) 
     if c == '@'  then delta = delta + 1 
     elseif c == 'x' then delta = delta + 5 
     else     delta = delta + 2 
     end 
    end) 
    here = here + delta 
    if fi-here > limit then 
    here = st - #indent + delta 
    return "\n"..indent..word 
    end 
end 
+0

你,先生,是個天才。我編輯了這篇文章,因爲當它需要'if c =='@''時,你有'if c ='@''。感謝您快速提出解決方案! – Josh

+0

顯示我的編輯未被批准。無論如何,請參閱以前的評論,瞭解所需的編輯更改。再次感謝! – Josh

+0

@Josh - 感謝您所做的編輯。 –