Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...