Re: Tip march 10

new topic     » goto parent     » topic index » view thread      » older message » newer message

Lucius Lamar Hilley III writes:

> To designate valid values that you might change instead of
> coding each value directly to the if statements like
>
> if c = '8' then--use for up
> elsif c = '2' then--use for down
> elsif c = '4' then--use for left
> elsif c = '6' then --use for right
> end if
>
> SNIP
>
> found = find(c, s)
> --this will also speed the checking by making sure it
> --was valid/found first.
> if found then
>     --found tells where c was found.
>   if found = 1 then--use for up
>   elsif found = 2 then--use for down
>   elsif found = 3 then--use for left
>   elsif found = 4 then --use for right
>   end if
> end if

Um... you're kidding, right? It seems to me that replacing the hard coded
values (which at least have intrinsic meaning) with arbitrary index values
(which are therefore meaningless) is far less maintainable, and much more
prone to error.

You've simply replaced one type of hard-coded information (key codes) with
another (index position). If you added an item into that list of key codes
(other than at the tail), all your code *breaks*.

Wouldn't a more you want to use symbolic constants, such as:

   validKeys = { UP, DOWN, LEFT, RIGHT }
   if find( key, validKeys ) then
      if key = UP then--use for up
      elsif key = DOWN then--use for down
      elsif key = LEFT then--use for left
      elsif key = RIGHT then --use for right
   end if

If the range is large, and there are a lot of items, you can do what Robert
does in the syntax coloring code: set up a sequence the size of the range,
and fill it with values. For example:

   repeat validKeys( 0, 256 ) -- all values are initially false
   validKeys[UP] = 1          -- up is valid
   validKeys[DOWN] = 1        -- down is valid
   validKeys[LEFT] = 1        -- left is valid
   validKeys[RIGHT] = 1       -- right is valid

He also does a real neat trick, setting a full range:

   validKeys['a'..'z'] = 1    -- 'a' through 'z' are valid

You can then use the value you are testing as an index into the sequence:

   if validKeys[key] then
      ...

This technique becomes even more useful if you have values other than true
or false (for example, the syntax coloring code returns the class of the
character). Back when I was a FORTH coder, we used to build arrays and poke
them with jump addresses instead of using CASE statements. Given a value,
you would use it as an index, grab the address from the table, and jump. Of
course, you pray you never get an index that exceeds the table bounds...

Just a suggestion.

 -- David Cuny

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu