- Lua Quick Start Guide
- Gabor Szauer
- 256字
- 2021-08-05 10:30:40
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
- ASP.NET Web API:Build RESTful web applications and services on the .NET framework
- Monkey Game Development:Beginner's Guide
- LabVIEW入門與實戰開發100例
- JMeter 性能測試實戰(第2版)
- Git高手之路
- Python Network Programming Cookbook(Second Edition)
- C語言程序設計案例式教程
- Go并發編程實戰
- Mastering React
- 用案例學Java Web整合開發
- Spring Security Essentials
- Scala編程(第5版)
- Python編程:從入門到實踐(第3版)
- Maker基地嘉年華:玩轉樂動魔盒學Scratch
- Python趣味編程與精彩實例