user3310334
user3310334

Reputation:

Unpack table into same-named variables

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.

Upvotes: 2

Views: 90

Answers (3)

lhf
lhf

Reputation: 72392

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

Upvotes: 0

QuentinC
QuentinC

Reputation: 14772

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.

Upvotes: 0

luther
luther

Reputation: 5564

No, 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.

Upvotes: 1

Related Questions