title: Lua split string to table
body: <p>I'm looking for the most efficient way to split a Lua string into a table.</p>
  <p>I found two possible ways using <code>gmatch</code> or <code>gsub</code> and tried to make them as fast as possible.</p>
  <pre><code>function string:split1(sep)
      local sep = sep or &quot;,&quot;
      local result = {}
      local i = 1
      for c in (self..sep):gmatch(&quot;(.-)&quot;..sep) do
          result[i] = c
          i = i + 1
      end
      return result
  end
  
  function string:split2(sep)
     local sep = sep or &quot;,&quot;
     local result = {}
     local pattern = string.format(&quot;([^%s]+)&quot;, sep)
     local i = 1
     self:gsub(pattern, function (c) result[i] = c i = i + 1 end)
     return result
  end
  </code></pre>
  <p>The second option takes ~50% longer than the first.</p>
  <p>What is the right way and why?</p>
  <p>Added: I added a third function with the same pattern.
  It shows the best result.</p>
  <pre><code>function string:split3(sep)
      local sep = sep or &quot;,&quot;
      local result = {}
      local i = 1
      for c in self:gmatch(string.format(&quot;([^%s]+)&quot;, sep)) do
          result[i] = c
          i = i + 1
      end
      return result
  end
  </code></pre>
  <p><code>&quot;(.-)&quot;..sep</code> - works with a sequence.</p>
  <p><code>&quot;([^&quot; .. sep .. &quot;]+)&quot;</code> works with a single character. In fact, for each character in the sequence.</p>
  <p><code>string.format(&quot;([^%s]+)&quot;, sep)</code> is faster than <code>&quot;([^&quot; .. sep .. &quot;]+)&quot;</code>.</p>
  <p>The <code>string.format(&quot;(.-)%s&quot;, sep)</code> shows almost the same time as <code>&quot;(.-)&quot;..sep</code>.</p>
  <p><code>result[i]=c i=i+1</code> is faster than <code>result[#result+1]=c</code> and <code>table.insert(result,c)</code></p>
  <p>Code for test:</p>
  <pre><code>local init = os.clock()
  local initialString = [[1,2,3,&quot;afasdaca&quot;,4,&quot;acaac&quot;]]
  local temTable = {}
  for i = 1, 1000 do
      table.insert(temTable, initialString)
  end
  local dataString = table.concat(temTable,&quot;,&quot;)
  print(&quot;Creating data: &quot;.. (os.clock() - init))
      
  init = os.clock()
  local data1 = {}
  for i = 1, 1000 do
      data1 = dataString:split1(&quot;,&quot;)
  end
  print(&quot;split1: &quot;.. (os.clock() - init))
  
  init = os.clock()
  local data2 = {}
  for i = 1, 1000 do
      data2 = dataString:split2(&quot;,&quot;)
  end
  print(&quot;split2: &quot;.. (os.clock() - init))
  
  init = os.clock()
  local data3 = {}
  for i = 1, 1000 do
      data3 = dataString:split3(&quot;,&quot;)
  end
  print(&quot;split3: &quot;.. (os.clock() - init))
  </code></pre>
  <p>Times:</p>
  <pre><code>Creating data: 0.000229
  split1: 1.189397
  split2: 1.647402
  split3: 1.011056
  </code></pre>