Altering values in passed variable number of arguments in functions

If I’ve got a function that takes a variable number of arguments

local function args(...)
end 

Why is it not possible to do

{...}[1] = nil
-- or
({...})[1] = nil

it only removes the error when indexing before that, but it’s comparing somehow which is not what I want

 -- within function
 local obj = ({...})[1] -- indexed first with a literal
 {...}[1] == nil --> silenced error in script editor when trying to compare without an if statement
 print(unpack({...})) --> but errors when I try to print it like 
 -- this at the previous line, attempt to call a number value
 args(1,2)
 
-- error when doing

 local function args (...)
     local obj -- upvalue
     {...}[1] = nil -- and within brackets as well
  end

I could just let a variable reference the arguments and set the first index in that as nil and solve the issue, but why does it error like that with table literals?

-- solution

local function args(...)
     local args = {...}
     args[1] = nil
     print(unpack(args)) 
end

args(1,2) --> nil, 2 (what I want to do without variables)

The question is: why do I need to use a variable to hold reference and index an element in the table before trying to set the first index to equal nil in the arguments passed, and why does it only silence the error in the script editor when I use comparison syntax (==) ???

I don’t have any use case for this, just want to know why I can’t set something individually to nil without using variables in the block.

Some sort of combination of caching and a bug previous?

local function args(...)
	  table.remove({...}, 1) --> remove the first index 
	  print(unpack({...}))
end 

args(1,2,3) --> prints all of them unless I use a variable to hold reference,
-- why?
1 Like

The only place where a literal value can be used is as a value to be assigned to a variable. Think

local a, b, c, d, e = {...}, {1, 2}, "test", 10, nil

That means you can’t e.g. call functions on or index literal values. This is nothing specific to varargs or the ... operator. E.g.:

"swag":len()
{1, 2, 3}[1] = nil

errors because they’re not valid expressions, while

local a = "swag"
a:len()
local t = {1, 2, 3}
t[1] = nil

works fine.

If you want to dig deeper into the “why” rabbithole, check out the precise grammar of the language at

https://www.lua.org/manual/5.1/manual.html#8 and
https://www.lua.org/manual/5.1/manual.html#2.5

1 Like