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

查看:33
本文介绍了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天全站免登陆