This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
loustak's profile picture

Variable number of argument to a function with ...

Started by loustak, 23 July 2016 - 07:53 AM
loustak #1
Posted 23 July 2016 - 09:53 AM
Hello,
I got this :

function type.Pos:load(data)
   print(data.x) -- Print the value correctly
   self:set(data)
end
who call this :

function type.Pos:set(...)
   local arg = {...}
   print(arg.x) -- print nothing
end

I don't understand why arg.x is nil.

Thanks for the help !
Emma #2
Posted 23 July 2016 - 05:50 PM
… is a strange operator that acts as a list of unpacked items, when you do {…} you pack all of the items into an array. In your first example data seems to be a table, and in your second example you try to access the previous data variable without accessing it first. Try this

local data = {...}
local X = data[1].x -- the [1] accesses the first argument
The Crazy Phoenix #3
Posted 23 July 2016 - 11:03 PM
I'd like to add that Lua will automatically assign the variable "arg" to functions which use the … operator. This means that you can remove the line where you redeclare and reassign arg.
loustak #4
Posted 24 July 2016 - 12:20 AM
Thanks for the replies.
Why I don't use arg is because it seems to be deprected since lua 5.1 (source)
… is a strange operator that acts as a list of unpacked items, when you do {…} you pack all of the items into an array. In your first example data seems to be a table, and in your second example you try to access the previous data variable without accessing it first. Try this

local data = {...}
local X = data[1].x -- the [1] accesses the first argument
Thanks it worked !