Tutorial: Passing Data To/From Functions

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

local tanx=math.abs(12)/math.abs(15)

local atanx=math.atan(tanx)--result inradians

local angle=atanx *180/math.pi--converted todegrees

print(angle)

tanx=math.abs(34)/math.abs(-16)

atanx=math.atan(tanx)--result inradians

angle=atanx *180/math.pi--converted todegrees

print(angle)

tanx=math.abs(80)/math.abs(-4)

atanx=math.atan(tanx)--result inradians

angle=atanx *180/math.pi--converted todegrees

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:

1

2

3

4

5

6

7

8

9

10

local functioncalculateAngle(sideA,sideB)

local tanx=math.abs(sideB)/math.abs(sideA)

local atanx=math.atan(tanx)--result inradians

local anglex=atanx *180/math.pi--converted todegrees

returnangle

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:

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:

1

local result=myFunction("somestring")

1

2

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:

1

local result=myFunction(10)

1

2

local myNumber=10

local result=myFunction(myNumber)

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

1

local result=myFunction(1,2,3)

1

2

3

4

5

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:

1

2

3

local functionmakeBusinessCard(firstName,lastName,address,city,state,postalCode)

--functionaction(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:

print("You must specify true or false if you want counter-clockwise rotation.")

returnfalse

end

local myAmount=amount

if(reverse)then

myAmount=myAmount *-1

end

target.rotation=target.rotation+myAmount

returntrue

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:

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

1

local direction=reverse orfalse

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:

1

2

3

4

5

6

local functionhandleTouch(event)

if(event.phase=="ended")then

--dosomething

end

returntrue

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:

1

2

3

4

5

6

local functionhandleTouch(e)

if(e.phase=="ended")then

--dosomething

end

returntrue

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.

1

returnangle

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:

1

2

3

4

local functionreturnTwoNumbers()

return10,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.

1

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:

1

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:

1

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.

Disclaimer: SDKNews.com only syndicates the blog entries from various SDK blogs.
We are not the creator/author of these entries (posts). Product names, brand names
and company names mentioned on this site may be trademarks of their respective owners.