lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 23/07/18 14:26, Axel Kittenberger wrote:
>> To write an efficient pure Lua routine is possible, but quite challenging.
> 
> an O( n * log( n ) ) one:
> """
> function _concat( t, p, n )
>     if n > 1 then
>         local n2 = n // 2
>         return _concat( t, p, n2 ) .. _concat( t, p + n2, n - n2 )
>     end
>     return t[ p ]
> end
> 
> function concat( tbl )
>     return _concat( tbl, 1, #tbl )
> end
> """
> For lua < 5.3 use math.floor( n / 2) or math.ceil, or round or whatever, it
> doesn't matter.

How about:

function concat(list, sep, i, j)
  i = i or 1
  j = j or #list

  local tmp = {}
  for i=1,#list do
    tmp[i] = tostring(list[i])
  end
  return table.concat(tmp, sep, i, j)
end

Which would just be O(n)?

Might be able to improve with table.pack/unpack, maybe.

Scott