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

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.
主站蜘蛛池模板: 康平县| 德州市| 邵东县| 桐城市| 乐安县| 平江县| 正镶白旗| 宿州市| 新郑市| 岢岚县| 宁南县| 栖霞市| 临安市| 河津市| 攀枝花市| 涟水县| 晋宁县| 井冈山市| 玉龙| 江陵县| 军事| 兴义市| 兴山县| 同德县| 金秀| 昌乐县| 娄底市| 嘉峪关市| 漳浦县| 莱芜市| 海口市| 深水埗区| 北票市| 桐庐县| 石狮市| 密山市| 顺昌县| 海口市| 怀化市| 思茅市| 兴城市|