I am finding Lua's scoping rules a bit confusing. I have submitted below, a snippet of a Lua script to highlight the issues I want to ask question(s) about:
-- 'forward definitions'
-- could these be moved to the bottom of the script to 'tidy up' the script?
-- could these reside in another file imported by require 'filename' to tidy up the script even more?
[[ Note: This function is accessing variables defined later on/elsewhere in the script
and is also setting a variable (flag) which is then used elsewhere in the script
]]
function war_is_needed()
if (goodwill:extendsToAllMen() and peace) then
if player:isAppointedLeader() then
economy_is_booming = false
return true
else
economy_is_booming = nil
return true
end
else
economy_is_booming = nil
return false
end
end
world = WorldFactory:new('rock#3')
player = PlayerFactory:getUser('barney', world)
while (not player:isDead()) do
peace = world:hasPeace()
goodwill = world:getGoodwillInfo()
if war_is_needed() then
world:goToWar()
else
if (not economy_is_booming) then
player:setNervousState(true)
player:tryToStartAWar()
else
player:setNervousState(false)
player:liveFrivously()
end if
end
end
My questions are (Ignoring for now that global variables CAN be considered evil) :
- Could the function at the top of the script be moved to the bottom of the script to 'tidy up' the script?
- Could the function at the top of the script be refactored (i.e. moved) into a separate file 'warfuncs.lua' and then imported into the script by replacing the function definition with a require 'warfuncs.lua'?
Whilst answering the above two questions, please bear in mind that the function at the top of the script is accessing variables defined later on/elsewhere in the script and is also setting a variable (flag) which is then used elsewhere in the script.
Do the scoping rules change if Lua is embedded in C or C++ (where objects may be being created on the heap)?