Re: Lost in Ashok's teachings

Liste des GroupesRevenir à cl tcl 
Sujet : Re: Lost in Ashok's teachings
De : ralfixx (at) *nospam* gmx.de (Ralf Fassel)
Groupes : comp.lang.tcl
Date : 26. Sep 2024, 10:21:14
Autres entêtes
Message-ID : <ygabk0ahit1.fsf@akutech.de>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
* Luc <luc@sep.invalid>
| ----------- oop.tcl -----------------
| oo::class create Account
| oo::define Account {
|     variable AccountNumber Balance
| }
>
| oo::define Account {
|     method UpdateBalance {change} {
|         set Balance [+ $Balance $change]
|         return $Balance
|     }
|     method balance {} { return $Balance }
|     method withdraw {amount} {
|         return [my UpdateBalance -$amount]
|     }
|     method deposit {amount} {
|         return [my UpdateBalance $amount]
|     }
| }
>
| oo::define Account {export UpdateBalance}
| set acct [Account new 3-14159265]
| Account create smith_account 2-71828182
| $acct deposit 132
| ----------------------------------
>
| There, I broke the toy.
>
| can't read "Balance": no such variable
|     while executing
| "+ $Balance $change"
|     (class "::Account" method "UpdateBalance" line 2)
|     invoked from within
| "my UpdateBalance $amount"
|     (class "::Account" method "deposit" line 2)
|     invoked from within
| "$acct deposit 132"
|     (file "oop.tcl" line 41)
| Compilation failed.
>
| I tried a lot of ideas and all of them run into the same problem:
| the compiler has no knowledge of this Balance variable I speak of.

You have ommitted the constructor from Ashoks example which initializes
the 'Balance' variable.  In your class, this variable is simply not
initialized, which leads to the error.

This is the same with every variable in TCL:

  global foo
  set foo
  => can't read "foo": no such variable

  namespace eval foo {
    variable bar
    set bar
  }
  => can't read "bar": no such variable

You need to initialize (=set) a variable before you can use it.
How the initialization is done depends on the context. 

  namespace eval foo {
    variable bar init-value
    set bar
  }
  => init-value
 
Thus if you have variables in a class, you most probably need a
constructor to initialize them.

This is also true for many OO languages...

HTH
R'

Date Sujet#  Auteur
26 Sep 24 * Lost in Ashok's teachings8Luc
26 Sep 24 `* Re: Lost in Ashok's teachings7Ralf Fassel
26 Sep 24  `* Re: Lost in Ashok's teachings6Luc
26 Sep 24   +- Re: Lost in Ashok's teachings1Ashok
26 Sep 24   +- Re: Lost in Ashok's teachings1Ralf Fassel
26 Sep 24   `* Re: Lost in Ashok's teachings3Rich
27 Sep 24    `* Re: Lost in Ashok's teachings2Luc
27 Sep 24     `- Re: Lost in Ashok's teachings1Rich

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal