Lua 行绕行,不包括某些字符。

我找到了一个代码,当我写关于我玩的 MUD 的笔记时想要使用。每个注释的行只能有 79 个字符,所以有时候写注释是很麻烦的,除非你在数字符号。以下是代码:

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 等)。

有没有什么干净的方法可以解决这个问题?

点赞
用户1847592
用户1847592
```lua
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

spstwordfi 传入该函数,函数内定义了变量 delta,初始化为 0word:gsub('@([@%a])', function(c) ... end) 用于将 word 字符串内所有出现 @ 开头的字符换成相应的数字,每换一个增加 delta 的值,最后加上 delta,并与 limit 比较大小。若 fi - here 大于 limit,则将 here 设为 st 减去 indent 的长度再加上 delta,返回一个以 \n 开头,紧跟 indentword 的字符串。

2015-08-16 08:54:03