lua-users home
lua-l archive

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


Is there really a need for syntactic sugar here though? There already is 'assert' to simplify your if-condition (erroring instead of printing though):

assert(next(named_args), "no arguments, did you forget something?")
for k, v in pairs(named_args) do print(k, v) end

already seems pretty concise to me. If you want it even shorter (or if you want different side effects), what about using functions to define your own iterator that has a special side effect if the list is empty:

local function arguments(args)
	if next(args) == nil then print"no arguments, did you forget something?" end
	return next, args
end
-- You can then use this as follows:
for k, v in arguments(named_args) do -- this will magically print the error message if the argument table is empty
	print(k, v)
end

You can even generalize this as follows:

local function pairs_else(table, else_clause(...))
	if next(table) == nil then else_clause(...) end
	return next, table
end
for k, v in pairs_else(named_args, print, "no arguments, did you forget something?") do
	print(k, v)
end

In conclusion: There are many options to deduplicate this code. Syntactic sugar doesn't seem necessary at all. Also consider some wrapper function that does the emptiness check of the arguments for you.

On 16.03.22 15:49, Benoit Germain wrote:
Usually it has to do with named arguments processing and catching user errors, like so:

local function foo(...)
   local named_args = ...
   if not next(named_args) then
        print "no arguments, did you forget something?"
     else
         for k,v in pairs(named_args) do
            print(k,v)
        end
     end
end

foo{ oeu='bob', bycoej='cfy'}
foo{}

this would be much cleaner like so:

local function bar(...)
     for k,v in pairs(...) do
        print(k,v)
    else
        print "no arguments, did you forget something?"
    end
end




Le mer. 16 mars 2022 à 15:01, Flyer31 Test <flyer31@googlemail.com> a écrit :
Interesting. Can you say a bit more of the typical possible
applications, just for me as "also Lua newbee" to judge, whether this
REALLY happens often or not?

(I until now never was in such a situation... Usually if I do for
loop, I am always quite sure that something in my container... and if
nothing inside, then I would just be happy that "nothing happens" - so
this standard working principle of Lua has been perfectly nice for me
here ... so far...).

On Wed, Mar 16, 2022 at 9:36 AM Benoit Germain <bnt.germain@gmail.com> wrote:


--
Benoit.