lua-users home
lua-l archive

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


Norman Ramsey wrote:
I have some code that uses Lua 5.0 and has varargs functions
in which some arguments may be nil.  Here is an example using Lua 5.0:

  local output
    --- function to output zero or more items, where an item is
    ---    * a string
    ---    * nil (ignored)
    ---    * a function returning zero or more items
    ---    * a list of items in a Lua table
  do
    local output_funs = { }
    output_funs['string']   = output_one
    output_funs['nil']      = function() end
    output_funs['table']    = function(t) return output(unpack(t)) end
    output_funs['function'] = function(f) return output(f()) end
    function output(...)
      for i = 1, table.getn(arg) do --- can't use ipairs b/c arg might be nil
        local v = arg[i]
        assert(output_funs[type(v)], "Bad value to output()") (v)
      end
    end
  end

I am struggling to figure out how to implement this function in Lua 5.1.
How am I to make sure that I get all the arguments when the new #
operator is not specified when some arguments are nil?
AFAIK, #... will return the total number of items in the ... object, including nils.
The problems with nil args only apply to tables as arrays.


(untested)
function output(...)
   for i = 1, select('#',...) do
      local v = select(i,...)
      assert(output_funs[type(v)], "Bad value to output()") (v)
   end
end

Adrian