返回值个数
Number of returned values
我有一个返回一堆值的函数,但我不知道返回了多少参数。
function ascii( value )
[...]
if type( value ) == "string" then
if #value > 1 then
local temp = {}
for i = 1, #value do
table.insert( temp , (value:byte(i)) )
end
return unpack( temp ) --<-- unknown number of return values
else
return value:byte(1)
end
end
[...]
end
我怎么知道返回了多少个值?
我的第一个想法是:
return numberOfValues, unpack( temp )
但在大多数情况下,值的数量是无关紧要的。
有没有办法避免在 95% 的情况下都不必要的额外努力?
保持你的函数定义不变,并像这样调用它:
local values = {ascii(myString)}
local n = #values
returned 值的数量与根据 returned 值构建的 table 中的元素数量不同。它在您的示例中有效,但这只是因为该示例不包含任何 nil
值。
在 returned 值可能包含 nil
的一般情况下,使用 select('#'...)
几乎总是更好:
print(#{(function() return 1, nil, 2 end)()})
print(select('#', (function() return 1, nil, 2 end)()))
此代码在 Lua 5.1 中打印 1 3
,但在 Lua 5.2 和 Lua 5.3 中打印 3 3
。在 return 值中再添加一个 nil
会将其更改为 1 4
在所有这些版本的 Lua 下。
这些函数可以用作 return 值的数量 return 以及 return 列表或 table 值的包装器:
function wrap(...) return select('#', ...), ... end
function wrapt(...) return select('#', ...), {...} end
使用这些函数之一,print(wrap((function() return 1, nil, 2, nil end)()))
按预期打印 4 1 nil 2 nil
。
我有一个返回一堆值的函数,但我不知道返回了多少参数。
function ascii( value )
[...]
if type( value ) == "string" then
if #value > 1 then
local temp = {}
for i = 1, #value do
table.insert( temp , (value:byte(i)) )
end
return unpack( temp ) --<-- unknown number of return values
else
return value:byte(1)
end
end
[...]
end
我怎么知道返回了多少个值?
我的第一个想法是:
return numberOfValues, unpack( temp )
但在大多数情况下,值的数量是无关紧要的。 有没有办法避免在 95% 的情况下都不必要的额外努力?
保持你的函数定义不变,并像这样调用它:
local values = {ascii(myString)}
local n = #values
returned 值的数量与根据 returned 值构建的 table 中的元素数量不同。它在您的示例中有效,但这只是因为该示例不包含任何 nil
值。
在 returned 值可能包含 nil
的一般情况下,使用 select('#'...)
几乎总是更好:
print(#{(function() return 1, nil, 2 end)()})
print(select('#', (function() return 1, nil, 2 end)()))
此代码在 Lua 5.1 中打印 1 3
,但在 Lua 5.2 和 Lua 5.3 中打印 3 3
。在 return 值中再添加一个 nil
会将其更改为 1 4
在所有这些版本的 Lua 下。
这些函数可以用作 return 值的数量 return 以及 return 列表或 table 值的包装器:
function wrap(...) return select('#', ...), ... end
function wrapt(...) return select('#', ...), {...} end
使用这些函数之一,print(wrap((function() return 1, nil, 2, nil end)()))
按预期打印 4 1 nil 2 nil
。