Using the argument '...' efficiently

103,470pages on
this wiki

With patch 2.0 and the upgrade to lua 5.1, the '...' arg is much more powerful and less memory intensive than it was previously. here's some handy tips on how to use this new functionality

Hooking Edit

Previously, the ... arg would create a table 'args' if called. This allocated a table into memory, and thus became a source of garbage churn. A very common pitfall of this came from hooking:

local f = somefunc
somefunc = function(...)
  -- do some crap
  return f(unpack(args))

Now if this function is called often, or there are many hooks like this, there will be a significant hit on performance. With lua 5.1 we can do this hook with no memory wasted

local f = somefunc
somefunc = function(...)
  -- do some crap
  return f(...)

Post-hooks Edit

The new functionality also allows for a nice clean post hook to be made. In this example we need the first arg passed to the function, and we wish to maintain a full proper hook. That means every arg is passed to the hooked function, and every return from that is returned back from our function.

local f = somefunc
local ph = function(a1, ...)
  -- do something with a1
  return ...
somefunc = function(a1, ...)
  return ph(a1, f(a1, ...)

Iterations Edit

As with hooking, iteration over arbitrary number of args would create a table and thus waste memory. With lua 5.1 we can do this cleanly in a for loop

function f(...)
  for i=1,select("#", ...) do
    local x = select(i, ...)
    -- do something with x

Recursion Edit

Clean recursive functions are simple with ...

function r(x, ...)
  local y = x*x
  if select("#", ...) > 0 then
    return y, r(...)
    return y

Around Wikia's network

Random Wiki