Lesson 10 of 10

Scope and local

Goal

The local keyword, shadowing and recursion

01

Explanation

Every variable you define without local is global: it's stored in the _G table, and any code running in the same environment can see it. All World of Warcraft add-ons share a single global table, so a global total in your add-on can wipe out a total in another one. A local variable, on the other hand, lives from the line that defines it to the end of the block it's in, and it's faster to access.

If you write local inside a block with a name that already exists, you're creating a new variable that hides the outer one without changing it. This is called shadowing: local score = score + 10 inside a function reads the outer variable and writes to a new copy that disappears at end. To change the outer variable, assign to it without local.

A function that calls itself needs its own name to be known inside it. In local f = function() ... f() ... end, the local f doesn't exist until the whole statement is finished, so the inner call looks for a global f and finds nil. local function f(), by contrast, declares the name first and then puts the function in it, so the function can see itself from the inside.

02

Your task

The code has three scope bugs. Fix them: make addKill add 10 to the outer score, make chainDamage call itself while staying local, and make endRound return the points and reset them without leaving total behind as a global variable.

Checks

5 checks
  1. addKill increases the outer score by 10
  2. chainDamage calls itself and gives 187 for three jumps
  3. endRound returns the points and resets them
  4. total doesn't stay global
  5. The functions are local and none of them is in _G
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.