lua-users home
lua-l archive

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


On 14 December 2012 12:30, Dirk Laurie <dirk.laurie@gmail.com> wrote:
local function merge(...)
   local s, arg = {}, {...}
   local n = select('#',...)
   for j=1,n do if type(arg[j])=='table' then
      for k,v in pairs(arg[j]) do s[k]=v end
   end end
   return s
end

The functionality can also be split into two usecases:

1) we have a table and want to add/override fields from another table - borrowing from jQuery, let's call it extend
2) merge all fields into a new table - easily implemented using the first

function extend(t, ...)
   local arg = {...}
   local n = select('#',...)
   for j=1,n do if type(arg[j])=='table' then
      for k,v in pairs(arg[j]) do t[k]=v end
   end end
   return t
end

function merge(...)
return extend({}, ...)
end

extend() can now be used for things such as default values when constructing objects or merging configuration that is split into several files.

Since the functions are so short, maybe they deserve the inclusion into Microlight? Or has the "top 30" limit been already reached? :)