Search code examples
lua

Why are some values disappearing?


I need to use a function that executes another function but adding an extra argument at the end, so I wrote this:

function ExecuteWithMyNameAtTheEnd(f, ...)
    f(..., "Maxi")
end

ExecuteWithMyNameAtTheEnd(print, 1, 2, 3)

But for some reason instead of printing 1 2 3 Maxi it prints 1 Maxi and I don't know why. I thought the ... contained the values 1 2 3 because when I use print(...) it says 1 2 3. I am using Lua 5.4 if that helps.

Let me know if I did something wrong when asking this question because it's my first time using Stack Overflow and I am not a native English speaker.


Solution

  • Multiple values get truncated when there's a comma after them. Something like this will work as a workaround:

    function ExecuteWithMyNameAtTheEnd(f, ...)
        local arg = table.pack(...)
        arg[arg.n + 1] = "Maxi"
        f(table.unpack(arg, 1, arg.n + 1))
    end
    
    ExecuteWithMyNameAtTheEnd(print, 1, 2, 3)