Tutorial: Passing Data To/From Functions

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn1

When 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:

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:

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:

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:

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:

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

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

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:

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:

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

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:

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:

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.

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:

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.

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:

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:

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.

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn1
Rob Miracle

Rob Miracle creates mobile apps for his own enjoyment and the amusement of others. He serves the Corona Community in the forums, on the blog, and at local events.

This entry has 11 replies

  1. Alex says:

    How to pass multiple parameters on a timer calling a function, for example?

    • Rob Miracle says:

      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.

  2. Chris says:

    Nice tutorial.

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

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

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

  3. Suhada says:

    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)
    if ( param.b ) then
    print (‘b is ‘,param.b)
    if ( param.c ) then
    print (‘c is ‘,param.c)
    print (‘———————-‘)

    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 } )

  4. Caleb P says:

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

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

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

    • Caleb P says:

      Whoopsies – sorry for the [lua] tags, thought this allowed them 🙂

  5. helios says:

    what do you call this method of programming whre you assign the function to an object?


    • Rob Miracle says:

      I would describe this as “adding a method to an object”.


  6. Archer says:

    Typo in second example, anglex needs to be angle if I am not mistaken

    • Rob Miracle says:

      Good catch Archer. It’s fixed.


  7. I think, it will be good to add information on that how to receive the necessary parameter using the select() to the last paragraph:
    From docs:
    print(string.find(“hello hello”, ” hel”)) –> 6 9
    print(select(1, string.find(“hello hello”, ” hel”))) –> 6
    print(select(2, string.find(“hello hello”, ” hel”))) –> 9

Leave a reply

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">