musictheory / NilScript

Objective-C-style language superset of JavaScript with a tiny, simple runtime
Other
50 stars 5 forks source link

Calling dynamic methods? #92

Closed IngwiePhoenix closed 8 years ago

IngwiePhoenix commented 8 years ago

One can check for a method to exist like so:

if([inst respondsToSelector:@selector(init)]) {
    // ...
}

But is there a way to run a method dynamically?

var method = "doSomething";
if([instance respondsToSelector:@selector(method)]) {
    [instance performBySelector:@selector(method)];
}

I see that ojc turns selectors into pseudo objects, for instance

if($oj_oj.msgSend($oj_oj._cls.$oj_c_Derp,{ respondsToSelector_: 1 },{ init: 1 })) {
    $oj_oj.msgSend($oj_oj._cls.$oj_c_Derp,{ init: 1 });
}

where { respondsToSelector_: 1 } is some kind of selector - at least, that much I understand.

So is it actually possible to call methods dynamically?

iccir commented 8 years ago

Same as Obj-C ;)

if ([foo respondsToSelector:@selector(doActionWithString:)]) {
    [foo performSelector:@selector(doActionWithString:) withObject:"Foo"];
}
iccir commented 8 years ago

performSelector: performSelector:withObject: performSelector:withObject:withObject:

IngwiePhoenix commented 8 years ago

Ohh, okay. I didn't see any public methods on oj regarding performSelector :). Thanks for the heads-up.

I also tested to see if variable strings work. method is treated as the selector constant - disregarding the value it actually holds. So much for that. Again, thanks! :)

iccir commented 8 years ago

https://github.com/musictheory/oj#base-class ;)