lua-users home
lua-l archive

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


On 04/07/2015 08:07 AM, Roberto Ierusalimschy wrote:
Yes. The point is that, when a closure has no external variables, the
difference between the closure and the "function" (or "prototype", as
it is called in the source code) is very thin. (In fact, in the current
implementation, there is a 1-1 correspondence between closures and
functions when there are no external variables.)

This reminds me of a coding-style question that comes up often for me. It amounts to, which is the "better" way to get data into a function, accessing an upvalue or passing in a parameter, especially when the use of the function is localized such as a function defined within another. My definition of "better" is typically run-time efficiency when the function is called many times, but I'd be interested in opinions of style as well. I sometimes superstitiously think that there may be some "advantage" in creating a function that has no external references rather than one which requires separate closures, but I honestly have no idea if this is true.

I suppose there are two cases, depending on how often the parameter data is changed, i.e. is the upvalue's value set prior to each function-call or does its value remain the same across many calls. An example of the latter case:

-- Given:
local foo = {};

-- Is this faster:
local function bar1( x )
    foo[#foo+1] = x;
end
for i = 1, 1000000 do
    bar1( "boo" );
end

-- Or this?
local function bar2( tbl, x )
    tbl[#tbl+1] = x;
end
for i = 1, 1000000 do
    bar2( foo, "boo" );
end