Tcl Source Code

View Ticket
Login
Ticket UUID: 784359
Title: Tcl'2003: Unknown Array Element Callback
Type: RFE Created on: 2003-08-06 19:32:58
Submitter: dkf Assigned to: msofer
Subsystem: 07. Variables Severity:
Priority: 2 Last modified: 2026-11-13 11:18:45
Status: Closed Closed by: serhiy.storchaka
Resolution: Out of Date Closed on: 2026-11-13 11:18:43
Version: None
Description:
Yet another idea that cropped up at Tcl'2003:

It should be possible to specify a callback for an
array that is called whenever an attempt to access
(read/write) a non-existant element is made. This would
enable all sorts of cool things, according to KBK.
User Comments:
msofer added on 2003-08-07 02:51:14:
Logged In: YES 
user_id=148712

I guess I didn't understand: in what respect is the
trace-based solution short of what's requested? Oris it just
a matter of performance?

% proc readTrace {name1 name2 op} {
        upvar 1 $name1 ary
        if {![info exists ary($name2)]} {
            puts "Non-existent element: set to \"z\""
            set ary($name2) z
        }
    }
% array set a {1 a 2 b}
% trace add variable a read readTrace
% set a(1)
a
% set a(2)
b
% set a(3)
Non-existent element: set to "z"
z

msofer added on 2004-03-26 23:53:07:
Logged In: YES 
user_id=148712

dkf: comments?

dkf added on 2004-03-29 16:02:11:
Logged In: YES 
user_id=79902

Handing this off to kbk; it was his idea originally

kennykb added on 2004-10-31 01:49:27:
Logged In: YES 
user_id=99768

Was I sober at the time ?

I certainly don't recall why I suggested such a thing, and
Miguel's read-trace idea appears workable.

msofer added on 2004-10-31 02:23:15:
Logged In: YES 
user_id=148712

Reopening - I like it; if it could be done in a manner that
doesn't impact performance too much, it could be a VERY good
way to define default values for arrays (and also dicts?).
Save us a bunch of [info exists], and defining default
values for [incr], etc.

The idea could be generalised to variables, namespaces, ...
Worth thinking about later on.

serhiy.storchaka added on 2026-11-13 11:18:45:

Default values for missing elements are provided by array default (TIP 508, Tcl 9.0), which also works with incr and lappend. Read traces cover the general callback.