Simple String Buffer

lua-users home
wiki

A simple way to avoid quadratic execution time when creating a string in pieces is to use a string buffer. The easiest way of doing this is to put the pieces into a table, and then concatenate them when you're done.

The following metatable generator makes this syntactically more interesting.

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

The simple strategy of always appending the new string chunk to a vector could be modified to use the Towers of Hanoi strategy, or some alternative.

Other possible enhancements include using a double-ended queue instead of a stack, to allow for concatenation on either side.

The metamethods were chosen to make assembly "look nice" (to me):

> 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


RecentChanges · preferences
edit · history
Last edited November 21, 2006 8:27 pm GMT (diff)