Checking Bounds in Forth | |
---|---|
Forth is a little different, compared with the usual suspects that are JAVA, C, Shellscripts and even PHP. It's stack-oriented! The code for simple bounds-checking: : check-range ( u lower upper -- ) That's it! It would be called like 1 0 2 check-range and return -1, if in bounds, 0 otherwise. |
Exceptions in Forth | |
---|---|
Exceptions in Forth are a purist's dream. if you call 'throw' with 0 on top of stack, nothing happens. if you call it with a number, an exception is thrown. my exception would be -24: invalid numeric argument, if out of bounds. in code: -24 throw |
Checking Bounds in Forth with Exceptions | |
---|---|
So, now we need to combine those two ideas of bounds checking and exceptions. it's kind of very easy! the magic behind it happens via the and-instruction. but let's have a look at the definition first: : check-range ( u lower upper -- ) We know about the within, we know the throw part. But what about the rest? 0= 'inverts' a logical value on the stack. if the value is 0, it's replaced by -1. if it isn't, it's replaced by 0. Now, remember the and-instruction. -1 has all bits set, thus something and -1 is something. 0 has no bit set, thus something and 0 is 0. Put together: if(in bounds) throw(0) else throw (-24); |
Comments - Make a comment |
The comments are owned by the poster. We are not responsible for its content. |
AdministrativeTexts
updated by freddiemac1993, 2013-06-14
wiki
Re: adventures
created by brittdavis10, 2012-02-23 (1 rply, 3 views)
thread
Re: how to run phpwebsite...
created by alexander, 2011-08-25 (2 rpls, 3607 views)
thread
Re: Forum tags
created by HaroldFaragher, 2011-08-22 (3 rpls, 8488 views)
thread