VukNovakovic
VukNovakovic

Reputation: 83

Unpack lua table as object and map them as function arguments

I'm looking for a way to unpack lua table(object, not an array) and map return value as arguments to a function. Example:

local function f(a, b, c, d)
    print(a, b, c, d)
end

--order is messed up on purpose
local object_to_unpack = {
    a = 1,
    c = 42,
    d = 18,
    b = 102
}

So Im looking for a way to do something like f(unpack_and_map(object_to_unpack)) and for function to output 1, 102, 42, 18. I know about unpack function, but it only works on arrays, not objects, and I don't have any ordering guarantees(as demonstrated in object_to_unpack)

Upvotes: 1

Views: 1948

Answers (1)

Piglet
Piglet

Reputation: 28950

Not sure why you want to unpack that table and not just use it as the functions parameter.

local someTable = {
  a = 1,
  c = 42,
  d = 18,
  b = 102,
}

local function f(t)
  print(t.a, t.b, t.c, t.d)
end

f(someTable)

If you insist on calling f with a list of expressions you need to create one.

function f(...)
  print(...)
end

local args = {}
for _, v in pairs(someTable) do
  table.insert(args, v)
end

f(table.unpack(args))

This does not guarantee any order. If you want the list ordered by the keys you need to sort that list prior to calling f.

local keys = {}
for k in pairs(someTable) do
  table.insert(keys, k)
end
table.sort(keys)
local args = {}
for _, key in ipairs(keys) do
  table.insert(args, someTable[key])
end

f(table.unpack(args))

Upvotes: 1

Related Questions