为什么要让全局 Lua 函数本地化? [英] Why make global Lua functions local?

查看:50
本文介绍了为什么要让全局 Lua 函数本地化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在看一些Lua源代码,经常在文件开头看到这样的东西:

I've been looking at some Lua source code, and I often see things like this at the beginning of the file:

local setmetatable, getmetatable, etc.. = setmetatable, getmetatable, etc..

他们是否只将函数本地化,以便在经常使用时让 Lua 更快地访问它们?

Do they only make the functions local to let Lua access them faster when often used?

推荐答案

本地数据在堆栈中,因此它们确实可以更快地访问它们.但是,我严重怀疑 setmetatable 的函数调用时间实际上对某些程序来说是一个重要问题.

Local data are on the stack, and therefore they do access them faster. However, I seriously doubt that the function call time to setmetatable is actually a significant issue for some program.

以下是对此的可能解释:

Here are the possible explanations for this:

  1. 防止污染全球环境.模块的现代 Lua 约定是不让它们直接将自己注册到全局表中.他们应该建立一个本地函数表并返回它们.因此,访问它们的唯一方法是使用局部变量.这迫使很多事情:

  1. Prevention from polluting the global environment. Modern Lua convention for modules is to not have them register themselves directly into the global table. They should build a local table of functions and return them. Thus, the only way to access them is with a local variable. This forces a number of things:

  1. 一个模块不能意外覆盖另一个模块的功能.

  1. One module cannot accidentally overwrite another module's functions.

如果模块不小心这样做,模块返回的表中的原始函数仍然可以访问.只有通过使用 local modname = require "modname",您才能保证准确且仅获得该模块公开的内容.

If a module does accidentally do this, the original functions in the table returned by the module will still be accessible. Only by using local modname = require "modname" will you be guaranteed to get exactly and only what that module exposed.

包含其他模块的模块不能相互干扰.您从 require 返回的表始终是模块存储的内容.

Modules that include other modules can't interfere with one another. The table you get back from require is always what the module stores.

  • 阅读local 变量访问速度更快"的人的过早优化,然后决定使所有内容local.

  • A premature optimization by someone who read "local variables are accessed faster" and then decided to make everything local.

    总的来说,这是一种很好的做法.好吧,除非是因为#2.

    In general, this is good practice. Well, unless it's because of #2.

    这篇关于为什么要让全局 Lua 函数本地化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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