Posted on by

functions-featWhen people first start programming, they quickly learn that writing all of their code in one large chunk becomes difficult to manage. As such, programming languages support a concept called functions which allow the programmer to direct parts of the program to perform a specific task. In addition to writing clean, organized code, functions are the foundation behind the concept of DRY or “Don’t Repeat Yourself.” If you find yourself writing the same basic block of code multiple times, with only minor differences in each block, using a function is probably in order. Also, any time you want to do the same thing multiple times, a function is usually the best approach.

“Similar Task” Functions

Let’s consider a scenario where we only need to change a small portion of code around a single data value:

local tanx = math.abs( 12 ) / math.abs( 15 )
local atanx = math.atan( tanx )  -- result in radians
local angle = atanx * 180 / math.pi  -- converted to degrees

print( angle )

tanx = math.abs( 34 ) / math.abs( -16 )
atanx = math.atan( tanx )  -- result in radians
angle = atanx * 180 / math.pi  -- converted to degrees

print( angle )

tanx = math.abs( 80 ) / math.abs( -4 )
atanx = math.atan( tanx )  -- result in radians
angle = atanx * 180 / math.pi  -- converted to degrees

print( angle )

In this code, we are simply calculating an angle based on the width and height of a triangle. As you can see, this code becomes repetitive — we are basically doing the exact same thing several times over, changing only the parameters of the triangle each time. This is a prime example of where a function is useful. Let’s look at a re-write of this code using a function:

local function calculateAngle( sideA, sideB )
   local tanx = math.abs( sideB ) / math.abs( sideA )
   local atanx = math.atan( tanx )  -- result in radians
   local angle = atanx * 180 / math.pi  -- converted to degrees
   return angle
end
--
print( calculateAngle( 15, 12 ) )
print( calculateAngle( -16, 34 ) )
print( calculateAngle( -4, 80 ) )

Notice that we have written the basic code just once, but we use variables to do the calculations. After the function block, we take the value of the variable angle, returned by the function, and print its value to the Terminal/console.

Sending Data In

Functions don’t require parameters (data) passed to them, nor are they required to return (send back) any data when they execute. In most cases, however, you will need the function to act on some specific data like the sideA and sideB values passed to the angle calculator above.

Data is sent to functions as parameters, or “arguments” as some developers refer to them. These are passed to the function as a comma-separated list of values or variables:

local picWidth = 32
local pic = display.newImageRect( "pic.png", picWidth, 64 )

In this example, we call a common Corona function, display.newImageRect(), and pass to it:

  1. a string value
  2. a variable
  3. a number

Spacing between the commas doesn’t matter, but string values must be passed within quotes, while variables must be passed without quotes. Other items can be passed as well, including tables of data and even other functions. Essentially, any valid Lua data type can be passed to a Lua function. Let’s look at some examples:

local result = myFunction( "somestring" )
local myString = "somestring"
local result = myFunction( myString )

These two cases are identical in behavior, except that the sole parameter is pre-declared as the variable myString in the second example. Here are some other equivalent cases:

local result = myFunction( 10 )
local myNumber = 10
local result = myFunction( myNumber )

And here’s an equivalent which passes in a table:

local result = myFunction( {1, 2, 3} )
local myTable = {}
table[1] = 1
table[2] = 2
table[3] = 3
local result = myFunction( myTable )

When you create the function, list all of the parameters you expect to process within it:

local function makeBusinessCard( firstName, lastName, address, city, state, postalCode )
   -- function action(s)
end

In this example, every parameter can be a string value, but functions can accept a mix of data types. As a developer, it’s your responsibility to ensure that the values passed to your function are what you expect them to be.

Let’s say you want a function that accepts three parameters: a display object, a number, and a boolean:

local function rotateImage( target, amount, reverse )
   -- target: the display object to manipulate
   -- amount: amount to rotate the object
   -- reverse: if true, rotate counter-clockwise
   if ( target == nil ) or ( type(target) ~= "table" ) or ( target.removeSelf == nil ) then
      print( "Error, target is not a display object!" )
      return false
   end
   if ( amount == nil ) or ( type(amount) ~= "number" ) then
      print( "Invalid value for amount, must be a number!" )
      return false
   end
   if ( reverse == nil ) or ( type(reverse) ~= "boolean" ) then
      print( "You must specify true or false if you want counter-clockwise rotation." )
      return false
   end

   local myAmount = amount
   if ( reverse ) then 
      myAmount = myAmount * -1
   end
   target.rotation = target.rotation + myAmount
   return true
end

With this in place, it would be nice if the reverse parameter was optional. Fortunately, you can change the code just a little and accomplish this. Let’s look at the same function with just a few slight changes:

local function rotateImage( target, amount, reverse )
   if ( target == nil ) or ( type(target) ~= "table" ) or ( target.removeSelf == nil ) then
      print( "Error, target is not a display object!" )
      return false
   end

   if ( amount == nil ) or ( type(amount) ~= "number" ) then
      print( "Invalid value for amount, must be a number!" )
      return false
   end

   local direction = reverse or false
   local myAmount = amount
   if ( direction ) then
      myAmount = myAmount * -1
   end
   target.rotation = target.rotation + myAmount

   return true
end

Notice that we added another variable – direction – which may look odd at first glance:

local direction = reverse or false

This is a Lua feature where you can populate a variable depending on whether a value is set or not. In this case, if the parameter reverse has a value, it will be saved into the variable direction. If for any reason the first parameter is nil (not provided), the second value will be used (in this case false).

Parameter Names

Parameter names should be whatever makes sense to you — they are not required to be anything in particular. However, anyone inspecting your code later may have trouble understanding what values the function is expecting. Sometimes you may copy functions from other projects, tutorials, templates, or other sources and include them in your code, so it’s wise to name the parameters sensibly. Let’s inspect a touch handling function as an example:

local function handleTouch( event )
   if ( event.phase == "ended" ) then
      -- do something
   end
   return true
end

This function requires just a single parameter – event – which is a Lua table that represents the “event” of the user touching the screen. This table has various values in it, including the phase of the event and the x/y location of the touch coordinates on the screen.

Note that some programmers may write the same function as follows:

local function handleTouch( e )
   if ( e.phase == "ended" ) then
      -- do something
   end
   return true
end

These functions are identical in behavior except that the parameter name event has been shortened to e. While e isn’t a descriptive name, it demonstrates that the name doesn’t matter. However, it’s good practice to name parameters sensibly so you don’t forget the purpose sometime in the future.

Getting Data Out

Frequently, it’s important to retrieve some data from the function. In the first example of this tutorial, we needed to get the angle value based on the parameters we passed in. Functions send data back to you via the simple return command, followed by the values to return.

return angle

Values, Plural?

Unlike most other programming languages, Lua allows a function to return multiple values (traditional languages usually return only one value). If you need to return multiple values, just provide a comma-separated list of values to return, and when you call the function, provide variables for each value returned:

local function returnTwoNumbers()
   return 10, 20
end
local value1, value2 = returnTwoNumbers()

This function will return the values 10 and 20 and put them into the variables value1 and value2 respectively. While returning two fixed numbers in this example isn’t very meaningful, it illustrates the fact that many functions, including Corona API calls, return multiple values.

One example is the built-in Corona function map:addMarker() , which should return a useful value, but may actually return an error message if the passed parameters are flawed.

local result, errorMessage = myMap:addMarker( latitude, longitude, options )

Another example is the Corona function physics:getLinearVelocity(). Because a physical linear velocity always consists of two velocity values, x and y, this function returns both values when you call it:

local linearX, linearY = myObject:getLinearVelocity()

Fortunately, you are not required to store every returned value as a variable. If you don’t need to even consider certain returned values, just request those that you want to regard and the others will be discarded. For example, if you only care about the linear x velocity in the above example, just store that value and the linear y value will be discarded:

local linearX = myObject:getLinearVelocity()

In Summary…

Hopefully this tutorial has helped you understand the nature of functions, their considerable usefulness, how to pass data of different types to functions, and how to retrieve the information you need. Remember that clean coding and smart use of functions will improve the structure and performance of your app, as well as make the program code easier to understand.


Posted by . Thanks for reading...

10 Responses to “Tutorial: Passing Data To/From Functions”

    • Rob Miracle

      You need to use Lua closures for that. In Javascript they are known as anonymous functions. Since timer.performWithDelay can’t pass any parameters you simply wrap your real function call inside an empty function. Let’s say you have a function called updateScore() that takes the score and some time left that you would normally call:

      updateScore(myScore, timeLeft)

      To put that into a timer:

      scoreTimer = timer.performWithDelay( 1000, function() updateScore(myScore, timeLeft); end, 0 )

      See how I wrapped the updateScore() call with an empty function definition: function() and end. Note the semi-colon as well. It’s good to keep multiple things on a line separate.

      Reply
  1. Chris

    Nice tutorial.

    You might want to extend your article and add the ability to add an undefined amount of arguments using “…”.

    Example:
    function addManyNumbers (…)
    local sum
    for i,v in ipairs(arg) do
    rum = rum + v
    end
    return sum
    end

    I know it’s possible using a table aswell, but this might be useful to know aswell :)

    Reply
  2. Suhada

    Great tutorial thanks. I really like the regular tutorials – like a trickle feed of corona community training.

    Sometimes it’s useful to have optional parameters where all of them are optional.
    One neat way of dealing with this is to pass all the variables as one table parameter and use the names of the table items:

    local function abc( param )
    if ( param.a ) then
    print (‘a is ‘,param.a)
    end
    if ( param.b ) then
    print (‘b is ‘,param.b)
    end
    if ( param.c ) then
    print (‘c is ‘,param.c)
    end
    print (‘———————-‘)
    end

    then
    abc{a=’hello’}
    will print
    a is hello
    ———————-

    abc{b=’greetings’, c=’goodbye’}
    will print
    b is greetings
    c is goodbye
    ———————-

    and as it’s a table the order of the parameters coming in doesn’t matter so
    abc{c=’cheese’, a=’tomato’}
    will print
    a is tomato
    c is cheese
    ———————-

    note that abc{ whatever }
    is short for abc( { whatever } )

    Reply
  3. Caleb P

    Great for beginners, but a quick problem is:
    [lua]
    local variable = whatever or false
    [/lua]

    Evaluates to false if “whatever” evaluates to “not”, not just nil. Values of “false” will still get the second declaration. Example:

    [lua]
    local function someFunction(booleanArgument)
    local booleanArgument = booleanArgument or true
    print(“booleanArgument is ” .. tostring(booleanArgument))
    end
    someFunction(false) — Ought to print “booleanArgument is false”, but prints “booleanArgument is true”
    [/lua]

    Reply

Leave a Reply

  • (Will Not Be Published)