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

前端 未结 2 1459
孤街浪徒
孤街浪徒 2021-01-15 13: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 c         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-15 13:30

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

提交回复
热议问题