最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

lua - Unpack table into same-named variables - Stack Overflow

programmeradmin1浏览0评论

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
  • Are you talking about Lua or other similar language? local name, age = person will just assign person to name in Lua. – shingo 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 – user3310334 Commented Nov 19, 2024 at 12:28
  • 3 local name, age = person.name, person.age – shingo Commented Nov 19, 2024 at 12:29
Add a comment  | 

3 Answers 3

Reset to default 1

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.

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
发布评论

评论列表(0)

  1. 暂无评论