lua - How do I create a function that returns the first non-nil, non-empty string passed to it? -
i'm trying implement function returns first non-blank string variables passed it. unfortunately, of these variables might nil, naive approach
function first_non_empty(...) i, item in ipairs({...}) if item ~= nil , item ~= '' return item end end return '' end
doesn't work: ipairs quits out encounters nil value. can fixed changing requirements variables can't nil, or passing length function table length doesn't have rely on ipairs
, or wrapping parameters in function none of them explicitly nil
function first_non_empty_func(...) i, func in ipairs({...}) local item = func() if item ~= nil , item ~= '' return item end end return '' end function fn(p) local f = function() return p end return f end -- change callers first_non_empty_func(fn(a), fn(b), fn(c))
however, both of these solutions complicate function prototype. there exist function taking ordered list of parameters, of may nil, returns first of parameters both non-nil , not empty string?
select('#', ...)
can used number of provided arguments, here alternative doesn't use table.pack
:
function first_non_empty_pack(...) = 1, select('#', ...) local item = select(i, ...) if item ~= nil , item ~= '' return item end end return '' end
Comments
Post a Comment