[Gambas-user] Referencing an array element with boolean
Benoît Minisini
gambas at ...1...
Sat Jun 21 12:23:23 CEST 2014
Le 21/06/2014 09:47, Patrik Karlsson a écrit :
> Many years ago when I was programming in Delphi I used to have object
> arrays of size 2 and referencing to the element index with true and false.
> This was very very useful.
>
> It was possible since false=0 and true=+1.
> In Gambas we have false=0 and true=-1.
>
> So now I came up with:
> Dim sMoods As String[] = ["Sad", "Happy"]
> Dim bHappiness As Boolean
>
> Debug CInt(True), Abs(True), Abs(CInt(True))
> Debug CInt(False), Abs(False), Abs(CInt(False))
>
> bHappiness = False
> Debug "bHappiness= "; bHappiness; ": " & sMoods[Abs(CInt(bHappiness))]
> Debug "bHappiness= "; bHappiness; ": " & sMoods[If(bHappiness, 1, 0)]
>
> bHappiness = True
> Debug "bHappiness= "; bHappiness; ": " & sMoods[Abs(CInt(bHappiness))]
> Debug "bHappiness= "; bHappiness; ": " & sMoods[If(bHappiness, 1, 0)]
>
> 1. Why is Abs(True) True?
>
I think I did that so that TypeOf(Abs(x)) = TypeOf(x). But for boolean,
it is not very useful. Maybe I should automatically convert Boolean to
Int in that case, so that Abs(True) = 1 and Abs(False) = 0.
> 2. Which is fastest, Abs(CInt(... or If(... ? I guess that If(... is more
> future proof.
Abs(CInt(True)).
>
> 3. I have a "BoolToIndex" function in a library module but I was thinking
> if it should not be part of the language, to be able to reference in
> a _simple_ way to an array element with a boolean.
No. But you will be able to do Abs(True).
Moreover, Boolean is, by definition, not a good datatype for indexing!
Regards,
--
Benoît Minisini
More information about the User
mailing list