lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Nick Davies:
> Now, I hear that making global variables local results in a good speed
> increase.

In my Lua 4 projects there is definitely a speed increase, but nothing
really spectacular.  But as it is so little trouble to change it I'd say
it's worth it.  In Lua 4 you just prefix the globals with a %-sign to turn
them into upvalues.  For Lua 5 you can do it as you suggested (define them
as locals) and they will automatically become upvalues by lexical scoping.
Just remember that replacing Video, Audio, ... with other tables later on
will now have no effect because each function will hold on to the original
table when the script loads.  But I guess this is not an issue here.

David Holz:
> I'd guess that a global like "Audio.PlayTrack" from within a function
would
> require 3 table lookups, one to hit the local scope (which would usually
be
> empty and therefore probably a negligible speed hit), then the global
scope
> (which would find "Audio"), then search "Audio" for "PlayTrack".

I don't know about older versions of Lua but in Lua 4 up this takes only two
lookups.  The compiler will already have figured out that Audio refers to a
global.  (Locals are not stored in a table,  they reside on the stack and
are referred to by an index.)  Which reminds me: if you use the same table
(or global) value more than once then it is also a good idea to turn it into
a local first.  Example:

    if table.message then print(table.message) end

vs.

    local message = table.message
    if message then print(message) end

Bye,
Wim