Function 组合两个变量函数结果

Function 组合两个变量函数结果,function,lua,variadic-functions,variadic,Function,Lua,Variadic Functions,Variadic,假设我有两个这样的变量函数: function a(num) if num == 1 then return 1 else return 1, 2 end end function b(num) if num == 1 then return 1 else return 1, 2 end end function c(num) return a(num), b(num) end 然后我想构建另一个函数,该函数调用a和b,并

假设我有两个这样的变量函数:

function a(num)
  if num == 1 then
    return 1
  else
    return 1, 2
  end
end    

function b(num)
  if num == 1 then
    return 1
  else
    return 1, 2
  end
end
function c(num)
  return a(num), b(num)
end
然后我想构建另一个函数,该函数调用
a
b
,并返回
a
的所有结果,然后返回
b
的所有结果。我想写这样的东西:

function a(num)
  if num == 1 then
    return 1
  else
    return 1, 2
  end
end    

function b(num)
  if num == 1 then
    return 1
  else
    return 1, 2
  end
end
function c(num)
  return a(num), b(num)
end

但是它只返回
a
的第一个结果,然后是
b
的所有结果。如何执行此操作?

您只能返回表达式列表中最后一个函数的所有结果;其他结果将被截断为一个结果

因此,

function f1()
    return 1
end

function f2()
    return 2, 3
end

print(f1(), f2())
按预期打印
1 2 3
,但是

print(f2(), f1())
打印
2 1
,因为
f2()
被截断为一个结果

作为一种解决方法,如果您提前知道结果的数量,您可以这样做

local a, b = f1()
local c, d = f2()
return a, b, c, d
local t1 = {f1()}
local t2 = {f2()}
-- Append t2 to t1
return unpack(t1)
或者对于任意数量的结果,您可以

local a, b = f1()
local c, d = f2()
return a, b, c, d
local t1 = {f1()}
local t2 = {f2()}
-- Append t2 to t1
return unpack(t1)

将列表扩展到列表上下文时,要么只使用第一个项目,要么如果扩展发生在列表上下文的末尾,则使用所有项目。(很抱歉,这是Perl语言的术语。)

您可以捕获表构造函数
{a(num)}
中的所有列表项。由于列表作为列表上下文中的最后一项展开,因此将使用所有项

反过来说,您可以使用
unpack
功能将表缩减为列表。但是,它使用了表“长度”概念,该概念仅适用于连续序列数组。由于函数结果可能在任何地方包含
nil
,因此必须通过计数来测量表中的项数,并使用
pairs
函数迭代表

local function a(num)
  if num == 1 then
    return 1
  else
    return nil, 2
  end
end    

local function b(num)
  if num == 1 then
    return 1
  else
    return nil, 2
  end
end