7_R3X
7_R3X

Reputation: 4370

Defining functions in Lua

I read that we can declare a function in Lua with two different syntax:

function pr()
    print("I'm function pr()")
end

printt = function()
    print("I'm function printt()")
end

pr()
printt()

Though the functions seem to work exactly the same way when they're called I want to know if there's a difference between their implementation at lower level. Does the interpretor treats them exactly the same or do they differ in terms of speed, implementation, or in any way?

Upvotes: 3

Views: 1919

Answers (1)

Yu Hao
Yu Hao

Reputation: 122373

There's no real difference between the two. The first one is just a syntactic sugar to the second form.

From the reference manual Function Definitions:

The syntax for function definition is

  functiondef ::= function funcbody
  funcbody ::= ‘(’ [parlist] ‘)’ block end

The following syntactic sugar simplifies function definitions:

  stat ::= function funcname funcbody
  stat ::= local function Name funcbody
  funcname ::= Name {‘.’ Name} [‘:’ Name]

The statement

  function f () body end

translates to

  f = function () body end

Upvotes: 2

Related Questions