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

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

问题描述



 本地setmetatable,getmetatable等.. = setmetatable,getmetatable等。

让本地函数让Lua在经常使用时更快地访问它们?

解决方案

本地数据在堆栈中,因此它们会更快地访问它们。但是,我严重怀疑函数调用时间 setmetatable 对于某些程序实际上是一个重大问题。



这是可能的解释:


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


    1. 一个模块不会意外覆盖另一个模块的函数。 b $ b

    2. 如果模块不小心做到这一点,模块返回的表格中的原始函数仍然可以访问。只有通过使用 local modname = requiremodname才能保证得到正确且只有该模块暴露的内容。


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



  2. 读取 local 变量的人的过早优化可以更快地被访问,然后决定让所有内容 local


一般来说,这是一个很好的做法。那么,除非是因为#2。


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..

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

解决方案

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. 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. One module cannot accidentally overwrite another module's functions.

    2. 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.

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

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

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

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

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