it is worthwhile to become familiar with lua’s standard table library, in particular unpack and move.
most of the functions in table operate in place. {table.unpack(t)} is a quick-and-dirty method to clone a (flat) table if you want to return a copy.
here’s how i might implement those operations using the standard library.
t_print = function(t) for i,v in ipairs(t) do print(i, v) end print('') end
t = {'foo', 'bar', 'baz', 'zip', 'zap', 'rap' }
z = {'one','two','three'}
-- return first `n` entries
function t_take(t, n)
return table.pack(table.unpack(t, 1, n))
end
t_print(t_take(t, 3))
--- return the last 'n' entries
function t_drop(t, n)
return table.pack(table.unpack(t, #t - n + 1, #t))
end
t_print(t_drop(t, 3))
-- add contents of `t2` to end of `t1`
function t_append(t1, t2)
local t_new = {table.unpack(t1)}
return table.move(t2, 1, #t2, #t1+1, t_new)
end
t_print(t_append(t, z))
-- remove the first `n` elements of `t` and add them to the end
function t_rotate(t, n)
local t_new = {table.unpack(t)}
for i=1,n do
table.insert(t_new, table.remove(t_new, 1))
end
return t_new
end
t_print( t_rotate(t, 2) )
in general, using the table library is more efficient than doing the same things in lua code. (the lib is implemented in c and avoids extra allocations, rehashings &c)