简单字符串缓冲区

lua-users home
wiki

在分段创建字符串时,避免二次执行时间的一种简单方法是使用字符串缓冲区。最简单的方法是将这些片段放入一个表中,然后在完成后将它们连接起来。

以下元表生成器使语法更有趣。

function stringbufFactory(default_sep)
  local meta = {}
  function meta:__div(sep)
    if getmetatable(self) ~= meta then self, sep = sep, self end
    return table.concat(self, sep)
  end
  function meta:__unm() return self / default_sep end
  function meta:__call(str) table.insert(self, str); return self end
  
  return function(...) return setmetatable(arg, meta) end
end

始终将新的字符串块追加到向量的简单策略可以修改为使用汉诺塔策略或其他策略。

其他可能的增强包括使用双端队列而不是堆栈,以允许在任一侧进行连接。

元方法的选择是为了使程序集“看起来不错”(对我来说)

> L = stringbufFactory "\n"

-- This syntax won't work in the standalone interpreter, thus the do and end
> story = "It was a dark and stormy night, when nothing happened"
> do
Prose = -L 
   "The following story has been contributed:"
   "" (story)
   ""
   " -- 30 -- "
   ""
-- see the Lua Book for an explanation of the final ""
end

> =Prose
The following story has been contributed:

It was a dark and stormy night, when nothing happened

 -- 30 -- 

> -- This example will work fine in the standalone interpreter:

> C = stringbufFactory ", "
> vars1 = -C "a" "b" "c"

> S = stringbufFactory ""
> vars2 = ", " / S "a" "b" "c"
> -- or, depending on taste
> vars3 = S "a" "b" "c" / ", "
> =vars1
a, b, c
> =vars2
a, b, c
> =vars3
a, b, c


最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2006 年 11 月 21 日下午 8:27 GMT (差异)