1
votes

Can I unpack several named fields from a table in lua by name? I know that I can use table.unpack to unpack the numbered fields from a table into separate variables and I also can extract just one named field from the table.

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"

But I want to know if there is an equivalent to the following snipped in php

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

My use case is a require which returns a table with many named fields and I am only interested in some. So currently I am doing

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

But I was wondering if I could do that second one on one line.

2

2 Answers

1
votes

If you are going to do that thing often, you could define a function:

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

So, in your example, it will be: local b, c = destruct (require 'file/that/returns/table/with/many/fields', 'x', 'y').

But you shouldn't.

0
votes

If you change the structure of the table to unpack to a table with tables then you have more control over it. Check this out...

> 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