[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.2 - small enhancement for table.unpack
- From: Dirk Laurie <dpl@...>
- Date: Wed, 29 Jun 2011 12:09:31 +0200
On Wed, Jun 29, 2011 at 11:27:24AM +0200, Matthew Wild wrote:
> On 29 June 2011 10:26, steve donovan <steve.j.donovan@gmail.com> wrote:
> > On Wed, Jun 29, 2011 at 11:20 AM, Patrick Rapin <toupie300@gmail.com> wrote:
> >> The function table.pack could also set a metatable with then __len
> >> metamethod returning the true length, since table.unpack already obey
> >> __len metamethod.
> >
> > That is a most elegant solution, I think.
> >
>
> Until someone tries to modify the returned table and then wonders why
> the length doesn't change accordingly? :)
>
That person could have done this:
t = table.pack(1,2,nil,4)
t.n = #t
getmetatable(t).__len = rawlen
thus obtaining the current solution.
I agree with Steve: Patrick's solution is elegant. It exploits
a feature of Lua 5.2, whereas the current solution is reminiscent
of older versions.
> getn (table)
> Returns the ``size'' of a table, when seen as a list. If the table has
> an n field with a numeric value, this value is the ``size'' of the table.
— Lua 4.0 reference manual
Dirk