Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

scope - Why make global Lua functions local?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...