On 9/13/12 4:40 PM,
program...@gmail.com wrote:
> I am trying to implement an Array word that makes arrays. The problem I am having is trying to make do some bounds checking. I don't want an array to access memory that doesn't belong to it, so I need this feature.
>
> Here is my implementation so far. I'm having a problem keeping track of the size of the array in an Array instance. Maybe someone could tell me how to fix this implementation?
>
I posted a similar definition as an example just recently.
>
> : ARRAY ( cellCount - )
>
> \ Check if cellCount is greater than zero
Why? Just on general principles? Unless you seriously think someone is
going to do such a dumb thing, it's wasted code.
> dup dup ( cellCount cellCount cellCount )
Don't do two DUPs here, because...
> 1 < IF ( cellCount cellCount )
> CR ." Please specify an array size greater than zero." CR
> drop drop ( )
...it makes you do two DROPs here. If you needed to do two DROPs, you
could always say 2DROP, ut even that is unnecessary.
> abort
ABORT is a really useless error response. ABORT" at least lets you issue
an error message. THROW is even better.
> THEN
>
> \ Compile-time behavior
> CREATE CELLS ALLOT ( cellCount ) \ Creates and initializes the instance
> , \ store cellCount ( )
This is where you needed the second copy of the length. It's always
better from a readability perspective to do your DUP where you need it,
which would be before the CELLS ALLOT.
>
> \ Run-time behavior
> DOES> ( index address )
>
> @ \ retrieves cellcount ( index cellCount )
> swap ( cellCount index )
>
> \ lower limit check
> dup ( cellCount index index )
> 0 < IF ( cellCount index )
> CR ." Please specify an index that is greater than zero." CR
> drop \ Removes the address of the array instance
> -1 throw \ Stop normal execution after error
You could really combine the message with the THROW by specifying a
meaningful THROW code that would trigger a message at the CATCH level.
And, again, what is the likelihood that you will get a negative index?
If your calling code is well-vetted, the likelihood is zero, so this is
a wasted check.
> THEN
>
> \ upper limit check
> < IF ( cellCount index -- )
> CR ." Index out of bounds!"
> abort
> THEN
You have a stack underflow, I think. Try OVER instead of the SWAP DUP
above, with a DUP here.
What's on your stack now? You haven't tested this, have you?
>
> SWAP CELLS + \ Calculates address to return
> ; immediate
>
Why should this be IMMEDIATE? You would never want to execute this in
compile mode.
Cheers,
Elizabeth
--
==================================================
Elizabeth D. Rather (US & Canada) 800-55-FORTH
FORTH Inc.
+1 310.999.6784
5959 West Century Blvd. Suite 700
Los Angeles, CA 90045
http://www.forth.com
"Forth-based products and Services for real-time
applications since 1973."
==================================================