I could use some help with if/else statements and Mata declarations: I have a situation where my first inclination was to do something like this:
But when I do this I get the error "symbol x multiply defined". I am pretty sure this is something that is simply not allowed in Mata. But I'm not sure what the reason is, or how I would so something like this that is allowed.
In practice, I'm doing something a little more complicated, along the lines of
This gives the same error message as before.
I thought about using pointers as a workaround, as in the following example. You can see that the new() functions for both C1 and C2 are executed -- when the code is compiled -- even though I have these if/else statements in the code.
However, I can't figure out how to use this pointers approach (beyond using it to reveal when the new() functions are run) although maybe the it could work somehow. I have two concerns. First, I can't figure out the syntax for reading or writing members of a class instance when using the pointer. For example, all these things I tried inside test2() produced error messages:
The second concern is that the pointers approach would still run both new() functions instead of just running the one that is needed. That's not a problem for me, but it could be costly (computationally) if the new() function does something non-trivial.
Any help or tips would be much appreciated. Thanks!
- Keith
Code:
if (something) real scalar x else real matrix x
In practice, I'm doing something a little more complicated, along the lines of
Code:
class myclass1 { void new() real scalar x } class myclass2 extends myclass1 { void new() real scalar x } void myclass1::new() { "hello from 1" } void myclass2::new() { "hello from 2" } void testA() { if (0) class myclass1 scalar C else class myclass2 scalar C } testA()
I thought about using pointers as a workaround, as in the following example. You can see that the new() functions for both C1 and C2 are executed -- when the code is compiled -- even though I have these if/else statements in the code.
Code:
: void test2() { > "start" > if (0) class myclass1 scalar C1 > else class myclass2 scalar C2 > pointer C > "declarations done" > if (0) C = &C1 > else C = &C2 > "end" > } note: variable C set but not used : test2() hello from 1 hello from 1 hello from 2 start declarations done end
Code:
*C.x = 2 (*C).x = 2 *C->x = 2 C->x = 2
Any help or tips would be much appreciated. Thanks!
- Keith
Comment