Hit and Freeze
```lua -- You are trapped. Dont move, it ll be painful. -- Attack ogres only when they re within reach.
– This function checks if the enemy is in your attack range.
– The function returns a boolean value: true or false
local inAttackRange = function(enemy)
local distance = hero:distanceTo(enemy)
– Almost all swords have attack range of 3.
if distance <= 3 then
return true
else
return false
end
end
while true do
– Find the nearest enemy and store it in a variable.
-- Call inAttackRange(enemy), with the enemy as the argument
-- and save the result in the variable canAttack.
-- If the result stored in canAttack is true, then attack!
end
<hr>
Introduction:
You're caught in a trap!
Wait until the ogres are close, then attack, or you'll injure yourself!
Functions can return a value, including a `boolean` value (true or false).
Use this to decide if an ogre is `inAttackRange()`!
```lua
local inAttackRange = function(enemy)
local distance = hero:distanceTo(enemy)
if distance <= 3 then
-- return True because the enemy is in range
else
-- return False because the enemy is out of range
end
end
Save the result to a variable to use it later in the code:
local canAttack = inAttackRange(target)
Overview:
You can have several return
statements in a function, but only one will be used, because return
causes the function to stop executing, and “returns” back to where the function was called.
local moreThanTen = function(n)
-- if 'n' greater than 10, then the function will return true.
if n > 10 then
return true
-- Otherwise 'return' inside 'else' will be called and the function will return false.
else
return false
end
end
local isSmall = moreThanTen(5) -- isSmall == true