Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
5

Can someone explain how the tuple argument works? (...)

Asked by
Psudar 882 Moderation Voter
5 years ago
Edited 5 years ago

I was making a script to get the largest value out of an unknown number of arguments, but I can't really figure out how to use (...) tuple.

Can someone explain how it works, please? The only thing I know is that it's not a true tuple, since lua actually treats them as individual values and not a data structure like a table or such.

Thanks!

local function Val(...)
    print(...)
end

Val(1, 2, 3, 4, 5, 6)

1, 2, 3, 4, 5, 6

The code isn't really that important to the question, Its just what I first was messing around with.

0
local function max(...) return math.max(...); end Zafirua 1348 — 5y

1 answer

Log in to vote
2
Answered by
thebayou 441 Moderation Voter
5 years ago
Edited 5 years ago

Alright. Lua can be pretty confusing, especially in the more sketchy nooks and crannies that you don't really mess with until you somehow do. This is one example.

The ... argument is actually pretty straightforward. It does what you think it does - makes it possible for the function to take in any number of arguments. However, accessing those arguments is less-known but painfully simple. Here's what you do:

local function Val(...)
    local arguments = {...} -- This line is key!
    -- Do whatever with the arguments
end

Surrounding ... with braces converts it to a table of arguments. The first argument would be at position [1], the second at [2], etc. etc.

That's it!

(Don't ask me why its type is a number. I don't know either.)

0
Hey thanks! I actually was looking for a way to get them into a table. I'll be sure to accept this as a solution if nobody responds with a more detailed one in the next 30 or so mins. :D Psudar 882 — 5y
2
You should also include that you can take advantage of multi-variable assignment. This "list" of values can be thought of as simply multiple results of a function, and as such, you can do: a, b, c = ... ScriptGuider 5640 — 5y
1
@ScriptGuider good idea, but you might not know how many arguments you'll actually receive. That's what makes the table helpful thebayou 441 — 5y
2
Its type is not a number. The reason why it shows its type is a number is because the first argument passed in the tuple is a number. If I passed any other datatype, it will say the type of the tuple corresponding to the first element in the tuple. Zafirua 1348 — 5y
View all comments (2 more)
0
@ScriptGuider saving the day once again Psudar 882 — 5y
0
@Zafirua I figured as much, but if you pass in arguments of many different types the type will still be the type of the first argument, which makes no sense. What exactly is ... then? thebayou 441 — 5y
Ad

Answer this question