无需在 LUA 中创建变量即可从函数中获取多个值 [英] Getting multiple values from a function without creating a variables in LUA
问题描述
有没有办法从一个函数中获取多个值而不为它创建变量?
Is there any way to get several values from a function without creating variables for it?
local major, minor, revision, codename = love.getVersion() -- Get current LÖVE version as a string.
因此,我们将使用一些只会返回您需要的值的东西,而不是创建四个不同的变量(或数组).
So instead of making four different variables (or array) we'll use something that will just return a value you need.
get( love.getVersion(), 0 ) -- Will return the first value (major).
我在某处读到我可以使用方括号并尝试了love.getVersion()[1]
,但它说尝试索引一个数值."
I read somewhere that I can use square brackets and triedlove.getVersion()[1]
but it says "Attempt to index a number value."
推荐答案
为了举例,我们假设 love.getVersion()
定义如下:
For the sake of example let's assume that love.getVersion()
is defined as follows:
function love.getVersion ()
return 1, 2, 3, "four"
end
使用select(index, ...)
:
如果index
是数字,则select
返回index
的参数索引之后的所有参数.考虑:
Using select(index, ...)
:
If index
is number then select
returns all arguments after argument index of index
. Consider:
print("A:", select(3, love.getVersion()))
local revision = select(3, love.getVersion())
print("B:", revision)
输出:
A: 3 four
B: 3
如有疑问 - 参考手册 - select
.
In case of doubts - Reference Manual - select
.
您提到尝试 love.getVersion()[0]
.这就是差不多,但您首先需要将返回的值包装到一个实际的表中:
You have mentioned trying love.getVersion()[0]
. That's almost it, but you first need to wrap the values returned into an actual table:
local all_of_them = {love.getVersion()}
print("C:", all_of_them[4])
输出:
C: four
如果您想在一行中完成(本着不创建变量"的精神),您还需要将表格括在括号中:
In case you want to do it in one line (in the spirit of "without creating a variables") you need to wrap the table in parentheses, too:
print("D:", ({love.getVersion()})[1])
输出:
D: 1
使用 _
变量:
来自其他语言,您可以使用 _
分配您不感兴趣的值(如果它是一条短平线,没有人会注意到我们创建了一个变量),如:
Using the _
variable:
Coming from the other languages you can just assign values you are not interested in with _
(nobody will notice we create a variable if it is a short flat line), as in:
local _, minor = love.getVersion()
print("E:", minor)
输出:
E: 2
请注意,我在示例中跳过了以下任何_
(不需要local _, minor, _, _
).
Please note that I skipped any following _
in the example (no need for local _, minor, _, _
).
这篇关于无需在 LUA 中创建变量即可从函数中获取多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!