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

Quick Concatenation Question For Unpacking?

Asked by 7 years ago

So I found that .. and , can work for concatenating for example,

1print("hello" .. " my dude")

OR

1print("hello", " my dude")

however, that's not my main question. vvvvv

1code = {5455, 45, 23, 65, 89, 21, 45}
2 
3print("this code ; " .. unpack(code))

this only prints the first number of the table, 5455

WHILE

1code = {5455, 45, 23, 65, 89, 21, 45}
2 
3print("this code ; ", unpack(code))

this print ALL of the numbers of the table. I don't understand. Can someone explain the logic behind this? I am confused and it will help me understand things better in the future.

1 answer

Log in to vote
8
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago

unpack turns a table into a tuple. Tuples can be used in three places in Lua:

(The end of) an assignment:

1local t = {1, 2}
2 
3local a, b = unpack(t)
4-- same as a, b = 1, 2

(The last part of ) function calls:

1local t = {1, 2}
2 
3print(unpack(t))
4-- same as print(1, 2)

and (the last element in) table literals:

1local t = {1, 2}
2 
3local u = {3, unpack(t)}
4-- same as u = {3, 1, 2}

If you use a tuple anywhere else, such as with an operator like + or .., it will only use the first value in the tuple:

1local t = {1, 2}
2local a = 3 * unpack(t)
3-- same as a = 3 * 1

Parenthesis also take only the first value in a tuple:

1local t = {1, 2}
2 
3print( (unpack(t)) )
4-- same as print(1)

In your case, it's the .. which eliminates the remainder of the tuple after the first one.


print isn't really a way to "concatenate" strings, it's just something it happens to do if you give it multiple things.

You can use table.concat(list, " ") to concatenate the elements of list, separating them by spaces. (Note that this requires the elements of list be properly strings / numbers; unlike print, tostring will not be automatically called for other types of objects).

0
Thank you! laughablehaha 494 — 7y
Ad

Answer this question