12.07.2015 Views

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

64 Part I ■ Learning to Program-- Create a counter that cannot be accessed outside this scopelocal counter = 0-- Global functions to interact with counterfunction counter_get()return counterendfunction counter_inc()counter = counter + 1endendThis block <strong>of</strong> code makes a simple, one-way counter that can’t be decremented,but can be retrieved <strong>and</strong> incremented via the counter_get() <strong>and</strong>counter_inc() functions. Explore this by running the following in yourinterpreter:> print(counter_get())0> counter_inc()> counter_inc()> print(counter_get())2> counter = counter - 1stdin:1: attempt to per<strong>for</strong>m arithmetic on global 'counter' (a nil value)stack traceback:stdin:1: in main chunk[C]: ?You can see that the counter variable is not accessible outside <strong>of</strong> the createdscope <strong>and</strong> thus can’t be altered without calling the provided functions. Thiscode implements a single counter when, in fact, you might need more thanone. Because these functions are tied to a specific counter variable, they arevery limited.Using Tables as Simple ObjectsThe following is a different implementation <strong>for</strong> the simple counter, making thecounteranobjectwithtwomethods,get <strong>and</strong> inc. Unlike the first example, thecounter can be altered directly without calling the functions. Run the followingcode in your interpreter:counter = {count = 0}function counter.get(self)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!