| 228 | |
---|
| 229 | The last thing I should show you is how to call methods. Method lookup is a bit tricky, so it's usually not something that you want to do on your own. So MDState provides the callMethod function which takes an object and a method name to call. |
---|
| 230 | |
---|
| 231 | {{{ |
---|
| 232 | #!d |
---|
| 233 | void main() |
---|
| 234 | { |
---|
| 235 | MDContext ctx = NewContext(); |
---|
| 236 | ctx.globals["callSomething"d] = ctx.newClosure(&callSomething, "callSomething"); |
---|
| 237 | loadStatementString(ctx.mainThread, |
---|
| 238 | `class A |
---|
| 239 | { |
---|
| 240 | function foo(x, y) |
---|
| 241 | { |
---|
| 242 | writefln("A.foo ", x, ", ", y); |
---|
| 243 | } |
---|
| 244 | } |
---|
| 245 | |
---|
| 246 | local a = A(); |
---|
| 247 | callSomething(a, "foo"); |
---|
| 248 | ` |
---|
| 249 | ); |
---|
| 250 | } |
---|
| 251 | |
---|
| 252 | int callSomething(MDState s, uint numParams) |
---|
| 253 | { |
---|
| 254 | auto context = s.getParam(0u); |
---|
| 255 | auto cl = s.getParam!(MDString)(1); |
---|
| 256 | |
---|
| 257 | s.callMethod(context, cl, 0, 5, 10); |
---|
| 258 | return 0; |
---|
| 259 | } |
---|
| 260 | }}} |
---|
| 261 | |
---|
| 262 | callMethod is very straightforward. It takes the object to call the method on (which will also be used as the 'this' pointer of course), the name of the method to call, the number of returns, and then a list of parameters. This code will display "A.foo 5, 10" when run. |