So I found that .. and , can work for concatenating for example,
1 | print ( "hello" .. " my dude" ) |
OR
1 | print ( "hello" , " my dude" ) |
however, that's not my main question. vvvvv
1 | code = { 5455 , 45 , 23 , 65 , 89 , 21 , 45 } |
2 |
3 | print ( "this code ; " .. unpack (code)) |
this only prints the first number of the table, 5455
WHILE
1 | code = { 5455 , 45 , 23 , 65 , 89 , 21 , 45 } |
2 |
3 | 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.
unpack
turns a table into a tuple. Tuples can be used in three places in Lua:
(The end of) an assignment:
1 | local t = { 1 , 2 } |
2 |
3 | local a, b = unpack (t) |
4 | -- same as a, b = 1, 2 |
(The last part of ) function calls:
1 | local t = { 1 , 2 } |
2 |
3 | print ( unpack (t)) |
4 | -- same as print(1, 2) |
and (the last element in) table literals:
1 | local t = { 1 , 2 } |
2 |
3 | local 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:
1 | local t = { 1 , 2 } |
2 | local a = 3 * unpack (t) |
3 | -- same as a = 3 * 1 |
Parenthesis also take only the first value in a tuple:
1 | local t = { 1 , 2 } |
2 |
3 | print ( ( 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).