官术网_书友最值得收藏!

Returning multiple values

Lua has a unique feature that many traditional languages don't, multiple return values. This feature allows one function to return multiple values. To return multiple values, assign the result of the function to a list of variables separated by commas.

For example, you could write a function that takes a number for an argument and returns both the squared and cubed values of that number:

-- Declare the function
function SquareAndCube(x)
squared = x * x
cubed = x * x * x
return squared, cubed
end

-- Call the function
s, c = SquareAndCube(2)
print ("Squared: " .. s) -- will print: Squared: 4
print ("Cubed: " .. c) -- will print: Cubed: 8

Like with function arguments, the number of values a function returns does not have to match the number of variables it is assigned to. What happens if you return two values, but try to assign them to three variables? The extra variables will have a default value of nil:

s, c, q = SquareAndCube(2) -- Call the same function
print ("Squared: " .. s) -- will print: Squared: 4
print ("Cubed: " .. c) -- will print: Cubed: 8
print ("Quartic: " .. tostring(q)) -- will print: Quartic: nil

Similarly, you can return two values and try to assign them to a single variable. In this case, the first value is assigned and the rest of the variables are discarded. The following code demonstrates this:

square = SquareAndCube(2) -- Call the same function
-- rest of results are discarded
print ("Squared: " .. square) -- will print: Squared: 4
主站蜘蛛池模板: 怀仁县| 永修县| 江门市| 汶上县| 大同县| 甘孜县| 巴楚县| 井陉县| 古交市| 吉木乃县| 石狮市| 巫溪县| 台北市| 平凉市| 平凉市| 刚察县| 阳泉市| 辽宁省| 南涧| 鹤庆县| 琼中| 宣化县| 油尖旺区| 新平| 堆龙德庆县| 永安市| 集安市| 吴江市| 星子县| 六安市| 集贤县| 顺义区| 彭阳县| 太湖县| 丰台区| 峨眉山市| 铜川市| 阜宁县| 敦煌市| 栾城县| 巴林右旗|