- Lua Quick Start Guide
- Gabor Szauer
- 245字
- 2021-08-05 10:30:40
Returning a value
Functions don't just take input, they can also return some output to the calling code. This is done through a return value. When a function returns a value, it can be called as part of an expression or as a standalone statement.
If a function is called as a part of an expression, its return value can be assigned to a variable, or used wherever a variable could be used. The following code demonstrates this concept:
-- declare the function
function AddTwo(x)
result = x + 2
print (x .. " + 2 = " .. result)
return result
end
AddTwo(3) -- calls as statement
nine = 7 + AddTwo(5) -- Call as expression
print ("adding two " .. AddTwo(3)) -- Call as expression
When a function hits a return statement, it returns whatever data follows and stops executing. If you have code after your return statement, that code will not execute, for example:
-- Declare the function
function SquareIt(number)
result = number * number
print ("this will print") -- WILL PRINT!
do
return result
end
print ("this will not print") -- WILL NOT PRINT
end
-- Call the function
four = SquareIt(2) -- Will print: this will print
print(four) -- Will print: 4
Why is the return value inside of a do/end block? In Lua, the return keyword is only valid when followed by the end keyword. Without the do/end block around the return statement, this code would not compile, because following a return with a print statement is not valid.
推薦閱讀
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第二版)
- Maven Build Customization
- Full-Stack Vue.js 2 and Laravel 5
- 琢石成器:Windows環(huán)境下32位匯編語言程序設(shè)計(jì)
- Haxe Game Development Essentials
- Working with Odoo
- 創(chuàng)意UI:Photoshop玩轉(zhuǎn)APP設(shè)計(jì)
- Qlik Sense? Cookbook
- Java Web從入門到精通(第2版)
- MySQL 8從零開始學(xué)(視頻教學(xué)版)
- 人人都能開發(fā)RPA機(jī)器人:UiPath從入門到實(shí)戰(zhàn)
- Java高級(jí)程序設(shè)計(jì)
- Swift High Performance
- JavaScript前端開發(fā)基礎(chǔ)教程
- Visual C++程序設(shè)計(jì)全程指南