Getting multiple values from a function without creating a variables in LUA

百般思念 提交于 2020-07-30 03:17:04

问题


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).

I read somewhere that I can use square brackets and triedlove.getVersion()[1] but it says "Attempt to index a number value."


回答1:


For the sake of example let's assume that love.getVersion() is defined as follows:

function love.getVersion ()
   return 1, 2, 3, "four"
end

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)

outputs:

A:  3   four
B:  3

In case of doubts - Reference Manual - select.

Using a table wrapper:

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])

outputs:

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])

outputs:

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)

outputs:

E:  2

Please note that I skipped any following _ in the example (no need for local _, minor, _, _).




回答2:


Here is the function signature: [https://love2d.org/wiki/love.getVersion] which just returns multiple value, if understand to achieve like what you are asking for, you can have wrapper around getVersion to have lua table returned either like below or in array format

local function getVersion()
 local meta_data = {minor_version = "0.1", major_version = "1"}
 return meta_data
end

local res = getVersion()
print ("minor_version: ", res['minor_version'])
print ("major_version: ", res['major_version'])


来源:https://stackoverflow.com/questions/59379596/getting-multiple-values-from-a-function-without-creating-a-variables-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!