Michael Marshall
Michael Marshall

Reputation: 29

WoW Addon (Lua) Variables and methods

I've been messing with this for hours and I can't seem to get this to work

for i=1, 10 do
 local frame = "MyFrame"..i

 frame:EnableMouseWheel(true)
end

and the error I get is

attempt to call method 'EnableMouseWheel' (a nil value)

but if I do

MyFrame1:EnableMouseWheel(true)

there's no problem what so ever and it works

is there anyway to use a variable as a frame name for the method?

Upvotes: 0

Views: 1723

Answers (2)

Eric
Eric

Reputation: 97631

This will work:

local vars = getfenv()
for i=1, 10 do
    local frame = "MyFrame"..i

    vars[frame]:EnableMouseWheel(true)
end

Although you appear to be looking for the solution to the wrong problem. Why not store them in an array to begin with?

Upvotes: 1

hugomg
hugomg

Reputation: 69944

If you want to convert a string name into a variable name you need to access the global object as a table:

_G["MyFrame1"]

I don't know about what version of Lua warcraft uses. If its a really old version that doesn't have _G then you probably need to use the getglobal functions instead

getglobal("MyFrame1")

That said, this is usually an antipattern. If you are the one that originally defined the MyFrame variables its normally better to use an array instead:

Myframes = {
   MyFrame1,
   MyFrame2,
}

since this lets you avoid the string manipulation

local frame = MyFrames[i]
frame:EnableMouseWheel(true)

Upvotes: 0

Related Questions