Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Beginner Question on Functions

edited March 2013 in Questions Posts: 140

Greetings... I'm trying to get a better grasp of Lua functions and I came across an article by Roberto Ierusalimschy (http://www.inf.puc-rio.br/~roberto/docs/ry09-03.pdf) entitled 'Programming with Multiple Paradigms in Lua.' In section 3, Mr. Ierusalimschy explains that Lua offers first-class functions with lexical scoping. I don't need definitions for first-class functions or lexical scoping--I can research the Internet for that. My problem is that Roberto uses this line as an example:

    (function (a,b) print(a+b) end)(10, 20)

He said, 'It creates an anonymous function that prints the sum of its two parameters and applies that function to arguments 10 and 20'. I had never seen a function like this before, so I tried to put it into Codea for closer examination and experimentation. Unfortunately, Codea returns an error at this line when I hit 'Run.' What am I missing here? My presumption was that the a and b variables would get their values from the parameters 10 and 20, add them together and then print them.

Comments

  • Posts: 202

    This heavily depends on what you have written before since Lua is quite liberal regarding newlines. Lua may think that you have written a function name the line before and now you are trying to pass parameters. If you write the line at the top of the file you'll get no parser error. There were some changes in Lua 5.2 to accommodate this.

    Use the semicolon as a panacea:


    ;(function (a,b) print(a+b) end)(10, 20)
  • Posts: 140

    Thanks @Codeslinger. That answers it. I was using one test program for all of my experiments and Lua reacted exactly as you said. This serves as a valuable lesson on the use of anonymous functions.

Sign In or Register to comment.