2015-08-16 63 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 - 感谢您所做的编辑。 –