I have some generic functions that I’m placing into various classes and tables at runtime. It would be very handy if these functions could have access to the name of their parent class/table. I haven’t had any luck getting getinfos() to work. Is there any way to use it or to reference “this” to get the name?
Looks like getinfos() isn’t implemented - I’ll a ticket to our system to look at having it implemented.
Reflection can be a pretty powerful tool, and I imagine there will be some people who use it in interesting ways!
It looks like you can use the instanceof operator:
if (this instanceof :: ClassName) { // do some stuff } else if (this instanceof :: ClassName2) { // do some other stuff } // ...
I don’t think instanceof will work for me. The classes/tables I’m using are dynamic and I won’t necessarily know the name of them at coding time. In the meantime, I have a workaround, but it’s not so pretty.
It actually doesn’t look like getinfos() is what you want either…
getinfos() returns information about the function, not the class (and classes don’t have an equivalent method).
Can you go into any more detail about what you’re trying to do?
Actually, just had an idea - if you implement the _typeof metamethod, you can make this work in a fairly elegant way:
`class Test {
constructor() {
}
function genericFunctionInLotsOfClasses() {
server.log("This is an instance of " + typeof(this));
}
// _typeof is a metamethod that will be called when we call
// typeof(x) if x is an instance of Test
function _typeof() {
return "Test";
}
}
test <- Test();
server.log(typeof(test));
test.genericFunctionInLotsOfClasses();`
Yes, that’s pretty much exactly how I’m doing it now. I realise now that finding an instance name for the class is probably not possible (doesn’t seem to be available in Java either). So, I’m taking a different tack.
Tables don’t have names in Squirrel:
local t = { foo=bar ... }; local u = t; // now u and t are the same table -- which one is its "name"?
What’s maybe not obvious to those coming from C++ backgrounds, is that classes don’t have names either:
class Foo {...}
is just shorthand for:
Foo <- class {...}
and Foo is just a normal variable, currently with an object of type “class” assigned to it, but it can be reassigned:
`class Foo {
function fnord() { server.log(“fnord”); }
};
local Bar = Foo;
Foo = 3;
local f = Bar();
f.fnord();
`
So yes, either _typeof() or some other function name of your own convention, is the only way to do it.
Peter