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 6 years ago

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

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

OR

print("hello", " my dude")

however, that's not my main question. vvvvv

code = {5455, 45, 23, 65, 89, 21, 45}

print("this code ; " .. unpack(code))

this only prints the first number of the table, 5455

WHILE

code = {5455, 45, 23, 65, 89, 21, 45}

print("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
6 years ago

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

(The end of) an assignment:

local t = {1, 2}

local a, b = unpack(t)
-- same as a, b = 1, 2

(The last part of ) function calls:

local t = {1, 2}

print(unpack(t))
-- same as print(1, 2)

and (the last element in) table literals:

local t = {1, 2}

local u = {3, unpack(t)}
-- 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:

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

Parenthesis also take only the first value in a tuple:

local t = {1, 2}

print( (unpack(t)) )
-- 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 — 6y
Ad

Answer this question