PDA

View Full Version : Can't use getCTFromToken from inside onAdd



bmos
August 26th, 2021, 17:40
I'm having an issue using Token.onAdd as a way of triggering an event whenever a token is dragged onto the map.
I use this exact method with Token.onMove and it works great. Any suggestions how I can make this work?

It debugs as nil when dragging token to the map. I have checked for token.getContainerNode() and token.getId() and they both return values, so I think the issue is with CombatManager.getCTFromTokenRef not being able to find the token on that map using its id.


local onAdd = nil;
local function auraOnAdd(tokenInstance)
if onAdd then
onAdd(tokenInstance);
end
if Session.IsHost then
Debug.chat(CombatManager.getCTFromToken(tokenInsta nce))
end
end

function onInit()
onAdd = Token.onAdd
Token.onAdd = auraOnAdd
end

Moon Wizard
August 26th, 2021, 17:58
First, you can't capture "handlers" like you can with global scripts. Token.onAdd isn't a function, but a mechanism to register a handler function that gets stored in an internal table and called with all the other handler functions. So, you can't intercept other registered handlers, only work alongside them (or replace the scripts that register them). Handlers are used for objects that are instanced without having native script spaces (i.e. tokens and databasenodes).

Second, the onAdd event may be getting called at a point in the process when not everything is registered in the CombatManager script yet. (i.e. your onAdd could be getting called before the CombatManager onTokenAdd (see above)).

Regards,
JPG

bmos
August 26th, 2021, 18:26
Thanks for the reply JPG

bmos
August 26th, 2021, 19:01
I confused though, because it feels like this contradicts some prior advice you gave me. Am I misunderstanding something?

You should only be adding handlers directly to a token in a Token.onAdd event; or just capturing Token.onMove directly.

Moon Wizard
August 26th, 2021, 19:25
I don’t remember the context of that answer specifically. You can still hook into the onAdd event; but you can’t assume that other onAdd events are triggering before yours.

So, it could be more complex depending on what you are trying to do. Since the onAdd event triggers when the table is loaded, there can be some ordering considerations.

You’d have to look through the CM function you’re calling to see if it needs to be initialized before it can handle; or skip handling for the onAdd event before tabletop initialization complete and add a separate initialization when the tabletop initialization completes (onDesktopInit)

Regards,
JPG

JPG