简体   繁体   English

在 Lua 中定义函数

[英]Defining functions in Lua

I read that we can declare a function in Lua with two different syntax:我读到我们可以用两种不同的语法在 Lua 中声明一个函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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