Lua:如何在定义函数之前调用它? [英] Lua: How to call a function prior to it being defined?

查看:372
本文介绍了Lua:如何在定义函数之前调用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建函数的语法是什么,然后在代码中进一步添加其实现?

What is the syntax to create the function, but then add it's implementation further down in code?

大致如此:

  • 定义功能doX
  • 调用doX(在代码中进一步向下)
  • doX实现(即,所有功能都位于文件底部)
  • Define function doX
  • Call doX (further down in the code)
  • doX implemention (i.e. all functions down at the bottom of the file)

推荐答案

哦...所以在实际定义函数之前,真的没有办法调用funcName吗?也就是说,您仍然需要确保在首次调用funcName本身之前已调用defineIt?

oh...so there's really no way to call funcName prior to having actually defined the function then? i.e. you still need to make sure defineIt is called before your first call to funcName itself?

我想澄清这一点,我认为答案比发表评论要好.

I wanted to clarify this point, and I felt that an answer would be the better way than a comment.

Lua是比C或C ++简单得多的语言.它建立在一些简单的基础上,并带有一些语法糖,使其中的某些部分更容易被吞咽.

Lua is a much simpler language than C or C++. It is built on some simple foundations, with some syntactic sugar to make parts of it easier to swallow.

Lua中没有功能定义"之类的东西.函数是一流的对象.它们是Lua中的,就像数字28或字符串文字"foo"是值一样. 函数定义"只是将一个值(即函数)设置为变量.变量可以包含任何类型的值,包括函数值.

There is no such thing as a "function definition" in Lua. Functions are first-class objects. They are values in Lua, just like the number 28 or the string literal "foo" are values. A "function definition" simply sets a value (namely, the function) into a variable. Variables can contain any kind of value, including a function value.

所有函数调用"都是从变量中获取值并尝试对其进行调用.如果该值是一个函数,则使用给定的参数调用该函数.如果该值不是函数(或具有__call元方法的表/用户数据),则将出现运行时错误.

All a "function call" is is taking the value from a variable and attempting to call it. If that value is a function, then the function gets called with the given parameters. If that value is not a function (or a table/userdata with a __call metamethod), then you get a runtime error.

您不能再调用尚未在变量中设置的函数了:

You can no more call a function that hasn't been set in a variable yet than you can do this:

local number = nil
local addition = number + 5
number = 20

并且希望addition中有25个.那不会发生.因此,出于相同的原因,您不能这样做:

And expect addition to have 25 in it. That's not going to happen. And thus, for the same reason, you can't do this:

local func = nil
func(50)
func = function() ... end

正如Paul所指出的,您可以从定义的另一个函数中调用一个函数.但是,除非您在变量中填写了要包含的内容,否则您就不能执行调用它的函数.

As Paul pointed out, you can call a function from within another function you define. But you cannot execute the function that calls it until you've filled in that variable with what it needs to contain.

这篇关于Lua:如何在定义函数之前调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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