从函数获取多个值而无需在LUA中创建变量 [英] Getting multiple values from a function without creating a variables in LUA

查看:60
本文介绍了从函数获取多个值而无需在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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆