Lua - Retrieving button's name from event header

To cut right to the chase, I have these two snippets of Lua code. One of which generates three buttons to put in a menu window:

for i=1,3,1 do
	local button = Button:new()
	button.minHeight = 24 = i
	local buttonText = Text:new()
	buttonText.text = "Stage "..i
	buttonText:SetAlignment(HA_CENTER, VA_CENTER)
	SubscribeToEvent(button, "Released", "LoadStage")

and later on I have that event:

function LoadStage(object, eventType, eventData)
	log:Write(LOG_INFO, "Loaded stage "

In theory, this should result in the log mentioning β€œLoaded stage 1”, β€œLoaded stage 2” and β€œLoaded stage 3” when I press the appropiate button. However, it doesn’t work properly and pressing the buttons results in an β€œExecute Lua function failed: [string β€œinit”]:61: attempt to concatenate field β€˜name’ (a nil value)” error in the log. Any help?

An event handler has the signature of HandleThingy(eventType, eventData) so in your example, LoadStage is being passed a StringHash, then a VariantMap, and finally the one you call eventData is passed as nil. Inside, you are essentially trying to concatentate a field that resolves to StringHash::name, which there is no such thing.

In order to get the object sending the event, inside LoadStage you need to do something like:

function LoadStage(eventType, eventData) local e=eventData["Element"]:GetPtr("UIElement") local name=e:GetName() log:Write(LOG_INFO, "Loaded stage " end

This will obtain the name of the UIElement sending the event.

1 Like

Ah, I had misunderstood a few things then. Your solution works and also thanks for the explanation.