Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining functions in Lua

Tags:

function

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?

like image 205
7_R3X Avatar asked Jul 30 '26 13:07

7_R3X


1 Answers

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
like image 89
Yu Hao Avatar answered Aug 01 '26 07:08

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!