在Lua中向前定义功能吗? [英] Forward define a function in Lua?

查看:53
本文介绍了在Lua中向前定义功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何调用一个需要从其创建之上调用的函数?我读了一些有关前向声明的内容,但是Google在这种情况下并没有帮助.正确的语法是什么?

How do I call a function that needs to be called from above its creation? I read something about forward declarations, but Google isn't being helpful in this case. What is the correct syntax for this?

推荐答案

Lua是一种动态语言,函数只是可以用()运算符调用的一种值.因此,您不必真正声明函数,而只需在调用时确保作用域中的变量就是您认为的变量即可.

Lua is a dynamic language and functions are just a kind of value that can be called with the () operator. So you don't really need to forward declare the function so much as make sure that the variable in scope when you call it is the variable you think it is.

对于包含函数的全局变量,这根本不是问题,因为全局环境是解析变量名的默认位置.但是,对于局部函数,您需要确保局部变量已经在需要调用其存储的值的词法范围内,并且还必须确保在运行时它确实持有可以被调用的值.

This is not an issue at all for global variables containing functions, since the global environment is the default place to look to resolve a variable name. For local functions, however, you need to make sure the local variable is already in scope at the lexical point where you need to call the value it stores, and also make sure that at run time it is really holding a value that can be called.

例如,这是一对相互递归的局部函数:

For example, here is a pair of mutually recursive local functions:

local a,b
a = function() return b() end
b = function() return a() end

当然,这也是一个使用尾部调用进行无限递归的示例,该递归不执行任何操作,但这里的重点是声明.通过在其中未存储任何函数之前用local声明变量,可以在示例的其余部分的词法范围内将这些名称称为局部变量.然后存储这两个函数,每个函数都引用另一个变量.

Of course, that is also an example of using tail calls to allow infinite recursion that does nothing, but the point here is the declarations. By declaring the variables with local before either has a function stored in it, those names are known to be local variables in lexical scope of the rest of the example. Then the two functions are stored, each referring to the other variable.

这篇关于在Lua中向前定义功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆