xstring.lua

-- some extra string functions

-- Written by Rici Lake, released into the public domain. Use as you wish.

local coro = import "coro"
local yield, wrap = coro.yield, coro.wrap

local string = import "string"
local strfind, strsub = string.find, string.sub

return function(xstring)

  -- divide a string into two pieces at the indicated index.
  function xstring.divide(path, e)
    return strsub(path, 1, e), strsub(path, e + 1)
  end 

  local function splitCoro(str)
    local s, e = 1, 0
    local sep = yield()
    while s do
      local ee = e + 1
      local cap
      s, e, cap = strfind(str, sep, ee)
      if s then sep = yield(strsub(str, ee, s - 1), cap or sep)
           else sep = yield(strsub(str, ee), nil)
      end
    end
  end

  -- either an iterator or not, as you wish.
  -- iterator usage: for word, sep in xstring.splitter(str, pattern) do ... end
  -- generator usage:
  --   local words = xstring.splitter(str)
  --   while true
  --     local word, sep = words(pattern)
  --     ...
  --     if sep then break end
  --   end
  --
  -- Notes:
  --   1) sep is nil for the last word
  --   2) there is always at least one word
  --   3) don't use a nullable pattern with the iterator. It's
  --      ok with the generator (you could use this to ditch
  --      optional whitespace, for example)
  
  function xstring.splitter(str, sep)
    assert(sep and not strfind("", sep), "Don't split on nullable patterns")
    local rv = wrap(splitCoro)
    rv(str)
    return rv, sep
  end
  
  return xstring
end

Produced by TNT, the Lua-linter. TNT/0.5 Copyright (C) 2004 Rici Lake