Pack function
To complement the “unpack” function, this section proposes to backport the “pack” function from Lua 5.2. This can be added either as the global function pack
, or the library function table.pack
(if the latter, it would be good to include table.unpack
as an alias to unpack
).
Definition of the pack function according to the Lua 5.2 manual:
table.pack (···)
Returns a new table with all parameters stored into keys 1, 2, etc. and with a field “n” with the total number of parameters. Note that the resulting table may not be a sequence.
Note that pack can be trivially implemented as the following:
function pack(...)
return {n = select("#", ...), ...}
end
This change may have backwards incompatibilities with:
- scripts that assume the
pack
global variable is nil
Agreement with this proposal
- Agree
- Neutral
- Disagree
0 voters
Support field n
in unpack
The “unpack” function has optional arguments i
and j
to specify the range of arguments to unpack. i
is the lower bound, and j
is the upper bound. When j
is unspecified, it defaults to the length of the table as defined by the #
operator.
local args = {1, 2, 3, nil, nil}
print(unpack(args, 2, 5)) --> 2, 3, nil, nil
print(unpack(args, 2)) --> 2, 3
print(unpack(args)) --> 1, 2, 3
This section proposes to change the behavior of unpack to include looking for field n
in the table when determining the upper bound. This is to complement the pack
function, which sets field n
to indicate the number of packed arguments.
To get the upper bound:
- If argument
j
is specified, then use it as the upper bound. - Otherwise, if field
n
of the table is a number, then use it as the upper bound. - Otherwise, use the length of the table as defined by the
#
operator.
This change may have backwards incompatibilities with:
- scripts that call unpack on a table with field
n
, which expect the length of the table for the number of arguments. e.g.t = {1, 2, 3, n = 5} print(unpack(t)) -- expect: 1, 2, 3 -- result: 1, 2, 3, nil, nil
Note that this change is not present in later versions of Lua, though a similar proposal has been made.
Agreement with this proposal
- Agree
- Neutral
- Disagree
0 voters