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

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
主站蜘蛛池模板: 平阳县| 罗平县| 济南市| 右玉县| 靖宇县| 阜新| 临沭县| 吉林省| 湄潭县| 绥芬河市| 藁城市| 双桥区| 珲春市| 达州市| 石楼县| 洛阳市| 广安市| 米易县| 海原县| 永年县| 肇源县| 台南市| 万荣县| 南京市| 封丘县| 镇江市| 山西省| 巴彦县| 福清市| 蓬莱市| 淄博市| 甘孜| 石景山区| 磐安县| 定兴县| 大渡口区| 遵义县| 莱州市| 天祝| 洪湖市| 大洼县|