RoGo Magazine - Beginner Lua Lesson 6: “return” and Callbacks


Posted in Tutorials

October 25, 2014 at 12:39 AM

Beginner Lua Lesson 6: “return” and Callbacks

By DerAtomik

Editors: Zaqre

Previous Beginner Lua Lesson

First Beginner Lua Lesson


The word “return” is bold and dark blue, just like “function,” “end,” etc. What it does, essentially, allows you to retrieve anything from a separate function. You call upon the function, and in that function, add “return,” followed by what to send back to what called upon the function; these must be on the same line, spaced once.


function RetrieveAlivePlayers()
local count = 0
for i, plyr in pairs(game.Players:GetPlayers()) do
if plyr.PlayerIsAlive.Value then --Pretend this exists on the Player
count = count + 1
return count

--Loop checks every 10 seconds how many Players are alive
while true do
local AlivePlayers = RetrieveAlivePlayers()
print("There are currently "..AlivePlayers.." alive!")


A callback is the same as a function mostly. The only difference is how the two are fired. With a function, you use the connect method like you would an event. As for a callback, you instead use an “=” to make it seem as if you’re setting a value. However, this can essentially be the case. Callbacks are actually very rare. One of the only usages is RemoteFunction.


--[[The following Callback halts the game from
shutting down until the Callback finishes after
the last player has left. return is
surprisingly not used.
game.OnClose = function()
print("Waiting 5 seconds before shutting down...")