WoW:Lua variable scoping: Difference between revisions

m
no edit summary
(BASIC variables were default-global :P)
mNo edit summary
Line 130: Line 130:


Block-local variables are especially useful as counters and other variables which will only be useful for a particularly small section of code. One extra advantage to doing this is an author can use extremely simple variable names such as "a," "n," or "key," which can then be reused several times within the same function, each time not conflicting with the other version of it. This greatly simplifies code without the need to make esoteric variable names.
Block-local variables are especially useful as counters and other variables which will only be useful for a particularly small section of code. One extra advantage to doing this is an author can use extremely simple variable names such as "a," "n," or "key," which can then be reused several times within the same function, each time not conflicting with the other version of it. This greatly simplifies code without the need to make esoteric variable names.
== Static Variables ==
The "static" keyword does not exist in Lua; therefore, it's not possible to create a static variable. Static variables are useful in that they are local to the function, but retain their value with subsequent calls to said function. You can simulate this functionality by encapsulating your function definition in a do...end block with the local variable declaration inside the do...end block and before the function definition. Like so:
<pre>do
    local myStaticFrame
    function(...)
        if not myStaticFrame then
            -- Don't create the frame until the function is called once and don't make it again.
            myStaticFrame = CreateFrame('Frame')
        end
        -- Do stuff to myStaticFrame
    end
end</pre>
This could be useful in OnUpdate scripts that must use a frame/table each time it's executed, which is horribly inefficient.


== Complex Scope ==
== Complex Scope ==
Anonymous user