Sie sind auf Seite 1von 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

Forums

Download

Sign-in

Products
Blog Home

Community

Resources

Pricing

Blog

About

Site Search

Tutorials, Tips and Demos

Tutorial: Passing Data To/From Functions

FREE DOWNLOAD

Tutorial: Passing Data To/From Functions


Posted on October 8, 2013 by Rob Miracle
Like 0 Send Tweet 1

Need Pro Features?


BUY NOW

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 Dont 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.

Starting building a
Game Business app eBook Hybrid app Educational app
The possibilities are endless!

Similar Task Functions


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

Corona in the Classroom

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.

local tanx = math.abs( 12 ) / math.abs( 15 ) local atanx = math.atan( tanx ) -- result in radians -- converted to degrees Corona is the tool of choice among schools and universities such as the Academy of Art University, BYU and more! local angle = atanx * 180 / math.pi print( angle ) tanx = math.abs( 34 ) / math.abs( -16 ) atanx = math.atan( tanx ) -- result in radians -- converted to degrees angle = atanx * 180 / math.pi print( angle ) tanx = math.abs( 80 ) / math.abs( -4 ) atanx = math.atan( tanx ) -- result in radians -- converted to degrees angle = atanx * 180 / math.pi print( angle )

Blog Post Categories


Amazon Kindle (21) Android (65) Corona Enterprise (5) Corona Geek (103) Corona SDK (225) Daily Build (50) eBooks (12) Education (11)

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. Lets look at a re-write of this code using a function:

Events and Listeners (48) FAQ (34) Flash (18) Friday Night Forum (15)

1.

local function calculateAngle( sideA, sideB )

Game Development (66)

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 1 of 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

2. 3. 4. 5. 6. 7. 8. 9. 10.
--

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

Google+ Hangouts (76) Guest Bloggers (144) iPad (77) iPhone (95) Lua (26) Mobile App of the Week (159) News & Announcements (258) NOOK (25) Partners (16)

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.

Showcase (39) Tech (63) Training/Support (28) Tutorials, Tips and Demos (142) Uncategorized (122) Videos (46) Groups and Events (41)

Sending Data In
Functions dont 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:

1. 2.

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 doesnt 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. Lets 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 )

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 2 of 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

And heres 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 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, its your responsibility to ensure that the values passed to your function are what you expect them to be. Lets say you want a function that accepts three parameters: a display object, a number, and a boolean:

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24.

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. Lets look at the same function with just a few slight changes:

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 3 of 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

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:

12.

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 its wise to name the parameters sensibly. Lets inspect a touch handling function as an example:

1. 2. 3. 4. 5. 6.

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:

1. 2.

local function handleTouch( e ) if ( e.phase == "ended" ) then

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 4 of 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

3. 4. 5. 6.

-- 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 isnt a descriptive name, it demonstrates that the name doesnt matter. However, its good practice to name parameters sensibly so you dont forget the purpose sometime in the future.

Getting Data Out


Frequently, its 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.

5.

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 commaseparated list of values to return, and when you call the function, provide variables for each value returned:

1. 2. 3. 4.

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 isnt 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 dont 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()

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 5 of 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

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 Rob Miracle. Thanks for reading...


Like 0 Send Tweet 1

Post Category: Tutorials, Tips and Demos Post Tags: function tutorial

Ready to bring your ideas to life?


DOWNLOAD CORONA SDK
Need access to native libraries or services? Corona Enterprise allows you to call any Objective-C or Java library from within Corona.

3 Responses to Tutorial: Passing Data To/From Functions

Alex
How to pass multiple parameters on a timer calling a function, for example?
October 8th, 2013

Reply

Rob Miracle
You need to use Lua closures for that. In Javascript they are known as anonymous functions. Since timer.performWithDelay cant pass any parameters you simply wrap your real function call inside an empty function. Lets 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. Its good to keep multiple things on a line separate.
October 8th, 2013

Reply

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 6 of 7

Tutorial: Passing Data To/From Functions | Corona Labs

10/10/13 4:54 PM

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 its possible using a table aswell, but this might be useful to know aswell
October 9th, 2013

Reply

Leave a Reply
Name (required) Your Name Mail (required) Your Email Website Your Website Your Comment Here...
(Will Not Be Published)

Submit Comment

Products Corona SDK Enterprise Support & Training

Community Forum Groups and Events Hall of Fame Corona Ambassadors Certified Developers

Resources Documentation 3rd Party Tools Case Studies FAQs

Get Corona Starter: Publish Free Buy Pro

About Jobs Press Contact

Social

Copyright 2009-2013 Corona Labs Inc. A mobile development software company. All rights reserved. Privacy Policy Terms and Conditions

http://coronalabs.com/blog/2013/10/08/tutorial-passing-data-tofrotions/?utm_source=newsletter&utm_medium=email&utm_campaign=101013

Page 7 of 7

Das könnte Ihnen auch gefallen