简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM