【问题标题】:Unpack several lua fields from a table by name按名称从表中解压缩几个 lua 字段
【发布时间】:2020-10-12 19:03:00
【问题描述】:

我可以按名称从 lua 中的表中解压缩几个命名字段吗?我知道我可以使用table.unpack 将表中的编号字段解压缩到单独的变量中,并且我也可以只从表中提取一个命名字段。

local a, b = table.unpack({1,2,3})
print(a, b) -- will print "1    2"
local t = {some=1, stuff=2}
local field = t.some
print(field) -- will print "1"

但我想知道php中是否有与以下内容等效的内容

$x = ["a"=>1, "b"=>2, "c"=>3];
list("a"=>$a, "c"=>$c) = $x;
echo "$a $c";  // will print "1 3"

我的用例是require,它返回一个包含许多命名字段的表,我 我只对一些感兴趣。所以目前我在做

local a = require("file/where/I/just/need/one/field").the_field
local tmp = require("file/that/returns/table/with/many/fields")
local b, c = tmp.x, tmp.y

但我想知道我是否可以在一行中完成第二个。

【问题讨论】:

    标签: lua lua-table unpack


    【解决方案1】:

    如果你要经常做那件事,你可以定义一个函数:

    local function destruct (tbl, ...)
        local insert = table.insert
        local values = {}
        for _, name in ipairs {...} do
            insert (values, tbl[name])
        end
        return unpack(values)
    end
    
    -- Test:
    local a, b = destruct ({a = 'A', b = 'B', c = 'C'}, 'a', 'b')
    print ('a = ' .. tostring (a) .. ', b = ' .. tostring (b))
    

    因此,在您的示例中,它将是:local b, c = destruct (require 'file/that/returns/table/with/many/fields', 'x', 'y')

    但你不应该。

    【讨论】:

    • 你是对的,不应该那样做。可以说它比两行版本的可读性差,而且必须先定义一个自定义函数,因此它不适合小型脚本或小型项目。我希望找到一个“本机”解决方案或“没有本机解决方案”(根据我的经验,这在 lua 中很常见:)。无论如何,谢谢。
    【解决方案2】:

    如果您更改表格的结构以解压缩为带有表格的表格,那么您可以更好地控制它。看看这个...

    > test={{},{},{}}
    > test[1]={one=1,two=2,three=3}
    > test[2]={eins=1,zwei=2,drei=3}
    > test[3]={uno=1,dos=2,tres=3}
    > check=table.unpack(test,1)
    > check.one
    1
    > check.two
    2
    > check.three
    3
    > check=table.unpack(test,2)
    > check.eins
    1
    > check.zwei
    2
    > check.drei
    3
    > check=table.unpack(test,3)
    > check.uno
    1
    > check.dos
    2
    > check.tres
    3
    

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2021-02-14
      • 2014-01-22
      • 1970-01-01
      相关资源
      最近更新 更多