在竞争激烈的游戏行业中,尤其页游,面对策划复杂和频繁的需求,使用脚本可以降低难度和成本。在使用Lua的过程中,会经常访问全局变量来作为配置文件。
在访问全局变量时,可以通过局部变量引用全局变量来优化。当然,这样的优化毫无意义。
Locals Vs Globals from http://lua-users.org/wiki/LocalsVsGlobals
Comparison between local and global variables:
Implementation: Locals index an array of registers on the stack, with hard-coded integer index (at least in the standard implementation -- LuaImplementations).
Globals index from a table (or userdata), typically with variable name string, stored as constant or variable, as the key.
实现:在Lua标准实现中,使用hard-code 整数索引在 registers on the stack 上索引局部变量。
在table或者userdata中,通过string常量或者string变量作为键来索引全局变量。
Performance: The above point implies that locals can be a bit faster
Still, table indexing is a fairly efficient operation in Lua (e.g. strings are interned with precomputed hash), so this point can often be ignored unless profiling indicates optimization is needed.
性能:通过实现不同,局部变量稍微比全局变量速度快。但是,在lua table中通过string来索引也是相当快。因为字符串在lua中被内化,事先计算过hash值。
所以,除非在剖析优化性能之外,性能问题可以被忽略。
Syntax: If an environment table is set, globals can be accessed in Lua code with or without explicitly naming the environment table they come from: foo, _G.foo, or getfenv().foo (or in 5.2.0work3, _ENV.foo).
This allows different styles of environment usage, such as in ModuleDefinition.
语法:如果环境table是一个集合,在环境table之外可以通过foo,_G.foo 或者getfenv().foo来获取到全局变量。