lua-users home
lua-l archive

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


On Sat, Jun 1, 2013 at 1:01 PM, Luis Carvalho <lexcarvalho@gmail.com> wrote:
> A simple solution is to add a parameter that specifies if you want a copy or
> not:
>
> local _myfunc = myfunc
> myfunc = function (x, copy)
>   return _myfunc(copy and copy(x) or x)
> end


what i do sometimes is to add an optional argument for the copy:

myfunc = function (in, dst)
  dst = dst or in
  .... do all work, reading parameters from in, writing to dst
  return dst
end


so, it's used like:

result = myfunc{a,b,c}
-- result is the same table, no allocations

or:

obj = {a,b,c}
myfunc(obj)
-- obj is modified in place

or:

obj = {a,b,c}
result = myfunc(obj, {})
-- result is the new table allocated just before calling
-- obj is not modified


or:

result = myfunc({a,b,c},{d,e})
-- result is a new table, with some 'default' results



--
Javier