strip関数とsplit関数

Luaにはstrip関数, split関数がない。

以下はstrip関数。

function strip(s)
  return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end

以下はsplit関数。

function split(s, delim)
  local is, ie
  local t = {}
  -- タブ・空白で分割
  if not delim then
    for v in s:gmatch('(%S+)') do
      table.insert(t, v)
    end
    return t
  end
  -- デリミタで分割
  while true do
    is, ie = s:find(delim)
    if not is then
      table.insert(t, s)
      break
    end
    if is == 1 then
      table.insert(t, '')
    else
      table.insert(t, s:sub(1, is-1))
    end
    s = s:sub(ie+1)
  end
  return t
end

以下は簡易的なsplit処理。

> -- タブ・空白で分割
> line = 'a  b  c'
> t={}; line:gsub('(%S+)', function (v) table.insert(t, v) end)    -- 方法1
> t={}; for v in line:gmatch('(%S+)') do table.insert(t, v) end    -- 方法2
> for i,v in ipairs(t) do print(i,v) end
1       a
2       b
3       c
>
> -- カンマで分割
> line = 'a,b,,d'
> line = line:gsub(',', ' , ')
> t={}; for v in line:gmatch('([^,]+)') do v=strip(v); table.insert(t, v) end
> for i,v in ipairs(t) do print(i,v) end
1       a
2       b
3
4       d