簡易字串緩衝

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 (diff)