LuaFix2 - Example - elseifs

Go back to Luafix2


Consider the following code:

local n = math.random() if n > .25 and n < .5 then print(n - .25) print("in middle") elseif n >= .5 and n < .75 then print(n + .25) print("in middle") end

The print("in middle") is the same in two places; if I wanted to change it, I would have to change it in several places. If I was replacing it with a loop, then I would have a loop twice.

This means we should pull this code to after the if so that the same one is used by both. A simple if has to be added to make it only happen when one of the previous branches happened. It is easy to do this in this case:

local n = math.random() if n > .25 and n < .5 then print(n - .25) elseif n >= .5 and n < .75 then print(n + .25) end if n > .25 and n < .75 then print("in middle") end

Let's say we're making a simple game and there are several materials: Stone, Grass, Glass, and Dirt — there are no other materials. Thus the following does not require an else clause.

if material == "Stone" then getStone(); wait(1) print("You got Stone") elseif material == "Grass" then getGrass(); wait(1) print("You got Grass") elseif material == "Glass" then getGlass(); wait(1) print("You got Glass") elseif material == "Dirt" then getDirt(); wait(1) print("You got Dirt") end

In this case, we know we are always going to get that message printed. The last statement is a little different each time. Let's change it a little.

The following does the same thing:

if material == "Stone" then getStone() wait(1) print("You got " .. material) -- Stone elseif material == "Grass" then getGrass() wait(1) print("You got " .. material) -- Grass elseif material == "Glass" then getGlass() wait(1) print("You got " .. material) -- Glass elseif material == "Dirt" then getDirt() wait(1) print("You got " .. material) -- Dirt end

Now each line ends with the same thing. We know that at least one will happen, so we can just move the print("You got " .. material) after the if:

if material == "Stone" then getStone() elseif material == "Grass" then getGrass() elseif material == "Glass" then getGlass() elseif material == "Dirt" then getDirt() end wait(1) print("You got " .. material) -- Whatever
You could probably take this further and reduce the likely reuse between the getStone(), getGrass(), etc.