简单字符串缓冲区 |
|
以下元表生成器使语法更有趣。
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