WoWInterface

WoWInterface (https://www.wowinterface.com/forums/index.php)
-   Lua/XML Help (https://www.wowinterface.com/forums/forumdisplay.php?f=16)
-   -   creating frames with for loops (https://www.wowinterface.com/forums/showthread.php?t=54888)

Tesser 12-03-16 01:58 PM

creating frames with for loops
 
I've made this generic because the actual loop is 50+ lines and I'm just wondering if I'm missing some basics here.
Everything is working except that when I go to print some information about the frame in the "mouseover" event (in this case just "i"), it always prints the information from the last frame created in the loop.
It seems like the logic should have it printing information to it's particular frame, no?

So in this case, say there were 5 table entries - hovering over any of the 5 frames created would print "5".

Code:

for i=1, #table, 1 do
        frames[i]=CreateFrame()
        frames[i]:SetPoint('CENTER', UI, 'CENTER' x, y)
        frames[i]:SetScript("OnEnter", function()
                        print(i)
                end)
        frames[i]:SetScript("OnLeave", function() end)
end


Clamsoda 12-03-16 03:06 PM

Post your actual function, or if it is too long, the file.

Banknorris 12-03-16 04:29 PM

Lua Code:
  1. for i=1, #table, 1 do
  2.     frames[i]=CreateFrame()
  3.     frames[i].i=i
  4.     frames[i]:SetPoint('CENTER', UI, 'CENTER' x, y)
  5.     frames[i]:SetScript("OnEnter", function(self)
  6.             print(self.i)
  7.         end)
  8.     frames[i]:SetScript("OnLeave", function() end)
  9. end

Kanegasi 12-03-16 05:01 PM

Quote:

Originally Posted by Banknorris (Post 321182)
Lua Code:
  1. for i=1, #table, 1 do
  2.     frames[i]=CreateFrame()
  3.     frames[i].i=i
  4.     frames[i]:SetPoint('CENTER', UI, 'CENTER' x, y)
  5.     frames[i]:SetScript("OnEnter", function()
  6.             print(self.i)
  7.         end)
  8.     frames[i]:SetScript("OnLeave", function() end)
  9. end


You forgot the self declaration.

Lua Code:
  1. frames[i]:SetScript("OnEnter", function(self)
  2.             print(self.i)
  3.         end)

SDPhantom 12-04-16 12:02 AM

The iteration variable in a for lop should be isolated between each iteration. I ran the following test as proof.

Lua Code:
  1. local t={};
  2. for i=1,5 do
  3.     t[i]=function() print(i); end
  4. end
  5. for _,f in ipairs(t) do f(); end

This prints the following output.
Code:

1
2
3
4
5



In conclusion, something in your code is contaminating the variable in your for loop. Without being able to look through all of your code, there's no way to tell what's going on exactly.


All times are GMT -6. The time now is 11:49 AM.

vBulletin © 2024, Jelsoft Enterprises Ltd
© 2004 - 2022 MMOUI