使用名称从Lua表中解包多个字段

我能否使用lua按名称从表中解压出多个命名字段?我知道我可以使用“table.unpack”将表中的编号字段解压成单独的变量,也可以提取表中的一个命名字段。

local a, b = table.unpack({1,2,3})
print(a, b) -- 将打印"1     2"
local t = {some=1, stuff=2}
local field = t.some
print(field) -- 将打印“1”

但是,我想知道以下 PHP 中的代码片段是否有相当的语法:

$x = ["a"=>1, "b"=>2, "c"=>3];
list("a"=>$a, "c"=>$c) = $x;
echo "$a $c";  // 将打印“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

但我想知道是否可以在一个线路上执行第二个操作。

点赞
用户6632736
用户6632736

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

local function destruct (tbl, ...)
    local insert = table.insert
    local values = {}
    for _, name in ipairs {...} do
        insert (values, tbl[name])
    end
    return unpack(values)
end

-- 测试:
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')

但是你不应该这样做。

2020-10-12 09:01:15
用户11740758
用户11740758

如果你将表的结构改为拆成包含表的表,则可以更加掌控它。看看这个例子...

> 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
2020-10-12 11:03:00