lua-users home
lua-l archive

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

2009/9/21 Saurabh T <>:
> I'm working with Lua scripts driving C code and trying to write a wrapper
> around functions like so
> function doit()
>   local status, err = pcall(unpack(arg))
>   -- do something with status and err
> end
> and
> doit(x, arg1, arg2, ...)
> Now the problem is arg1, arg2 etc can genuinely be nil, and unpack stops at
> nil. Is there any way I can get unpack to get all the entries in the table,
> whether or not they are nil? Thanks,
> saurabh

As Luiz and Shaun have already pointed out, what you want here is
pcall(...), instead. However, to directly answer your question as well
anyway, there *is* a way to get unpack to get all the entries in a
table, using optional extra parameters of unpack():

   local a = {}
   a[5] = 'x'
   print(unpack(a))   --> (nothing)
   print(unpack(a, 1, table.maxn(a)))     -->   nil, nil, nil, nil, 'x'

...if you can improve on the performance of table.maxn() by knowing
the number of elements in advance, so much the better. For a vararg
list you can use select('#', ...) to get this.