0

Is it possible to convert a key in object? I would like to simplify this code:

This works:

for key, data in pairs(DBButtonOptions[self.value]) do
    if key == "widgetframe1" then
        widgetframe1:SetText(data)
        widgetframe1:SetDisabled(enable)
    elseif key == "widgetframe2" then
        widgetframe2:SetText(data)
        widgetframe2:SetDisabled(enable)
    elseif key == "widgetframe3" then
        widgetframe3:SetText(data)
        widgetframe3:SetDisabled(enable)
    elseif key == "widgetframe4" then
        widgetframe4:SetText(data)
        widgetframe4:SetDisabled(enable)
    elseif key == "widgetframe5" then
        widgetframe5:SetText(data)
        widgetframe5:SetDisabled(enable)
    end
end

This does not work:

for key, data in pairs(DBButtonOptions[self.value]) do
    key:SetText(data)
    key:SetDisabled(enable)
end

This works but error (Attempt to index local key):

for key, data in pairs(DBButtonOptions[self.value]) do local key = _G[key] key:SetText(data) key:SetDisabled(enable) end

2
  • fixed <code> local widgetframe1 </code> replaced by <code>widgetframe1</code> now error fixed Commented May 28, 2018 at 20:18
  • 1
    can you try using a different name for your local variable and use the last one, i.e. local control = _G[key]? Also what do you mean by it works but you get an error? Is it possible there is a key that isn't a control with SetText and SetDisabled functions? Commented May 28, 2018 at 22:26

1 Answer 1

0

The problem seems to take key like local variable. check this post

I tried this snippet and it works fine

storeFn = _G
storeFn.Gn = {} -- limit iteration of loop "for" and don't get errors
storeFn.Gn.first = function(val) print("test first! "..val) end
storeFn.Gn.second= function(val) print("test second! "..val) end

for k, v in pairs(storeFn.Gn) do
     print( assert (loadstring('return '..'storeFn.Gn.'..k..'(...)')) (math.random()) )
end

Only have be careful with memory leaks

storeFn.Gn = nil
for k,_ in pairs(storeFn) do print(k) end -- restart to original _G

Also can use _G.Fn={} and after destroy it _G.Fn=nil

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.