Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes between Version 3 and Version 4 of API/Part1

Show
Ignore:
Author:
JarrettBillingsley (IP: 65.117.184.122)
Timestamp:
08/02/07 13:35:47 (17 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • API/Part1

    v3 v4  
    226226 
    227227Here we define a "calculate" function which takes an operation function and two operands.  It calls the operation with the two operands, expects one result, and returns that result.  easyCall makes this very straightforward.  The parameters to it are, in order: the object to call, the number of return values we want, the context pointer to call it with, and then a variadic list of arguments.  We expect exactly one result, and since it's already on the stack when easyCall returns, we can just return 1 and that value will become the return value of calculate.  This program will output "9" and "20" when run. 
     228 
     229The 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 
     233void 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 
     252int 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 
     262callMethod 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.