Search code examples
luafunctional-programmingargument-unpacking

Lua flexible function argument unpacking in local function


I am working on command handler that needs to work in two environments. Below is a a small part of the function I am working on, which I think captures the problem. At least, I get the error message I need to adress.

In the live environment, a Fibaro Home center 2, command sets given in the table should be executed one by one using fibaro:call, which takes 2-3 arguments, depending the call.

During development I instead use the print function to just print the commands that should have been issued.

function movementHandler(movementSendorId,onTable)
    local offTable = offTable or {};
    local onTable = onTable or {};
    if (fibaro or {}).call then 
       function callFunc(...) ;
          return fibaro:call(...);
       end;
    else
        function callFunc(...)
            print(unpack(arg));
       end;       
    end;
    if onTable ~= {} then
        for i,command in pairs(onTable) do
            callFunc(unpack(command));
        end;
    end;
end;

However, when I try this in the Lua command shell

> c= {}
> c[1] = {1,"turnOn"}
> c[2] = {1,"setValue",10}
> movementHandler(10,c,c) 

, I get this output:

stdin:10: bad argument #1 to 'unpack' (table expected, got nil)
stack traceback:
    [C]: in function 'unpack'
    stdin:10: in function 'callFunc'
    stdin:15: in function 'movementHandler'
    stdin:1: in main chunk
    [C]: in ?

What I am not understanding about how unpack works?


Solution

  • Automatic creation of the arg table for vararg functions was deprecated in Lua 5.1 and removed in Lua 5.2.

    Use simply

    function callFunc(...)
        print(...)
    end
    

    If you need a table, use

    function callFunc(...)
        local arg={...}
        print(unpack(arg))
    end