Reputation: 416
I was recently trying to write event callback handlers for my UI system, and I've been having trouble accessing higher-scope variables from a procedurally generated global function.
Here's some sample code to re-create the problem:
gameInstance = {}
gameInstance.State = {}
gameInstance.State.GetPlayerCountry = function()
local country = {}
country.GetInterestGroups = function()
local iglist = {}
iglist[1] = "ig1";
iglist[2] = "ig2";
iglist[3] = "ig3";
return iglist;
end;
return country;
end;
gameState = gameInstance.State;
playerCountry = gameState.GetPlayerCountry();
interestGroups = playerCountry.GetInterestGroups();
for i in ipairs(interestGroups) do
local elementID = 'Slider' .. i;
local onClickCallbackID = elementID .. 'Callback';
print(onClickCallbackID);
--layout.CreateElementFromTemplate('slider_template', parentElementID);
--layout.SetOnClickCallback(elementID, onClickCallbackID);
_G[onClickCallbackID] = function()
--local layout = layoutController.xmlLayoutProxy;
print('Testing a dynamic callback ' .. elementID);
end;
Slider1Callback();
end;
This produces the following output (quite unexpectedly):
As you can see, my elementID variable isn't being correctly read by my procedural callbacks. This is a problem because my UI framework heavily relies on ids, and the callback system isn't designed to give a callback function the id of the element it is serving as a callback for (it's expected that the function/coder who writes the function knows or has a way of looking it up), and a re-design would be painful, as I'd have to dig into old unmaintained messy C# Unity code written by somebody else that heavily uses reflection, - I'd basically have to re-write the entire event handling portion of the UI library I am using, altering dozenz of classes.
Why is this happening? Is there any way to fix this.
Upvotes: 0
Views: 39