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

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
主站蜘蛛池模板: 东乌珠穆沁旗| 吴川市| 盖州市| 威海市| 冷水江市| 五指山市| 监利县| 张家界市| 芜湖市| 宽甸| 梓潼县| 磐安县| 布尔津县| 竹山县| 巩留县| 华亭县| 朔州市| 桑植县| 金湖县| 泸西县| 泗洪县| 安顺市| 长白| 阳原县| 三都| 手游| 尉氏县| 剑川县| 抚远县| 周口市| 南丹县| 临邑县| 蒙山县| 兴海县| 关岭| 彩票| 台中县| 军事| 商都县| 高雄市| 竹北市|