Pack: Difference between revisions
Jump to navigation
Jump to search
imported>Felice Enellen (→ See also: formatting) |
imported>Felice Enellen (mention .n and flesh out the examples to demonstrate its use) |
||
| Line 4: | Line 4: | ||
|...||parameters||| | |...||parameters||| | ||
}} | }} | ||
Returns a new table with all parameters stored into keys 1, 2, etc | Returns a new table with all parameters stored sequentially into keys [1], [2], etc. | ||
Examples | The table will also contain a member <var>.n</var> which specifies how many arguments were passed to <code>pack()</code>, including <var>nil</var> arguments. This can be used to detect the difference between an argument that was not passed at all and a <var>nil</var> value that was deliberately passed, since the <code>#</code> operator stops when it reaches a <var>nil</var> value. | ||
== Examples == | |||
<syntaxhighlight lang="lua"> | <syntaxhighlight lang="lua"> | ||
table = pack(x, y, dx, dy) -- returns {x, y, dx, dy} | |||
print(#table) -- prints "4" | |||
print(table.n) -- prints "4" | |||
table = pack(x, y) -- returns {x, y} | |||
print(#table) -- prints "2" | |||
print(table.n) -- prints "2" | |||
table = pack(x, y, nil, nil) -- returns {x, y} | |||
print(#table) -- prints "2" | |||
print(table.n) -- prints "4" | |||
</syntaxhighlight> | </syntaxhighlight> | ||
== See also == | == See also == | ||
* [[Unpack|<code>unpack()</code>]] | * [[Unpack|<code>unpack()</code>]] | ||
Revision as of 16:21, 29 September 2020
pack( ... )
- Creates a table from the given parameters.
- ...
-
- parameters
Returns a new table with all parameters stored sequentially into keys [1], [2], etc.
The table will also contain a member .n which specifies how many arguments were passed to pack(), including nil arguments. This can be used to detect the difference between an argument that was not passed at all and a nil value that was deliberately passed, since the # operator stops when it reaches a nil value.
Examples
table = pack(x, y, dx, dy) -- returns {x, y, dx, dy}
print(#table) -- prints "4"
print(table.n) -- prints "4"
table = pack(x, y) -- returns {x, y}
print(#table) -- prints "2"
print(table.n) -- prints "2"
table = pack(x, y, nil, nil) -- returns {x, y}
print(#table) -- prints "2"
print(table.n) -- prints "4"