If I have a table with known properties, but where the order of the properties is potentially unknown:
local person = {
name = 'James',
age = 30,
}
can I reliably destructure it:
local name, age = unpack(person)
My worry is that if the order of the fields in the table is changed, that destructuring assignment will no longer work as expected.
If I have a table with known properties, but where the order of the properties is potentially unknown:
local person = {
name = 'James',
age = 30,
}
can I reliably destructure it:
local name, age = unpack(person)
My worry is that if the order of the fields in the table is changed, that destructuring assignment will no longer work as expected.
Share Improve this question edited Nov 19, 2024 at 12:27 asked Nov 19, 2024 at 12:01 user3310334user3310334 3 |3 Answers
Reset to default 1No, there's no way to associate table fields (which are just string keys in a hash table) with local variables of the same name. You just have to be explicit and think of variables and table keys as two separate things.
It won't work as such, since table.unpack works with numbered indices. In other words,
local name, age = unpack(person)
is mostly equivalent to:
local name, age = person[1], person[2]
There is no built-in unpacking function for named keys. So you just have to write it explicitly as:
local name, age = person.name, person.age
Note that there is no correspondance between number and string keys at all. When you write:
local t = { x = true }
You cannot refer to t.x
or t['x']
with t[1]
. They are in completely separate table slots.
Here is a cute trick. It does not set local variables but allows us to use table field as global variables:
local person = {
name = 'James',
age = 30,
}
do
local print = print
_ENV = person
print(name,age)
end
local name, age = person
will just assignperson
toname
in Lua. – shingo Commented Nov 19, 2024 at 12:19local name, age = person.name, person.age
– shingo Commented Nov 19, 2024 at 12:29