Skip to content
Tcl Source Code View Ticket
Login

View Ticket

Tcl'2003: Unknown Array Element Callback

Closed / Out of Date784359ffffffffffffffffffffffffffffffffffCreated 23 years agoUpdated 20 days ago
Descriptionplain2003-08-06 19:32:58
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.
msoferplain2003-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
msoferplain2004-03-26 23:53:07
Logged In: YES 
user_id=148712

dkf: comments?
dkfplain2004-03-29 16:02:11
Logged In: YES 
user_id=79902

Handing this off to kbk; it was his idea originally
kennykbplain2004-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.
msoferplain2004-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.storchakawiki2026-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.

Log in (anonymous is fine) to add a comment.