backtrace()[-2]->fun gives you the calling function. function_object(backtrace()[-2]->fun); gives you the calling object.
There once were a shortcut for that last expression called "previous_object". I wonder what happened with it?
void some_func() { write("Called from: %O, %O\n", backtrace()[-2]->fun, function_object(backtrace()[-2]->fun)); }
But! Note that Pike optimizes tail-recursion. So you need to either turn it off (how, I forgot) or to avoid it. It means that unneeded stack frames aren't stored, so you can for instance do
int fak(int n,void|int c) { return n<2?(c||1):fak(n-1,n*(c||1)); }
without getting n stack entries.
(In your example, it doesn't seem like the tail recursion optimizer gets a hit. I wonder why, shouldn't it optimize that?)
/ Mirar
Previous text:
2003-02-05 05:32: Subject: Any way to access the calling object?
Hi everyone,
Is there any way to find out which object [instance] is calling some function?
I expected that this_object() will do the work, but regardless of the caller it always returns module where it is written.
Actually, what I need is to get exact reference to the instance of the object which calls my function (if there is an instance).
backtrace() won't work - I'll get the function name and location in the file, but no reference to calling object...
Or, to summarize:
--- snip otest.pike ---
class A { void method() { some_func(); } }
some_func() { write(sprintf("Called from: %O", caller())); }
int main() { A a = A();
some_func(); // Should print "Called from: otest()" a->some_func(); // Should print "Called from: A()" and (caller() == a) will be true }
--- snip otest.pike ---
Regards, /Al
/ Brevbäraren