View Single Post
08-08-15, 05:57 PM   #1
Nimhfree
A Frostmaul Preserver
AddOn Author - Click to view addons
Join Date: Aug 2006
Posts: 267
Issue with variable scope

Hi, I have a problem that someone can probably explain to me pretty easily, but my head is a little fuzzy at the moment from lack of sleep.

In the following code I have a variable followerName declared outside of the for loop. I insert a new table into t with a function f defined to pass in followerName to the call to SetMapAreaQuests. What happens is whenever that function f is called, the value that is passed in for followerName is always the last one that was in the Grail.followerMapping as it passed through the for loop.

Code:
local followerInfo, followerName, qualityLevel
for questId, followerId in pairs(Grail.followerMapping) do
	if Grail:MeetsRequirementFaction(questId) then
		followerInfo = C_Garrison.GetFollowerInfo(followerId)
		followerName = followerInfo.name
		qualityLevel = followerInfo.quality
		tinsert(t, { sortName = followerName, displayName = ITEM_QUALITY_COLORS[qualityLevel].hex..followerName.."|r", mapID = 0, f = function() Grail:SetMapAreaQuests(0, followerName, { questId }) Wholly.zoneInfo.panel.mapId = 0 Wholly._ForcePanelMapArea(Wholly, true) CloseDropDownMenus() end })
	end
end
A fix that seems to work properly is to change the scope of the followerName variable such that is is defined within the loop itself as the following code shows:

Code:
local followerInfo, qualityLevel
for questId, followerId in pairs(Grail.followerMapping) do
	if Grail:MeetsRequirementFaction(questId) then
		followerInfo = C_Garrison.GetFollowerInfo(followerId)
		local followerName = followerInfo.name
		qualityLevel = followerInfo.quality
		tinsert(t, { sortName = followerName, displayName = ITEM_QUALITY_COLORS[qualityLevel].hex..followerName.."|r", mapID = 0, f = function() Grail:SetMapAreaQuests(0, followerName, { questId }) Wholly.zoneInfo.panel.mapId = 0 Wholly._ForcePanelMapArea(Wholly, true) CloseDropDownMenus() end })
	end
end
Can someone enlighten me as to why this is the case?
  Reply With Quote