Project 11>Strings-- calling string constructor

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Project 11>Strings-- calling string constructor

kraftwerk1611
Hi,

I have a question about the right way to call String.new() constructor.

The book says on page 235 that it should be like String.new(length).
Does it translate to following vm code

push length
call String.new 1

And does '1' above represent the 'this' ?
Thanks.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Project 11>Strings-- calling string constructor

cadet1620
Administrator
kraftwerk1611 wrote
I have a question about the right way to call String.new() constructor.

The book says on page 235 that it should be like String.new(length).
Does it translate to following vm code

push length
call String.new 1

And does '1' above represent the 'this' ?
There is no 'this' involved in the call to a constructor.  The '1' is the number of parameters

Creating the string constant is the same as creating any other String object.
do Output.printString("abc");
is functionally equivalent to
let str = String.new(3);
do str.appendChar(97);
do str.appendChar(98);
do str.appendChar(99);
do Output.printString(str);
The confusing bit is that because the compiler requires that appendChar() return the String that was passed to it, the compiler can shortcut popping the return value and pushing 'str' for the next call when it is creating a String constant.
                            // stack after command
push 3                      // 3
call String.new 1           // str
push 97                     // 97   str
call String.append 1        // str
push 98                     // 98   str
call String.append 1        // str
push 99                     // 99   str
call String.append 1        // str
call Output.printString 1

--Mark
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Project 11>Strings-- calling string constructor

kraftwerk1611
Thank you for this explaining it.
Loading...