• Civilization 7 has been announced. For more info please check the forum here .

[LUA]how to call a unit method defined in xml table

epicss

Warlord
Joined
Mar 10, 2012
Messages
188
I think I have see this before in this forum but can't find it now, I have a xml table that defines some callback function, that need to be called by a unit, like this:
Code:
local callback = GetTheFunctionNameFromTable(...);
unit:callback(...);
but that won't work, the error is:
Code:
HeroesUtils.lua:98: attempt to call method 'callback' (a nil value)
if I write it like this:
Code:
unit[callback](...);
there is an error too:
Code:
HeroesUtils.lua:98: Not a valid instance.  Either the instance is NULL or you used '.' instead of ':'.

I wonder if someone know how to do that?
my code piece here:
Spoiler :
Code:
		local modifier = GameInfo.AbilityModifiers[modi.YieldType];
		if modifier ~= nil and modifier.Callback ~= nil and unit ~= nil and unit[modifier.Callback] ~= nil then
			local callback = modifier.Callback;
			local change = modi.Yield;
			if isminus then
				change = -modi.Yield;
			end
			unit[callback]( change );
		end
 
Not exactly sure what you are trying to do; based on your code example, callback seems to be a string = the name of the unit method to use (also assuming unit is a pointer to a valid unit c++ object).
The method can be invoqued by unit[callback], but it needs to be passed self as the first of its parameters (in addition to its normal ones), because that is what the ":" column lua syntactic sugar operator normally does: unit[callback](unit, ...) where ... are the normal parameters (or nothing if it has none).
Cheers
 
Top Bottom