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.

Chapter 4 ■ Working with Tables 71The metamethod correctly h<strong>and</strong>les the addition <strong>and</strong> creates a new tablewith the results <strong>of</strong> the addition. The other basic arithmetic operations couldbe defined in the same way. Instead <strong>of</strong> returning a table, these functions couldreturn some meaningful number that can be used as part <strong>of</strong> a larger <strong>for</strong>mula.Defining Negation Using ___unmThe unary minus (negation) operator, __unm, expects exactly one argument,<strong>and</strong> should return the result <strong>of</strong> the argument being negated. In these examples,this will mean reversing the array part <strong>of</strong> the given table. Run the followingcode:function mt.___unm(a)local result = setmetatable({}, mt)-- Reverse through the elements <strong>of</strong> the array<strong>for</strong> i = #a, 1,-1 dotable.insert(result, a[i])endreturn resultendTest table negation with a few examples:> unm_test = -tbl1> <strong>for</strong> i = 1, #unm_test do print(i, unm_test[i]) end1 gamma2 beta3 alpha> unm_test = -tbl1 + tbl2> <strong>for</strong> i = 1, #unm_test do print(i, unm_test[i]) end1 gamma2 beta3 alpha4 delta5 epsilon6 zeta<strong>Creating</strong> Meaningful Output with ___tostringIn the current example, it would be useful to print the table <strong>and</strong> have it displaythe elements rather than the unique string Lua provides. You can accomplishthat using the ___tostring metamethod, which takes a single argument (thetable) <strong>and</strong> should return a string.Run the following code:function mt.___tostring(tbl)local result = “{“<strong>for</strong> i = 1, #tbl do

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

Saved successfully!

Ooh no, something went wrong!