lua-users home
lua-l archive

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

On Thu, Feb 19, 2009 at 03:32:16PM +1100, Vaughan McAlley wrote:
> 2009/2/19 Etan Reisner <>:
> > Personally I tend to avoid using table.insert in favor of
> >    tab[#tab + 1] = item
> > or keeping an explicit counter, but that probably doesn't matter much
> > except in tight loops.
> >
> It took me a while to work out why this is popular (apart from
> featuring heavily in Programming in Lua). It's because this method
> allows access to metamethods, while table.insert doesn't. Am I right?
> -Vaughan

Using table.insert requires a global lookup for table, a table lookup for
insert, and a call on the resulting function each time. Using #tab or
keeping an explicit counter avoids these costs. You can avoid the two
lookups by using a local 'local tinsert = table.insert' outside the loop
but that still leaves the call.

I also personally just find it wordier than the alternatives.

But now that you mention it, yes the metatable point is a good one. I'd
never thought about that before. Using table.insert seems to bypass
metamethods while the other two methods do not. And I would much sooner
suggest someone use a local tinsert than a local rawset to avoid the
metmethod lookup for this.