lua-users home
lua-l archive

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


I like both.
I made an utility function ("assign") for that and for giving a value to a variable in a call to function (without leaning on order) It is not syntactic sugar because the construction is longer but is more powerful
must be called with an array as argument when you want defaults
Hope anyone likes!!
Best
victor bombi
--------------
--allow defaults as in:
--function fun4d(defval)
-- local an,en,inp = assign({"an","en","inp"},{1,2,3},defval)
-- print("fun4d",an,en,inp)
--end
--fun4d{en=67,5}

local function assign(defs,defv,...)
local defval
if select('#', ...)==1 and type(select(1, ...))=="table" and getmetatable(select(1, ...)) == nil then
 defval = select(1, ...)
else
 defval = {...}
end
local def ={}
--assign default
for k,v in ipairs(defs) do
 def[v]=defv[k]
end
--assign integer indexed
for k,v in pairs(defval) do
 --print("def2a ",k,v)
 if type(k)=="number" and math.floor(k)==k then
  if defs[k] then
   def[defs[k]]=v
  else
   error("bad arg index:"..k)
  end
 else
  def[k]=v
 end
end
local ret = {}
for i,v in ipairs(defs) do
 ret[i] = def[defs[i]]
end
return unpack(ret)
end
----- Original Message ----- From: "Dirk Laurie" <dirk.laurie@gmail.com>
To: "Lua mailing list" <lua-l@lists.lua.org>
Sent: Sunday, April 21, 2013 8:41 AM
Subject: Syntax sugar for default arguments


   function f(x,y=0)
   function f(x,y or 0)

to mean

   function f(x,y) y=y or 0

Neither would break existing code.

Which of the above should I choose to implement as a patch?