Game Development Community

How to tell if a function exists?

by Ken Pajala · in Torque Game Builder · 07/09/2006 (9:10 pm) · 5 replies

Given the following, how do I tell if %this.someFunction() exists before I try to call it?

function t2dSceneObject::testFunction (%this)
{
	%this.someFunction ();
}

In particular, I'm using someFunction() as a callback that may or may not exist, so I'm trying to avoid the error in the console log "Unknown command someFunction".

#1
07/09/2006 (9:17 pm)
I have no idea if this will work, but try this:
function t2dSceneObject::testFunction (%this)
{
	if(isObject(%this.someFunction)       
		%this.someFunction ();
}

If that doesn't work, set a flag named something like 'hasSomeFunction' to true in the classes you implement the function in, then just check that flag before you try to execute it.
#2
07/09/2006 (9:29 pm)
Thanks for the suggestion Brian. isObject() seems to always return false :(

Yeah, I will likely use some sort of flag if there's no way to test for it directly.
#3
07/10/2006 (1:23 am)
There are two possible calls; "isFunction()" and "isMethod()".

You should be able to use ...

if ( %this.isMethod( someObjectFunction ) ) echo("Object Function Exists!");

... on an object and ...

if ( isFunction( someGlobalFunction ) ) echo("Global Function Exists!");

Be careful of the "isFunction()" call though as it searches the StringTable as part of its search and so could possibly return a false positive.

Hope this helps,

- Melv.
#4
07/10/2006 (9:29 am)
Excellent! isMethod() works. I thought it didn't at first because I was calling:
if ( %this.isMethod( %this.someFunction ) ) echo("someFunction Exists!");
rather than
if ( %this.isMethod( someFunction ) ) echo("someFunction Exists!");

Also, isFunction() doesn't seem to be visible to scripts, as there's no console method defined.
#5
07/10/2006 (10:00 am)
Yes, sorry, I thought "isFunction()" was available. You could add it yourself though in a couple of lines though.

- Melv.