--#!lua
-- Copyright (c) 2012 Oddstr13 <oddstr13@openshell.no>
-- License: MIT - http://www.opensource.org/licenses/mit-license.php
-- Filename: str

function split(s, sSeparator, nMax, bRegexp)
  -- http://lua-users.org/wiki/SplitJoin
  -- "Function: true Python semantics for split"
  assert(sSeparator ~= '')
  assert(nMax == nil or nMax >= 1)

  local aRecord = {}

  if s:len() > 0 then
    local bPlain = not bRegexp
    nMax = nMax or -1

    local nField=1 nStart=1
    local nFirst,nLast = string.find(s.."",sSeparator, nStart, bPlain)
    while nFirst and nMax ~= 0 do
      aRecord[nField] = string.sub(s.."",nStart, nFirst-1)
      nField = nField+1
      nStart = nLast+1
      nFirst,nLast = string.find(s.."",sSeparator, nStart, bPlain)
      nMax = nMax-1
    end
    aRecord[nField] = string.sub(s.."",nStart)
  end

  return aRecord
end

function join(t, sep)
  local result = ""
  for i=1,#t-1 do
    result = result  .. t[i] .. sep
  end
  result = result  .. t[#t]
  return result
end

function ljust(s, n, fill)
  if fill == nil then fill = " " end
  local result = s
  while #result < n do
    result = result .. fill
  end
  return result
end

function rjust(s, n, fill)
  if fill == nil then fill = " " end
  local result = s
  while #result < n do
    result = fill .. result
  end
  return result
end
