按名称从表中解压几个lua字段



我可以按名称从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

但我想知道我是否可以在一条线上做第二个。

如果你经常这样做,你可以定义一个函数:

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')

但你不应该。

如果您将表的结构更改为解压为包含表的表,则您可以对其进行更多控制。。。

> 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

最新更新