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

  • 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.
主站蜘蛛池模板: 醴陵市| 甘洛县| 嘉善县| 五华县| 西城区| 关岭| 玛多县| 安庆市| 庆安县| 阳原县| 长治县| 武夷山市| 包头市| 嘉鱼县| 龙陵县| 潍坊市| 文登市| 闻喜县| 东乡县| 丹巴县| 宿松县| 大姚县| 柯坪县| 济宁市| 车险| 海原县| 平阴县| 东源县| 新余市| 盱眙县| 苍山县| 青铜峡市| 怀安县| 温泉县| 吉首市| 进贤县| 阿鲁科尔沁旗| 伊宁县| 佛教| 石泉县| 和田县|