3

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.

3
  • Are you talking about Lua or other similar language? local name, age = person will just assign person to name in Lua. Commented Nov 19, 2024 at 12:19
  • @shingo I know, and I am asking about what that line should be to achieve reliable name-based destructuring Commented Nov 19, 2024 at 12:28
  • 3
    local name, age = person.name, person.age Commented Nov 19, 2024 at 12:29

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments