WoW:Using the argument '...' efficiently

From AddOn Studio
Revision as of 00:06, 30 December 2006 by WoWWiki>Tekkub
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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

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))
end

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(...)
end

Post-hooks

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 ...
end
somefunc = function(a1, ...)
  return ph(a1, f(a1, ...)
end

Iterations

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
  end
end

Recursion

Clean recursive functions are simple with ...

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