2

In writing some one-off Lua code for an answer, I found myself code golfing to fit a function on a single line. While this code did not fit on one line...

foo=function(a,b) local c=bob; some_code_using_c; return c; end

...I realized that I could just make it fit by converting it to:

foo=function(a,b,c) c=bob; some_code_using_c; return c; end

Are there any performance or functional implications of using a function parameter to declare a function-local variable (assuming I know that a third argument will never be passed to the function) instead of using local? Do the two techniques ever behave differently?


Note: I included semicolons in the above for clarity of concept and to aid those who do not know Lua's handling of whitespace. I am aware that they are not necessary; if you follow the link above you will see that the actual code does not use them.


Edit Based on @Oka's answer, I compared the bytecode generated by these two functions, in separate files:

function foo(a,b)
   local c
   return function() c=a+b+c end
end
function foo(a,b,c)
   -- this line intentionally blank
   return function() c=a+b+c end
end

Ignoring addresses, the byte code report is identical (except for the number of parameters listed for the function).

Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745

1 Answers1

2

You can go ahead and look at the Lua bytecode generated by using luac -l -l -p my_file.lua, comparing instruction sets and register layouts.

On my machine:

function foo (a, b)
    local c = a * b
    return c + 2
end

function bar (a, b, c)
    c = a * b
    return c + 2
end

Produces:

function <f.lua:1,4> (4 instructions at 0x80048fe0)
2 params, 4 slots, 0 upvalues, 3 locals, 1 constant, 0 functions
        1       [2]     MUL             2 0 1
        2       [3]     ADD             3 2 -1  ; - 2
        3       [3]     RETURN          3 2
        4       [4]     RETURN          0 1
constants (1) for 0x80048fe0:
        1       2
locals (3) for 0x80048fe0:
        0       a       1       5
        1       b       1       5
        2       c       2       5
upvalues (0) for 0x80048fe0:

function <f.lua:6,9> (4 instructions at 0x800492b8)
3 params, 4 slots, 0 upvalues, 3 locals, 1 constant, 0 functions
        1       [7]     MUL             2 0 1
        2       [8]     ADD             3 2 -1  ; - 2
        3       [8]     RETURN          3 2
        4       [9]     RETURN          0 1
constants (1) for 0x800492b8:
        1       2
locals (3) for 0x800492b8:
        0       a       1       5
        1       b       1       5
        2       c       1       5
upvalues (0) for 0x800492b8:

Not very much difference, is there? If I'm not mistaken, there's just a slightly different declaration location specified for each c, and the difference in the params size, as one might expect.

Oka
  • 23,367
  • 6
  • 42
  • 53