# Lucid Dreaming/Introduction

\

## Disclaimer

When attempting some of the techniques in this book, you may have some
frightening experiences, such as falling sensations or sleep
paralysis. Although the authors attest
these are not dangerous, you should avoid techniques that create these
sensations if you would prefer not to experience them.

Your own expectations will have a significant effect on your dreams. If
you believe that dream characters act dull and lifelessly, they are far
more likely to do so. If you believe they can be creative, original, and
surprising, they are far more likely to be. Remember that the easier you
think it is to dream lucidly, the easier it will be.

Many of the techniques and "facts" presented on these pages are not
backed up by scientific research. This is not to say that these
techniques do not work, only that they may be
placebos or be ineffective much of the
time.

## About dreaming

```{=html}
<div style="float: right; margin: 0 0 1em 1em; font-style: oblique; font-size: smaller;">
```
!Stages of sleep\
The stages of sleep

```{=html}
</div>
```
Each night, we spend about one and a half to two hours dreaming. We
dream about once every 90 minutes of sleep. The time you spend in dreams
becomes longer throughout the night, from about 10 minutes to around 45
minutes or slightly longer. But what happens when we sleep?

There are five stages of sleep: four stages of NREM (Non-REM) sleep,
also called SWS (Slow-Wave Sleep), and one stage of REM (Rapid Eye
Movement) sleep. The most vivid and remembered dreams occur during REM
sleep. Research has shown that a person being woken from REM sleep will
account having just been in a dream roughly 80% of the time, while this
percentage is 15% during non-REM sleep.[^1] One sleep cycle is roughly
90 minutes long.

-   *(NREM 1)* The first stage is a transition state between wakefulness
    and sleep. This is the stage in which
    hypnagogic imagery occurs. It usually
    passes into stage 2 within a few minutes.
-   *(NREM 2)* During stage 2, the body gradually shuts down, and brain
    waves become longer in wavelength.
-   *(NREM 3)* Stage 3 usually occurs 30 to 45 minutes after falling
    asleep the first time. Large, slow delta brain waves are generated.
-   *(NREM 4)* Stage 4 is often called "deep sleep" or "delta sleep".
    The heart beats the slowest and there is the least brain activity.
    It is during this stage that sleepwalking usually occurs.
-   After stage 4, the NREM stages reverse and move back to stage 2, and
    then into REM sleep.
-   *(REM)* During REM sleep, some parts of the brain are nearly as
    active as while awake. In this stage, your eyes flicker rapidly
    (hence the acronym Rapid Eye Movement). Your body is paralyzed,
    preventing the body from acting out dreams.[^2]

After the REM state, you sometimes wake briefly. This is usually
forgotten by the time you wake up in the morning. If you don\'t wake up,
you go to stage 2.

**I never dream anyway.**

Actually, everyone has dreams --- but some people simply don't remember
them. In the next chapter, you will find out how to improve your dream
recall.

**Why do we dream? What do dreams mean?**

These questions are outside the scope of this book, but you can find
several hypotheses in the Wikipedia article on dream
interpretation.

## About lucid dreaming

Lucid dreaming is simply being aware that you are dreaming. With enough
experience, you can increase control over your dreams --- anything from
flying to creating people and places, and even changing into animals.
Having a lucid dream is like being the director of your own movie! A
passage from the fantasy novel *Harry Potter and the Deathly Hallows*
(chapter at King\'s Cross) that may explain what this looks like:

> For the first time, he wished he were clothed. Barely had the wish
> formed in his head than robes appeared a short distance away.

Lucid dreams have been scientifically proven to exist. Stephen LaBerge
of The Lucidity Institute used a special
machine to track eye movements during a dream (these are linked to your
eye movements within the dream). He asked lucid dreamers to point their
eyes left and right in quick succession once they became \"conscious\"
in their dreams, and this movement was recorded on the machine. For more
information on this and other experiments, read *Exploring the World of
Lucid Dreaming* (ISBN in Further
Reading).

There are plenty of reasons you might want to dream lucidly:

-   For **fun**! Just flying in a lucid dream is an exhilarating
    feeling. Lucid dreams are generally far more intense and vivid than
    most non-lucid dreams. You can use a lucid dream to wind down after
    a long day.
-   Transforming into animals or getting superpowers is a **unique
    experience** that is hard to get any other way.
-   If you are particularly interested in dreams --- either spiritually
    or psychologically --- trying lucid dreaming could help you in your
    research.
-   If you\'re writing fiction or even **creating** a world for a
    computer game, lucid dreaming can help you visualize it. You could
    ask your characters how they feel about something or what they think
    will happen.
-   Some people compose music in their lucid dreams.
-   Lucid dreams can be realistic enough to **rehearse** a speech or
    musical performance.
-   You can **relive** previous dreams or experiences.
-   They can help in **dream interpretation** and **communicating with
    your subconscious**.

**I can't control my dreams.**

This is very rarely actually the case (though sometimes it is in
nightmares). Usually it is just your memory which treats you as though
it were beyond your control. If you become lucid in a dream where you
have a body, you will almost always be able to control your body.
However, you might not manage to do anything else. Don\'t worry, though
--- most people have no problem with jumping very high or flying in a
lucid dream!

On the other hand, parts of your brain are less active while dreaming,
which can lead to dream/trance logic and sometimes choices you will
later regret. For example, you might choose to continue your lucid
dream, although you know that once you wake you will only remember half
of it. Once you wake up, you may wish that you had stopped your dream.
Another example is of somebody who dreamt they were sitting next to
Mother Theresa. They wondered if they might be dreaming, thinking *isn't
Mother Theresa dead?* They then concluded that she was obviously right
next to them and therefore alive, and that it wasn't a dream!

**Are lucid dreams related to psi
phenomena?**

There are differing views on this. Some people claim to have organized
shared dreams or precognitive dreams through lucid dreaming. Others say
these are simply created in the brain like any other dream, something
like self-hypnosis.

**How long does it take to learn how to dream lucidly?**

This completely depends on the person and circumstances. Some people
have a lucid dream after just a few nights of learning about it, while
for others, it may take months! If you don\'t get enough sleep or feel
too stressed after work to regularly practice induction techniques, then
it may take a long time, especially if you expect it to. It will also
depend on how much effort you put in. However, *everybody* has the
ability to dream lucidly.

**I think I do this naturally. Does this happen?**

It is quite rare to have regular lucid dreams naturally, although most
people have had a lucid dream at some point in their lives. If you want
to increase the frequency of your lucid dreams, carry on reading through
the book; otherwise, skip to the
Using section to get some ideas for
your dreams.

**I had \[a dream\], was I lucid?**

In general, a lucid dream is defined as a dream in which you know you
are dreaming at some point, regardless of anything else. Even if you
were lucid one second but lost your lucidity, it is still technically a
lucid dream.

However, this can be a little misleading. Sometimes you dream that you
fall asleep and have a lucid dream! This is often thought of as a sign
that you will have a proper lucid dream soon, as your mind is thinking a
lot about lucid dreams.

Try using this table:

+-----------------------------------+-----------------------------------+
| Signs you were lucid              | Signs you weren\'t lucid          |
+===================================+===================================+
| -   Doing a reality check which   | -   Dreaming that you were        |
|     gave a positive result        |     dreaming                      |
| -   Attempting to stabilize the   | -   Having an unusually poor      |
|     dream (see the                |     recall for that dream after   |
|     Using | -   Not recognizing illogical     |
|     chapter)                      |     parts of the dream as a dream |
| -   Attempting to fly, walk       | -   Attempting to fly, walk       |
|     through mirrors, etc.         |     through mirrors, etc. without |
|     immediately after realizing   |     success                       |
|     you are dreaming              | -   Treating dream characters as  |
| -   Waking up as soon as you      |     you would real people\*       |
|     realize that you are dreaming |                                   |
| -   Remarks to dream characters   |                                   |
|     that you are dreaming         |                                   |
+-----------------------------------+-----------------------------------+

\* However, some people may have lucid dreams and deliberately choose to
treat dream characters as if they were real. In fact, it can be
intriguing to have real conversations with dream characters, such as
physics or philosophy discussions - you may discover they know more than
you do!

## Possible dangers of lucid dreaming

There is no current evidence of lucid dreaming being abnormal or
unhealthy in any way. However, there may be some more or less minor side
effects associated with having lucid dreams. Please don't let this scare
you away from trying this; rather, remember that with dreams you are
dealing with your own subconscious mind and recklessness is not
recommended.

### Alienation

Most people have never even heard of lucid dreaming, much fewer ever
experienced it. Some people are also less than open-minded and receptive
to new ideas. Don't be surprised if someone considers this whole
phenomenon "weird" or "crazy" (which it is not). Don't preach, either;
you don\'t have to convince anybody.

Often people who spontaneously lucid dream, especially children, may
find it surprising that not everyone does. They may even start thinking
that they are the only people in the world who have lucid dreams. If
they're worried, the best support is to let them know that they're not
alone.

### Dissociation

Lucid dreaming may weaken the borders between waking and dreaming, the
conscious and subconscious mind, reality and fantasy. This might lead to
problems of a dissociative nature. Probably the most common form of
dissociation involves having problems distinguishing your waking
memories from dream memories. Everyone who recalls at least one dream
will have to sort out their dreams from reality in the morning. This can
really be a problem for those who have previously had zero recall and,
due to lucid dreaming, have had a major uptick in recall. Now, suddenly,
they have all these excess, illogical memories to sort out. **This is
unlikely to be a major problem**, but may be a big annoyance. An example
is when you have actually misplaced an item, and \"find it\" in a dream.
If you cannot distinguish dream from reality you will now think you know
where that item is, perhaps even placed it where you felt sure to find
it later, but when you awake it will not be there.

However, there are signs that you should watch for which indicate a
larger problem may be developing. Lucid dreaming in itself should not
cause these to appear *in a waking state*:

-   Ability to ignore extreme pain or what would normally cause extreme
    pain
-   Absorption in a computer game, television program or movie
-   Remembering the past so vividly one seems to be reliving it
-   Finding evidence of having done things one can't remember doing
-   Not remembering important events in one's life
-   Being in a familiar place but finding it unfamiliar
-   Seeing oneself as if looking at another person
-   Other people and objects do not seem real
-   Looking at the world through a fog or haze
-   Not recognizing friends or family members
-   Finding unfamiliar things among one's belongings
-   Finding oneself in a place but unaware of how one got there
-   Finding oneself dressed in clothes one doesn't remember putting on

If this has happened, and there is no other cause (e.g. drugs), take a
break from lucid dreaming for a while. In fact, take a break from
anything fictional for a while, at least until symptoms stop. In
addition, you may consider avoiding experimentation with lucid dreaming
if you have a mental condition that will alter your perception of
reality, eg. Schizophrenia, Hallucinations, Dementia.

### False awakenings

One of the advantages of having lucid dreams is being able to change a
dream or wake up if things are not turning out as planned. A false
awakening is when you seem to have woken up but are actually still
dreaming. For example, you may find yourself waking up in your room. But
once there, new things will start happening---for example, someone might
visit, or you might wander outside because of an odd noise, or there
might be objects all over the place. There are no such things as loops
of awakenings. You can simply shock your body awake by applying a
stimulus in your dream. It\'s a good idea to get in the habit of doing a
reality check just after waking up so that you\'ll realize when this
happens and become lucid.

When this happens repeatedly in the same night, it can be very tiring
and often frightening. Not only can the belief of being fully awake in
your room while being exposed to unusual situations be scary, but you
also may start fearing you won\'t be able to actually wake up. And,
depending on the content of the dream, since all your dreams tend to
start in your room, you may fear what could happen once you actually do
wake up.

But this is not a very common situation. Once you are lucid, it is
usually easier to wake up or lose the dream than it is to keep dreaming.

### Controversial: Accidentally encountering "spiritual" entities

This depends on your worldview. If you believe that dreams are a
creation of your brain and nothing more, you don't need to worry about
spirits or anything similar. If you want to be on the safe side,
treating objects in your dream decently and politely won't do you any
harm.

The book \"The Art of Dreaming\" by Carlos Castaneda has a lot to say on
this subject. (See Further
Reading)

### Controversial: Creating bad habits or becoming a control freak

When lucid dreaming, you have the option to control the dream world in
ways that are impossible in the waking world. You can, for example, make
objects appear or disappear, or make people act according to your will.
Some people believe this may lead your subconscious to desire this kind
of control in the waking world, where it's highly inappropriate. Also,
you might be tempted to apply dream-world solutions to waking-life
problems instead of actually facing them; for example, just willing bad
things to go away or escaping or destroying them by superpowers. Again,
this is probably more of a problem if you are not mentally stable at the
outset of your dreaming process.

### Controversial: Exhaustion

Some people believe that experiencing many artificially induced lucid
dreams often enough can be very exhausting. The main reason for this
phenomenon is the result of the lucid dreams expanding the length of
time between REM states. With fewer REMs per night, this state in which
you experience actual sleep and your body recovers becomes infrequent
enough to become a problem. This is just as exhausting as if you were to
wake up every twenty or thirty minutes and watch TV. The effect is
dependent on how often your brain attempts to lucidly dream per night.
If you enter into a routine of attempting to lucidly dream, you may
cause recursive lucid dreams that occur at each state change.

### Controversial: Inability to stop

If you have trained your mind to the point where it can step over the
boundary without conscious effort, you might find it difficult to stop.
Do not become alarmed if you have trouble stopping the process of lucid
dreaming, it is possible to get out of the habit. As long as you truly
expect to stop having lucid dreams regularly, you will. You just need to
stop any further attempts to lucid dream, and within a few months the
lucid dreaming will go away by itself. Remember; do not be alarmed if,
even with your attempts to stop, you experience further lucid dreams. It
might take a while to break the habit. If you have real concerns, it may
be advisable to talk with your doctor or therapist regarding appropriate
treatment, including medication.

## Similar techniques

**I can do astral projection, should I learn how to dream lucidly?**

Possibly not. If you often enter a "dream world" after having the
experience of leaving your body, that is basically the same as the
method called Wake-Initiation of Lucid
Dreams. Keep in
mind that many people believe that "astral projection" or "out-of-body
experiences" are actually lucid dreams. Whether these are real psi
phenomena or the creative product of your
dreaming mind, learning to dream lucidly will expand the variety of your
experiences.

**If this is so similar, why learn lucid dreaming and not astral
projection?**

Here are some reasons:

-   Lucid dreaming is something that everybody can understand. In fact,
    most people have already had a lucid dream. No single theory about
    astral projection is accepted even in the astral projection
    community.
-   If you are prepared to spend money, there are some gadgets that can
    help induce lucid dreams. They usually emit light or sound signals
    shortly after the REM state is detected. Hypnosis tapes usually
    focus more on self-improvement and you cannot decide what to do with
    your hypnotic trance.
-   If you don't believe in psi
    phenomena, you will likely be much
    more comfortable reading books about lucid dreaming than those on
    astral projection. If you have to keep stopping and thinking \"but
    that\'s not possible\", there\'s always the danger that your
    feelings of skepticism will affect the way you think about lucid
    dreaming and make it much harder for you to do.
-   You would be sleeping anyway, so it doesn\'t take up waking time.
-   You\'ll be able to use this Wikibook to your advantage!

## References

```{=html}
<references/>
```
es:Sueño lúcido/Introducción
it:Sogno lucido/Introduzione
pl:Świadome_śnienie/Wstęp

[^1]: Arno F. Wittig. *Schaum\'s outline of theory and problems of
    introduction to psychology*. McGraw-Hill, 1977. Retrieved from
    Google
    Books
    on September 23, 2009.

[^2]: Rochelle Merilien. *Sleep Paralysis*. Retrieved September 21, 2009
    from
    1


# Lucid Dreaming/Using

## Dream stabilization

Once you are able to dream lucidly, you may find that it is difficult to
stay in the dream; for example, you may wake instantly or the dream may
start "fading" which is characterized by loss or degradation of any of
the senses, especially vision. Alternatively, a new lucid dreamer could
easily forget that they are in a dream, as a result of the shock of the
sensation.

Don\'t worry if you wake immediately after becoming lucid. As you gain
more experience of becoming lucid, it will come as less of a shock and
you'll be less likely to wake up. Make sure you do a reality check to be
sure you're not still dreaming. As you gain more experience, you will
have an easier time identifying when and remembering that you are
dreaming.

You can avoid more gradual fadings by **stimulating your senses**. This
means listening for sounds, feeling around with your hands, and paying
attention to what you see and smell. The idea here is to load your
senses with stimulation from the dream so that your senses cannot shift
to the real world. If you close your eyes, you are removing a great deal
of sensory information and might wake up. Staring at a single point can
cause effectively the same problem if you stop seeing everything else in
your peripheral vision, or don\'t see enough movement. If you hear
something loud in real life and are hearing nothing in the dream, your
senses may shift to the real world, causing you to wake up.

Ideally you should be able to use the techniques below to stabilize your
dream *before* it starts to fade (or "black out"). As always, prevention
is better than treatment - and the more stable and vivid your dreams
are, the more enjoyable they will be. However, if that doesn\'t work you
may be able to use stabilization techniques to stop the fading; the
spinning technique is probably the most effective in this case.

If you still can't stabilize your dream, you may decide to try and wake
up with the aim of remembering your dream as accurately as possible
while its still fresh in your mind.

### Hand Touching

Rub your hands together and concentrate on the rubbing. You should feel
the friction and the heat of your hands. If you can concentrate on the
feelings that this action generates, your dream is likely to stabilize
and become more vivid and detailed. You can also keep one hand on your
arm while exploring the dream for a constant sense of stimulation. This
technique is most effective when used in conjunction with the "Slowing
it down" technique, by staring at your hands while rubbing them
together.

### Spinning

You spin around in your dream much as you would if you suddenly want to
feel dizzy in real life. The sensation of movement is the key here to
stabilizing the dream. Many people report success with this technique,
but it also tends to cause a complete change of your dream scene (see
Changing the dream
environment below). If the
dream scene disappears completely (e.g., becomes black), it is necessary
to visualize the dreamscape to return to the dream.

### Slowing it down

Some people like to stabilize the dream by "stopping to smell the roses"
and slowly staring at a dream object until it becomes clear. The dreamer
would then look around elsewhere, noticing how detailed everything is,
thereby stimulating the visual portion of the dream. *However, others
find this can cause their lucid dream to end.* If you focus on one
object for too long to the exclusion of everything else, you will likely
wake up or lose the dream. It works best to pay attention to everything
in your vision, including your peripheral vision, not just the center of
the object you\'re staring at. If staring at a single object doesn\'t
work for you, try to let your eyes wander around instead.

### Touching your dream

If you feel that your dream is too abstract and fear that it might be
fading, you can prevent this by grabbing hold of a solid object in your
dream and focus on how real the sensation is. A good tip is to find
something you know is stuck, for instance a table nailed to the ground,
and pull it with all your muscular power (no *supernatural* powers!),
and you should feel how solid it is. The idea is that you convince
yourself that the dream is solid and real --- through tactile
stimulation --- and nothing abstract.

### Regaining waking memory or skills

This is also likely to enhance your degree of lucidity. Try to remember
facts from your waking life, such as your phone number, address, etc.,
or do some simple math. Or, start reciting the lyrics to your favorite
song. Or perhaps try some sports practice you know well --- this all
depends on which senses / methods of thought process you tend to rely on
most in your waking life.

### Dream Guide

Summon a DC (Dream character) that you expect to Guide you through the
dream. Summoning is easier if you always expect this Guide to be there
in a dream. The Guide is useful for escaping scary or unpredicted
environments (\"whooshing\" you away, killing or unsummoning the threat,
reminding you that you are in control.). Imagine this Guide as powerful,
knowledgeable, and protective over you. Guides can also walk you through
summoning, flying, shapeshifting, etc. and be useful for learning and
controlling your dreams.

### False awakening

A couple of the users on the ld4all.com forums have had success with
creating a false awakening to stabilize a dream. If the above techniques
are failing and you find your dream still fading, *and you really want
to continue your lucid dream*, do the following:

1.  Expect to have a false awakening.
2.  When you think you wake up, perform a reality check.

You will either have a false awakening, reality check, and then end up
with an even more vivid lucid dream, or will really wake up, perform a
reality check, and realize that you just woke up (bad luck!).

The most important part of this is the reality check. This is what will
continue your lucid dream. You should be performing reality checks when
you wake up. If you plan to induce false awakenings in order to
stabilize a dream, the reality check that you perform as you wake up is
as important as the one that got you lucid, if not more.

Perform every check in the book until you are **positively, absolutely,
and completely sure** that you aren't dreaming. A series of 10 reality
checks is more likely to produce dream results in a dream, especially if
you are expecting dream results. This technique is for those who are
desperate!

*If you have had a good experience with this technique, please go to the
talk page and post your experiences, as there have not been many
anecdotes of it working yet.*

```{=html}
<div style="text-align: right; font-size: small">
```
top

```{=html}
</div>
```
## Recovering from lost visuals

There are a few things you can try to do if you lose your vision. Most
of these are less likely to help prolong your dream than the above
techniques.

You can also try these if you have just woken up and are lying in your
bed. You may be able to return to your dream.

### Autosuggestion

You can repeat over and over a phrase similar to "I can see my dream,"
or otherwise enforce in your mind that you can see a dreamscape. (See
Autosuggestion)

### Visualising

You can visualise the scene as it would be if you could see it. You
could take this as an opportunity to change the dreamscape by
visualising a different environment from the previous one in the dream.
This can be made easier by spinning as you visualize. (See Changing the
dream environment below)

## Altering the dream

### Changing the dream environment

You can change the dreamscape by simply visualizing a different
environment. Stephen LaBerge, author of *Exploring the World of Lucid
Dreaming*, suggests closing your eyes, spinning around, and visualizing
a new location. Alan Worsley, a famous lucid dreamer, describes another
technique of summoning a television and remote to switched dreamscapes.
By simply "changing the channel" on the remote, imagine your
surroundings switching to your desired location, as though you were
switching through various television programs.

In both of these methods, details are key. The more details you provide
for your next dreamscape, the easier it will be to get there. For
example, if you wanted go to the Superbowl in your dreams, you might
simply state:

:   **"I want to be at the Superbowl."**

But this statement could be improved by adding details:

:   **\"I want be in the endzone seats, drinking a Coke, and wearing my
    favorite player\'s jersey at the Super Bowl.\"**

### Summoning objects into your dream

At some point in your lucid dreaming experience, you\'ll probably want
to handle various objects, or talk with certain people. Both of these
needs can be fulfilled by using your mind, and the power of suggestion.
There is no set way to \"make\" things in the dream world; in fact, many
lucid dreamers devise their own methods through experimentation.
However, here are some of the more common \"summoning\" techniques:

-   Try reaching for objects that are not within your field of vision.
    For example, think to yourself: "When I reach into my pocket, there
    will be a green box of mints." Then, attempt to actually take a
    green box of mints out of your pocket. Other variations of this
    include reaching behind you for an object, or reaching through a
    mirror in hopes of getting a hold of what you want.
-   To summon a person, you might say to yourself: "When I turn around,
    \[person\'s name\] will be standing in front of me," or "When I walk
    through this mirror, I will see \[person\'s name\]," or "In a few
    moments, \[person\'s name\] will walk through that door (or around
    that corner)."
-   More experienced lucid dreamers can try making the object
    materialize right before their eyes. This will require a fair amount
    of concentration. Here is an example of this process:\

:   I am lucid dreaming in my backyard, and it\'s currently night. Now,
    I don\'t like the dark in my lucid dreams because I\'m more likely
    to wake up, and I fear there are monsters lurking around every
    corner. So, I want to **make the sun appear** so that it\'ll be
    daytime. Focusing on the horizon, I visualize the sun rising above
    it.\
:   At first nothing happens, but I continue focusing and\...yes!
    There\'s some light filtering over the horizon! And now the sun is
    rising to the sky and it settles there; so far, so good. But
    wait\...the sky is still black. Peering at bit closer at the sun, I
    can just make out a faint ring of blue sky encircling it. Lifting my
    hand towards it I shout, \"Blue!\". The blue ring quickly spreads
    across the sky, creating the full daytime effect."\

-   Some dreamers may have success by closing their eyes and imagining
    the desired object in front of them once when they open their eyes .
-   Try using mechanical devices within the dream, such as a nearby
    lightswitch or button, to summon objects or people. (i.e. \"When I
    flip this switch/press this button, X will appear.\")
-   Convince yourself you have magical powers (or scientific). Then, use
    them to summon objects, shapeshift, etc. This can help you believe
    the creation of objects more easily.
-   (This one is dumb, but it works.) Begin singing *Friend Like Me*,
    and summon stuff to the beat. They may disappear after you finish
    singing, or start dancing, but hey, it\'s pretty darn fun.

Remember, in the dream world, your expectations shape your surroundings.
If you think a big, scary monster is going to step out of the shadows
and attack you\...well, a big, scary monster probably *is* going to step
out of the shadows and attack you. So, don\'t be a victim; take control
of your thoughts and use them to your advantage.

```{=html}
<div style="text-align: right; font-size: small">
```
top

```{=html}
</div>
```
## What you can do

This final section should see you off with a few ideas of what to do in
a dream.

It is advised to have a *clear purpose* for your lucid dreams whenever
you go to sleep. In other words, every night you consider what you want
to do when you have a lucid dream, and select one thing, or perhaps two
or three if you are skilled. Avoid this:

:   \"What am I gonna do what am I gonna do? I wanna fly, walk through
    walls, eat until my stomach explodes, spy on my neighbours, drive in
    a car real fast, woooeeey I\'m gonna . . .\"

You will either end up doing none of these things in your dream or
getting overexcited and waking up.

Now that that's clear, here's a list of possible things you could do,
ordered in difficulty. Remember that you might find some things
unusually hard (or easy) compared to most lucid dreamers, this is
perfectly normal! This is a very rough guide --- if you've managed
something in the Easy section, don\'t be scared to try for something
from the Medium section.

### Easy

-   Fly

    :   Most people enjoy flying around in dreams. There are different
        styles of flight that people use, each with a varied level of
        success for each individual. Methods such as "swimming through
        the air", "Superman style" (one arm outstretched), "Neo style"
        (both arms at your side), and "Airplane style" (both arms out)
        ,\"eagle style\" (gliding through the air currents, using your
        fingered wings to navigate altitudes) are often used. There are
        a few methods of getting up into the air, such as simply jumping
        (you can jump really high in dreams if you believe it) or
        imagining a great force pushing you from your feet or walking up
        on air as though it is a staircase. Some people summon jetpacks
        and slip them on to fly. Be creative and dream up your own
        methods.
-   Explore your dream world

    :   Be warned, you are quite likely to forget you are dreaming when
        exploring! Doing reality checks often and muttering to yourself
        about how real everything seems can help to avoid this. You can
        also ask a dream character to tag along with you and remind you
        when you forget that you're dreaming.
-   Walk through a mirror or wall

    :   You can pass through dream objects such as walls, glass, trees,
        and everything else. Confidence is really the key here. Some
        variations on going through stuff can be going in slowly,
        wiggling your finger in first, or running quickly into the
        object and telling yourself you would go through it. Some people
        particularly like to go through mirrors because of the
        unpredictable effects this action produces. However, if you tell
        yourself you will end up at a certain location before passing
        through a mirror, you can change the dream scene quickly. Be
        warned, some people experience nothing and wake up after passing
        through. You may want to hold your arm to keep yourself in the
        dream.
-   Look at the sky

    :   People often report amazing skies in lucid dreams. You can also
        shout colors at it and paint some sunrises.
-   Show off to your friends ("Hey guys; I can go through this wall!")
-   Do plenty of sports (trampolining, skiing, swimming, dancing, etc.)
-   Use various power such as Telekinesis and magic (a shortcut if you
    are having problems would be to summon a magic wand/staff or other
    device)
-   Try to read a book that you have never read and remember the content
-   Try to browse the Internet and visit sites that you\'ve never
    visited
-   Use things that you have never used
-   Last but not least: Edit Wikipedia/Wikibooks articles (see question
    106 of the Wikipediholic
    Test) and see
    if the changes remain when you awake!

### Medium

-   Eat until you're near bursting!
-   Teleport
-   Create some dream characters (possibly from a book or film)
-   Try to find your spirit guide
-   Experiments (in fact, researchers will often want people of various
    skills)
-   Body swapping/possession (where you enter a different body)
-   Morph
-   Take some drugs (this is more realistic if you've done so in real
    life)

    :   Many people have also experienced realistic effects when trying
        drugs in dreams that they have never taken in real life.
-   Drive a vehicle (This is especially fun if you haven\'t ever driven
    in real life)
-   Fight

    :   Nobody can tell you what you should and should not do in your
        dreams; the choice remains up to you.

    -   Use weapons

        :   It is usually more interesting to use melee weapons (knives,
            swords, brass knuckles) than projectile weapons. Machine
            guns and pistols often run out of ammo and summoning it can
            be difficult. Misfires and jamming is also common. *(Your
            subconscious expectations will shape your dreamscape in all
            manner of ways, If you believe it is hard to accomplish, if
            you believe it will jam or misfire, it will. I have had no
            issues with weaponry such as firearms in my dreams
            what-so-ever, take this \"advice\" lightly.)* However this
            can be overcome by using Directed Energy Weapons (Lasers,
            Plasma/pulse rifles), or weapons that can\'t jam (bows,
            simple firearms like muskets and so on).
-   \"Beat up\" your enemies

### Hard

-   Have sex

    :   The excitement, or closing your eyes, can cause you to wake up.
        An additional reason for waking up may be fixing your eyes on
        your partner, as holding a gaze for long is also known to cause
        waking up. Also your dream partner has a strange way of
        transforming in the midst of ecstasy. Finding a sex partner
        isn\'t very hard, it\'s keeping them that is difficult. That is
        why it is best to not panic when they are transforming and
        accept them for what your subconscious brings you.
-   More morphing like 360 degree vision, sonar
    vision, etc.
-   Create false memories, etc. False memories can be made by having a
    lucid dream, but scripting it so you will think it is real, e.g. you
    think what happened in your dream happened in real life. This is
    hard because you will have to forget it is a dream while staying
    lucid (knowing it is a dream).
-   Compose music or poems (or request them from your subconscious)
-   Build a fantasy dream world! (some people build a dream world
    naturally)
    -   Lucid Crossroads
    -   Astral Pulse
        Island
    -   H.P. Lovecraft\'s Dreamlands
-   Have precognition (your subconscious can be very good at predicting
    the future with relationships and career)
-   Experience death. This could be a very harsh experience, and
    depending on your religious or philosophical beliefs may summon you
    into a different world or nothingness.
-   Ask the dream to show you your worst fears/deepest traumas/etc. (be
    prepared for some bad stuff to surface)
-   Build/use impossible objects, such as
    hypercubes, Klein
    bottles, etc.
-   Rewind time

```{=html}
<div style="text-align: right; font-size: small">
```
top

```{=html}
</div>
```
## Conclusion

With all the techniques in this book, you may feel overwhelmed and
uncertain of what to do next. Don\'t worry --- just choose a few
techniques to "map your way to lucidity", decide on a few things you
will want to do from this page, and start!

If you are still unsure of what to do, don't worry --- you might happen
to have a lucid dream tonight!

If you are beginning to feel a compulsive thirst for *more* information
about dreams, head over to the Further
Reading section for the
sites to satisfy your cravings. Remember to come back occasionally and
help make the wikibook grow!

```{=html}
<div style="text-align: right; font-size: small">
```
top

```{=html}
</div>
```
es:Sueño lúcido/Uso it:Sogno
lucido/Uso


# Lucid Dreaming/Glossary

CAT :See *Cycle Adjustment Technique*.\
Cycle Adjustment Technique
:   Adjusting your sleep cycles to increase the likelihood of having a
    lucid dream.

DC :See *Dream character*.\
DILD :See *Dream-Initiated Lucid Dream*.\
Dream character
:   Any character inside your dream. Some people believe they are real
    people or spirit guides, others that they\'re just products of the
    dreaming mind.

Dream-Initiated Lucid Dream
:   A lucid dream that begins during a \"normal\", non-lucid dream.

Dream recall
:   The ability to remember details of one\'s dreams.

Dream Result
:   Result from a reality check that indicates that one is dreaming.
    *Ex: Breathing through your nose while pinching your nostrils.*

Dreamscape
:   The landscape and scenery of one\'s dreams.

Hypnagogic imagery
:   The images, sounds, etc. that you perceive as you fall asleep. Not
    to be confused with *phosphenes*.

EILD :See *Erotically induced lucid dream*\
Erotically induced lucid dream
:   A lucid dream with sexual activity. They may trigger a real orgasm,
    a phenomenon know as nocturnal emission or wet dream.

HI :See *Hypnagogic imagery*.\
LD :See *Lucid dream*.\
LILD :See *Lucid Induction of Lucid Dreams*.\
Lucid dream
:   A dream in which you are aware that you are dreaming.

Lucid Induction of Lucid Dreams
:   The technique in which you do something in a lucid dream that
    theoretically will remind you that you\'re dreaming in your next
    dream.

MILD :See *Mnemonic Induction of Lucid Dreams*.\
Mnemonic Induction of Lucid Dreams
:   The technique in which you mentally repeat to yourself, as you fall
    asleep, your future intention to realize that you\'re dreaming.

Named Subconscious Technique
:   (See \"Getting more help with MILD from your subconscious\", in the
    forum links box in the MILD
    section.) This technique
    is a useful aid to the MILD and autosuggestion techniques where the
    dreamer actively engages his or her subconscious for dream results.

NST :See *Named Subconscious Technique*.\
Oneironaut
:   A skilled lucid dreamer.

Phosphenes
:   Patches of colour (usually red or blue) that you can constantly see
    while your eyes are closed.

Rapid Eye Movement
:   The stage of the sleep cycle that your most vivid dreams occur in.

RC :See *Reality check*.\
Reality check
:   A simple and quick method of determining if one is dreaming. *Ex:
    Breathing with your nose shut, faulty light switches, etc.*

Real-life result
:   A reality check result which indicates one is may not be dreaming.
    *Ex: Being unable to will oneself to fly.*

REM :See *Rapid Eye Movement*.\
Sleep paralysis (SP)
:   The body\'s natural phenomenon of paralyzing the limbs of the body
    while asleep. This may be experienced consciously, either by
    accident or during the WILD technique.

VILD :See *Visual Induction of Lucid Dreams*.\
Visual Induction of Lucid Dreams
:   The technique in which you incubate a dream that reminds you to do a
    reality check and become lucid.

Vivid dream (VD)
:   A dream with a notably higher level of detail.

Wake-Back-To-Bed
:   The technique in which you wake up for a bit after a few hours of
    sleep and go back to sleep again. Usually used in combination with
    other techniques.

Wake-Initiated Lucid Dream
:   A lucid dream triggered by consciously falling asleep.

WBTB :See *Wake-Back-To-Bed*.\
WILD :See *Wake-Initiated Lucid Dream*.


# Tcl Programming/Introduction

### Introduction

#### So what is Tcl?

The name Tcl is derived from \"Tool Command Language\" and is pronounced
\"tickle\". Tcl is a radically simple open-source interpreted
programming language that provides common facilities such as variables,
procedures, and control structures as well as many useful features that
are not found in any other major language. Tcl runs on almost all modern
operating systems such as Unix, Macintosh, and Windows (including
Windows Mobile).

While Tcl is flexible enough to be used in almost any application
imaginable, it does excel in a few key areas, including: automated
interaction with external programs, embedding as a library into
application programs, language design, and general scripting.

Tcl was created in 1988 by John Ousterhout and is distributed under a
BSD style license
(which allows you everything GPL does, plus closing your source code).
The current stable version, in February 2008, is 8.5.1 (8.4.18 in the
older 8.4 branch).

The first major GUI extension that works with Tcl is Tk, a toolkit that
aims to rapid GUI development. That is why Tcl is now more commonly
called Tcl/Tk.

The language features far-reaching introspection, and the syntax, while
simple, is very different from the
Fortran/Algol/C++/Java world. Although Tcl is a string based language
there are quite a few object-oriented extensions for it like
Snit, incr
Tcl, and
XOTcl to name a few.

Tcl was originally developed as a reusable command language for
experimental computer aided design (CAD) tools. The interpreter is
implemented as a C library that could be linked into any application. It
is very easy to add new functions to the Tcl interpreter, so it is an
ideal reusable \"macro language\" that can be integrated into many
applications.

However, Tcl is a programming language in its own right, which can be
roughly described as a cross-breed between

-   LISP/Scheme (mainly for its tail-recursion capabilities),
-   C (control structure keywords, expr syntax) and
-   Unix shells (but with more powerful structuring).

#### One language, many styles

Although a language where \"everything is a command\" appears like it
must be \"imperative\" and \"procedural\", the flexibility of Tcl allows
one to use functional or object-oriented styles of programming very
easily. See \"Tcl examples\" below for ideas what one can do.

The traditional, \"procedural\" approach would be

``` tcl
proc mean list {
   set sum 0.
   foreach element $list {set sum [expr {$sum + $element}]}
   return [expr {$sum / [llength $list]}]
}
```

Here is yet another style (not very fast on long lists, but depends on
nothing but Tcl). It works by building up an expression, where the
elements of the lists are joined with a plus sign, and then evaluating
that:

``` tcl
proc mean list {expr double([join $list +])/[llength $list]}
```

From Tcl 8.5, with math operators exposed as commands, and the expand
operator, this style is better:

``` tcl
proc mean list {expr {[tcl::mathop::+ {*}$list]/double([llength $list])}}
```

or, if you have imported the tcl::mathop operators, just

``` tcl
proc mean list {expr {[+ {*}$list]/double([llength $list])}}
```

Note that all of the above are valid stand alone Tcl scripts.

It is also very easy to implement other programming languages (be they
(reverse) polish notation, or whatever) in Tcl for experimenting. One
might call Tcl a \"CS Lab\". For instance, here\'s how to compute the
average of a list of numbers in Tcl (after first writing somewhat more
Tcl to implement a J-like functional language - see Tacit
programming in examples):

``` tcl
Def mean = fork /. sum llength
```

or, one could implement a RPN language similar to FORTH or Postscript
and write:

``` tcl
 : mean  dup sum swap size double / ;
```

A more practical aspect is that Tcl is very open for \"language-oriented
programming\" - when solving a problem, specify a (little) language
which most simply describes and solves that problem - then go implement
that language\...

#### Why should I use Tcl?

Good question. The general recommendation is: \"Use the best tool for
the job\". A good craftsman has a good set of tools, and knows how to
use them best.

Tcl is a competitor to other scripting languages like awk, Perl, Python,
PHP, Visual Basic, Lua, Ruby, and whatever else will come along. Each of
these has strengths and weaknesses, and when some are similar in
suitability, it finally becomes a matter of taste.

Points in favour of Tcl are:

-   simplest syntax (which can be easily extended)
-   cross-platform availability: Mac, Unix, Windows, \...
-   strong internationalization support: everything is a Unicode string
-   robust, well-tested code base
-   the Tk GUI toolkit speaks Tcl natively
-   BSD license, which allows open-source use like GPL, as well as
    closed-source
-   a very helpful community, reachable via newsgroup, Wiki, or chat :)

Tcl is not the best solution for every problem. It is however a valuable
experience to find out what is possible with Tcl.

#### Example: a tiny web server

Before spoon-feeding the bits and pieces of Tcl, a slightly longer
example might be appropriate, just so you get the feeling how it looks.
The following is, in 41 lines of code, a complete little web server that
serves static content (HTML pages, images), but also provides a subset
of CGI functionality: if an URL ends with *.tcl*, a Tcl interpreter is
called with it, and the results (a dynamically generated HTML page)
served.

Note that no extension package was needed - Tcl can, with the **socket**
command, do such tasks already pretty nicely. A socket is a channel that
can be written to with **puts**. The **fcopy** copies asynchronously (in
the background) from one channel to another, where the source is either
a process pipe (the \"exec tclsh\" part) or an open file.

This server was tested to work pretty well even on 200MHz Windows 95
over a 56k modem, and serving several clients concurrently. Also,
because of the brevity of the code, this is an educational example for
how (part of) HTTP works.

``` tcl
# DustMotePlus - with a subset of CGI support
set root      c:/html
set default   index.htm
set port      80
set encoding  iso8859-1
proc bgerror msg {puts stdout "bgerror: $msg\n$::errorInfo"}
proc answer {sock host2 port2} {
    fileevent $sock readable [list serve $sock]
}
proc serve sock {
    fconfigure $sock -blocking 0
    gets $sock line
    if {[fblocked $sock]} {
        return
    }
    fileevent $sock readable ""
    set tail /
    regexp {(/[^ ?]*)(\?[^ ]*)?} $line -> tail args
    if {[string match */ $tail]} {
        append tail $::default
    }
    set name [string map {%20 " " .. NOTALLOWED} $::root$tail]
    if {[file readable $name]} {
        puts $sock "HTTP/1.0 200 OK"
        if {[file extension $name] eq ".tcl"} {
            set ::env(QUERY_STRING) [string range $args 1 end]
            set name [list |tclsh $name]
        } else {
            puts $sock "Content-Type: text/html;charset=$::encoding\n"
        }
        set inchan [open $name]
        fconfigure $inchan -translation binary
        fconfigure $sock   -translation binary
        fcopy $inchan $sock -command [list done $inchan $sock]
    } else {
        puts $sock "HTTP/1.0 404 Not found\n"
        close $sock
    }
}
proc done {file sock bytes {msg {}}} {
    close $file
    close $sock
}
socket -server answer $port
puts "Server ready..."
vwait forever
```

And here\'s a little \"CGI\" script I tested it with (save as time.tcl):

``` tcl
# time.tcl - tiny CGI script.
if {![info exists env(QUERY_STRING)]} {
    set env(QUERY_STRING) ""
}
puts "Content-type: text/html\n"
puts "<html><head><title>Tiny CGI time server</title></head>
<body><h1>Time server</h1>
Time now is: [clock format [clock seconds]]
<br>
Query was: $env(QUERY_STRING)
<hr>
<a href=index.htm>Index</a>
</body></html>"
```

#### Where to get Tcl/Tk

On most Linux systems, Tcl/Tk is already installed. You can find out by
typing *tclsh* at a console prompt (xterm or such). If a \"%\" prompt
appears, you\'re already set. Just to make sure, type *info pa* at the %
prompt to see the patchlevel (e.g. 8.4.9) and *info na* to see where the
executable is located in the file system.

Tcl is an open source project. The sources are available from
<http://tcl.sourceforge.net/> if you want to build it yourself.

For all major platforms, you can download a binary **ActiveTcl**
distribution from
ActiveState.
Besides Tcl and Tk, this also contains many popular extensions - it\'s
called the canonical \"Batteries Included\" distribution.

Alternatively, you can get Tclkit: a
Tcl/Tk installation wrapped in a single file, which you don\'t need to
unwrap. When run, the file mounts itself as a virtual file system,
allowing access to all its parts.

January 2006, saw the release of a new and promising one-file vfs
distribution of Tcl; **eTcl**. Free binaries for Linux, Windows, and
Windows Mobile 2003 can be downloaded from
<http://www.evolane.com/software/etcl/index.html> . Especially on
PocketPCs, this provides several features that have so far been missing
from other ports: sockets, window \"retreat\", and can be extended by
providing a startup script, and by installing pure-Tcl libraries.

#### First steps

To see whether your installation works, you might save the following
text to a file *hello.tcl* and run it (type *tclsh hello.tcl* at a
console on Linux, double-click on Windows):

``` tcl
package require Tk
pack [label .l -text "Hello world!"]
```

It should bring up a little grey window with the greeting.

To make a script directly executable (on Unix/Linux, and Cygwin on
Windows), use this first line (the \# being flush left):

``` tcl
#!/usr/bin/env tclsh
```

or (in an older, deprecated tricky style):

``` tcl
#! /bin/sh
# the next line restarts using tclsh \
exec tclsh "$0" ${1+"$@"}
```

This way, the shell can determine which executable to run the script
with.

An even simpler way, and highly recommended for beginners as well as
experienced users, is to start up tclsh or wish interactively. You will
see a % prompt in the console, can type commands to it, and watch its
responses. Even error messages are very helpful here, and don\'t cause a
program abort - don\'t be afraid to try whatever you like! Example:

`$ tclsh`

``` tcl
info patchlevel
```

`8.4.12`

``` tcl
expr 6*7
```

`42`

``` tcl
expr 42/0
```

`divide by zero`

You can even write programs interactively, best as one-liners:

``` tcl
proc ! x {expr {$x<=2? $x: $x*[! [incr x -1]]}}
! 5
```

`120`

For more examples, see the chapter \"A quick tour\".

------------------------------------------------------------------------

### Syntax

Syntax is just the rules how a language is structured. A simple syntax
of English could say (ignoring punctuation for the moment):

-   A text consists of one or more sentences
-   A sentence consists of one or more words

Simple as this is, it also describes Tcl\'s syntax very well - if you
say \"script\" for \"text\", and \"command\" for \"sentence\". There\'s
also the difference that a Tcl word can again contain a script or a
command. So

``` tcl
if {$x < 0} {set x 0}
```

is a command consisting of three words: *if*, a condition in braces, a
command (also consisting of three words) in braces.

``` tcl
Take this for example
```

is a well-formed Tcl command: it calls *Take* (which must have been
defined before) with the three arguments \"this\", \"for\", and
\"example\". It is up to the command how it interprets its arguments,
e.g.

``` tcl
puts acos(-1)
```

will write the string \"acos(-1)\" to the stdout channel, and return the
empty string \"\", while

``` tcl
expr acos(-1)
```

will compute the arc cosine of -1 and return 3.14159265359 (an
approximation of *Pi*), or

``` tcl
string length acos(-1)
```

will invoke the *string* command, which again dispatches to its *length*
sub-command, which determines the length of the second argument and
returns 8.

#### Quick summary

A Tcl **script** is a string that is a sequence of commands, separated
by newlines or semicolons.

A **command** is a string that is a list of words, separated by blanks.
The first word is the name of the command, the other words are passed to
it as its arguments. In Tcl, *\"everything is a command\"* - even what
in other languages would be called declaration, definition, or control
structure. A command can interpret its arguments in any way it wants -
in particular, it can implement a different language, like *expr*.

A **word** is a string that is a simple word, or one that begins with {
and ends with the matching } (braces), or one that begins with \" and
ends with the matching \". Braced words are not evaluated by the parser.
In quoted words, substitutions can occur before the command is called:

-   \$\[A-Za-z0-9\_\]+ substitutes the value of the given variable. Or,
    if the variable name contains characters outside that regular
    expression, another layer of bracing helps the parser to get it
    right:

`puts "Guten Morgen, ${Schüler}!"`

If the code would say *\$Schüler*, this would be parsed as the value of
variable *\$Sch*, immediately followed by the constant string *üler*.

-   (Part of) a word can be an embedded script: a string in \[\]
    brackets whose contents are evaluated as a script (see above) before
    the current command is called.

In short: Scripts and commands contain words. Words can again contain
scripts and commands. (This can lead to words more than a page long\...)

Arithmetic and logic expressions are not part of the Tcl language
itself, but the language of the **expr** command (also used in some
arguments of the **if**, **for**, **while** commands) is basically
equivalent to C\'s expressions, with infix operators and functions. See
separate chapter on *expr* below.

------------------------------------------------------------------------

#### The man page: 11 rules

Here is the complete manpage for Tcl (8.4) with the \"endekalogue\", the
11 rules. (From 8.5 onward there is a twelfth rule regarding the {\*}
feature).

The following rules define the syntax and semantics of the Tcl language:

**(1) Commands** A Tcl script is a string containing one or more
commands. Semi-colons and newlines are command separators unless quoted
as described below. Close brackets are command terminators during
command substitution (see below) unless quoted.

**(2) Evaluation** A command is evaluated in two steps. First, the Tcl
interpreter breaks the command into words and performs substitutions as
described below. These substitutions are performed in the same way for
all commands. The first word is used to locate a command procedure to
carry out the command, then all of the words of the command are passed
to the command procedure. The command procedure is free to interpret
each of its words in any way it likes, such as an integer, variable
name, list, or Tcl script. Different commands interpret their words
differently.

**(3) Words** Words of a command are separated by white space (except
for newlines, which are command separators).

**(4) Double quotes** If the first character of a word is double-quote
(\") then the word is terminated by the next double-quote character. If
semi-colons, close brackets, or white space characters (including
newlines) appear between the quotes then they are treated as ordinary
characters and included in the word. Command substitution, variable
substitution, and backslash substitution are performed on the characters
between the quotes as described below. The double-quotes are not
retained as part of the word.

**(5) Braces** If the first character of a word is an open brace ({)
then the word is terminated by the matching close brace (}). Braces nest
within the word: for each additional open brace there must be an
additional close brace (however, if an open brace or close brace within
the word is quoted with a backslash then it is not counted in locating
the matching close brace). No substitutions are performed on the
characters between the braces except for backslash-newline substitutions
described below, nor do semi-colons, newlines, close brackets, or white
space receive any special interpretation. The word will consist of
exactly the characters between the outer braces, not including the
braces themselves.

**(6) Command substitution** If a word contains an open bracket (\[)
then Tcl performs command substitution. To do this it invokes the Tcl
interpreter recursively to process the characters following the open
bracket as a Tcl script. The script may contain any number of commands
and must be terminated by a close bracket (\]). The result of the script
(i.e. the result of its last command) is substituted into the word in
place of the brackets and all of the characters between them. There may
be any number of command substitutions in a single word. Command
substitution is not performed on words enclosed in braces.

**(7) Variable substitution** If a word contains a dollar-sign (\$) then
Tcl performs variable substitution: the dollar-sign and the following
characters are replaced in the word by the value of a variable. Variable
substitution may take any of the following forms:

\$name

Name is the name of a scalar variable; the name is a sequence of one or
more characters that are a letter, digit, underscore, or namespace
separators (two or more colons).

\$name(index)

Name gives the name of an array variable and index gives the name of an
element within that array. Name must contain only letters, digits,
underscores, and namespace separators, and may be an empty string.
Command substitutions, variable substitutions, and backslash
substitutions are performed on the characters of index.

\${name}

Name is the name of a scalar variable. It may contain any characters
whatsoever except for close braces. There may be any number of variable
substitutions in a single word. Variable substitution is not performed
on words enclosed in braces.

**(8) Backslash substitution** If a backslash (\\) appears within a word
then backslash substitution occurs. In all cases but those described
below the backslash is dropped and the following character is treated as
an ordinary character and included in the word. This allows characters
such as double quotes, close brackets, and dollar signs to be included
in words without triggering special processing. The following table
lists the backslash sequences that are handled specially, along with the
value that replaces each sequence.

\\a
:   Audible alert (bell) (0x7).

\\b
:   Backspace (0x8).

\\f
:   Form feed (0xc).

\\n
:   Newline (0xa).

\\r
:   Carriage-return (0xd).

\\t
:   Tab (0x9).

\\v
:   Vertical tab (0xb).

\\`<newline>`{=html}whiteSpace
:   A single space character replaces the backslash, newline, and all
    spaces and tabs after the newline. This backslash sequence is unique
    in that it is replaced in a separate pre-pass before the command is
    actually parsed. This means that it will be replaced even when it
    occurs between braces, and the resulting space will be treated as a
    word separator if it isn\'t in braces or quotes.

\\\\
:   Literal backslash (\\), no special effect.

\\ooo
:   The digits ooo (one, two, or three of them) give an eight-bit octal
    value for the Unicode character that will be inserted. The upper
    bits of the Unicode character will be 0.

\\xhh
:   The hexadecimal digits hh give an eight-bit hexadecimal value for
    the Unicode character that will be inserted. Any number of
    hexadecimal digits may be present; however, all but the last two are
    ignored (the result is always a one-byte quantity). The upper bits
    of the Unicode character will be 0.

\\uhhhh
:   The hexadecimal digits hhhh (one, two, three, or four of them) give
    a sixteen-bit hexadecimal value for the Unicode character that will
    be inserted.

Backslash substitution is not performed on words enclosed in braces,
except for backslash-newline as described above.

**(9) Comments** If a hash character (#) appears at a point where Tcl is
expecting the first character of the first word of a command, then the
hash character and the characters that follow it, up through the next
newline, are treated as a comment and ignored. The comment character
only has significance when it appears at the beginning of a command.

**(10) Order of substitution** Each character is processed exactly once
by the Tcl interpreter as part of creating the words of a command. For
example, if variable substitution occurs then no further substitutions
are performed on the value of the variable; the value is inserted into
the word verbatim. If command substitution occurs then the nested
command is processed entirely by the recursive call to the Tcl
interpreter; no substitutions are performed before making the recursive
call and no additional substitutions are performed on the result of the
nested script. Substitutions take place from left to right, and each
substitution is evaluated completely before attempting to evaluate the
next. Thus, a sequence like

``` tcl
set y [set x 0][incr x][incr x]
```

will always set the variable y to the value, 012.

**(11) Substitution and word boundaries** Substitutions do not affect
the word boundaries of a command. For example, during variable
substitution the entire value of the variable becomes part of a single
word, even if the variable\'s value contains spaces.

#### Comments

The first rule for comments is simple: comments start with \# where the
first word of a command is expected, and continue to the end of line
(which can be extended, by a trailing backslash, to the following line):

``` tcl
# This is a comment \
going over three lines \
with backslash continuation
```

One of the problems new users of Tcl meet sooner or later is that
comments behave in an unexpected way. For example, if you comment out
part of code like this:

``` tcl
# if {$condition} {
    puts "condition met!"
# }
```

This happens to work, but any unbalanced braces in comments may lead to
unexpected syntax errors. The reason is that Tcl\'s grouping
(determining word boundaries) happens before the \# characters are
considered.

To add a comment behind a command on the same line, just add a
semicolon:

``` tcl
puts "this is the command" ;# that is the comment
```

Comments are only taken as such where a command is expected. In data
(like the comparison values in **switch**), a \# is just a literal
character:

``` tcl
if $condition {# good place
   switch -- $x {
       #bad_place {because switch tests against it}
       some_value {do something; # good place again}
   }
}
```

To comment out multiple lines of code, it is easiest to use \"if 0\":

``` tcl
if 0 {
    puts "This code will not be executed"
    This block is never parsed, so can contain almost any code
    - except unbalanced braces :)
}
```

### Data types

In Tcl, all values are strings, and the phrase \"**Everything is a
string**\" is often used to illustrate this fact. But just as `2` can be
interpreted in English as \"the number 2\" or \"the character
representing the number 2\", two different functions in Tcl can
interpret the same value in two different ways. The command `expr`, for
example, interprets \"2\" as a number, but the command `string length`
interprets \"2\" as a single character. All values in Tcl can be
interpreted either as characters or something else that the characters
represent. The important thing to remember is that every value in Tcl is
a string of characters, and each string of characters might be
interpreted as something else, depending on the context. This will
become more clear in the examples below. For performance reasons,
versions of Tcl since 8.0 keep track of both the string value and how
that string value was last interpreted. This section covers the various
\"types\" of things that Tcl values (strings) get interpreted as.

#### Strings

A string is a sequence of zero or more characters (where all 16-bit
Unicodes are accepted in almost all situations, see in more detail
below). The size of strings is automatically administered, so you only
have to worry about that if the string length exceeds the virtual memory
size.

In contrast to many other languages, strings in Tcl don\'t need quotes
for markup. The following is perfectly valid:

``` tcl
set greeting Hello!
```

Quotes (or braces) are rather used for grouping:

``` tcl
set example "this is one word"
set another {this is another}
```

The difference is that inside quotes, substitutions (like of variables,
embedded commands, or backslashes) are performed, while in braces, they
are not (similar to single quotes in shells, but nestable):

``` tcl
set amount 42
puts "You owe me $amount" ;#--> You owe me 42
puts {You owe me $amount} ;#--> You owe me $amount
```

In source code, quoted or braced strings can span multiple lines, and
the physical newlines are part of the string too:

``` tcl
set test "hello
world
in three lines"
```

To **reverse a string**, we let an index *i* first point at its end, and
decrementing *i* until it\'s zero, append the indexed character to the
end of the result *res*:

``` tcl
proc sreverse str {
set res ""
for {set i [string length $str]} {$i > 0} {} {
    append res [string index $str [incr i -1]]
}
set res
}

sreverse "A man, a plan, a canal - Panama"
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
amanaP - lanac a ,nalp a ,nam A
```

```{=html}
</dd>
```
```{=html}
</dl>
```
**Hex-dumping** a string:

``` tcl
proc hexdump string {
    binary scan $string H* hex
    regexp -all -inline .. $hex
}

hexdump hello
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
68 65 6c 6c 6f
```

```{=html}
</dd>
```
```{=html}
</dl>
```
**Finding a substring** in a string can be done in various ways:

``` tcl
string first  $substr  $str ;# returns the position from 0, or -1 if not found
```

``` tcl
string match *$substr* $str ;# returns 1 if found, 0 if not
```

``` tcl
regexp $substr  $str ;# the same
```

The matching is done with exact match in *string first*, with glob-style
match in *string match*, and as a regular expression in *regexp*. If
there are characters in *substr* that are special to *glob* or regular
expressions, using *string first* is recommended.

#### Lists

Many strings are also well-formed **lists**. Every simple word is a list
of length one, and elements of longer lists are separated by whitespace.
For instance, a string that corresponds to a list of three elements:

``` tcl
set example {foo bar grill}
```

Strings with unbalanced quotes or braces, or non-space characters
directly following closing braces, cannot be parsed as lists directly.
You can explicitly **split** them to make a list.

The \"constructor\" for lists is of course called *list*. It\'s
recommended to use when elements come from variable or command
substitution (braces won\'t do that). As Tcl commands are lists anyway,
the following is a full substitute for the *list* command:

``` tcl
proc list args {set args}
```

Lists can contain lists again, to any depth, which makes modelling of
matrixes and trees easy. Here\'s a string that represents a 4 x 4 unit
matrix as a list of lists. The outer braces group the entire thing into
one string, which includes the literal inner braces and whitespace,
including the literal newlines. The list parser then interprets the
inner braces as delimiting nested lists.

``` tcl
{{1 0 0 0}
 {0 1 0 0}
 {0 0 1 0}
 {0 0 0 1}}
```

The newlines are valid list element separators, too.

Tcl\'s list operations are demonstrated in some examples:

``` tcl
set      x {foo bar}
llength  $x        ;#--> 2
lappend  x  grill  ;#--> foo bar grill
lindex   $x 1      ;#--> bar (indexing starts at 0)
lsearch  $x grill  ;#--> 2 (the position, counting from 0)
lsort    $x        ;#--> bar foo grill
linsert  $x 2 and  ;#--> foo bar and grill
lreplace $x 1 1 bar, ;#--> foo bar, grill
```

Note that only **lappend**, above is mutating. To change an element of a
list (of a list\...) in place, the **lset** command is useful - just
give as many indexes as needed:

``` tcl
set test {{a b} {c d}}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
{a b} {c d}
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
lset test 1 1 x
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
{a b} {c x}
```

```{=html}
</dd>
```
```{=html}
</dl>
```
The **lindex** command also takes multiple indexes:

``` tcl
lindex $test 1 1
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
x
```

```{=html}
</dd>
```
```{=html}
</dl>
```
Example: To find out whether an element is contained in a list (from Tcl
8.5, there\'s the **in** operator for that):

``` tcl
proc in {list el} {expr {[lsearch -exact $list $el] >= 0}}
in {a b c} b
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
1
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
in {a b c} d
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
#ignore this line, which is only here because there is currently a bug in wikibooks rendering which makes the 0 on the following line disappear when it is alone
0
```

```{=html}
</dd>
```
```{=html}
</dl>
```
Example: remove an element from a list variable by value (converse to
lappend), if present:

``` tcl
proc lremove {_list el} {
  upvar 1 $_list list
  set pos [lsearch -exact $list $el]
  set list [lreplace $list $pos $pos]
}

set t {foo bar grill}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
foo bar grill
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
lremove t bar
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
foo grill
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
set t
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
foo grill
```

```{=html}
</dd>
```
```{=html}
</dl>
```
A simpler alternative, which also removes all occurrences of *el*:

``` tcl
proc lremove {_list el} {
  upvar 1 $_list list
  set list [lsearch -all -inline -not -exact $list $el]
}
```

Example: To draw a random element from a list L, we first determine its
length (using *llength*), multiply that with a random number \> 0.0 and
\< 1.0, truncate that to integer (so it lies between 0 and length-1),
and use that for indexing (*lindex*) into the list:

``` tcl
proc ldraw L {
   lindex $L [expr {int(rand()*[llength $L])}]
}
```

Example: Transposing a matrix (swapping rows and columns), using
integers as generated variable names:

``` tcl
proc transpose matrix {
   foreach row $matrix {
       set i 0
       foreach el $row {lappend [incr i] $el}
   }
   set res {}
   set i 0
   foreach e [lindex $matrix 0] {lappend res [set [incr i]]}
   set res
}

transpose {{1 2} {3 4} {5 6}}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
{1 3 5} {2 4 6}
```

```{=html}
</dd>
```
```{=html}
</dl>
```
Example: pretty-printing a list of lists which represents a table:

``` tcl
proc fmtable table {
   set maxs {}
   foreach item [lindex $table 0] {
       lappend maxs [string length $item]
   }
   foreach row [lrange $table 1 end] {
       set i 0
       foreach item $row max $maxs {
           if {[string length $item]>$max} {
               lset maxs $i [string length $item]
           }
           incr i
       }
   }
   set head +
   foreach max $maxs {append head -[string repeat - $max]-+}
   set res $head\n
   foreach row $table {
       append res |
       foreach item $row max $maxs {append res [format " %-${max}s |" $item]}
       append res \n
   }
   append res $head
}
```

Testing:

``` tcl
fmtable {
   {1 short "long field content"}
   {2 "another long one" short}
   {3 "" hello}
}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
+---+------------------+--------------------+
| 1 | short            | long field content |
| 2 | another long one | short              |
| 3 |                  | hello              |
+---+------------------+--------------------+
```

```{=html}
</dd>
```
```{=html}
</dl>
```
**Enumerations:** Lists can also be used to implement enumerations
(mappings from symbols to non-negative integers). Example for a nice
wrapper around lsearch/lindex:

``` tcl
proc makeEnum {name values} {
   interp alias {} $name: {} lsearch $values
   interp alias {} $name@ {} lindex $values
}

makeEnum fruit {apple blueberry cherry date elderberry}
```

This assigns \"apple\" to 0, \"blueberry\" to 1, etc.

``` tcl
fruit: date
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
3
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
fruit@ 2
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
cherry
```

```{=html}
</dd>
```
```{=html}
</dl>
```
#### Numbers

Numbers are strings that can be parsed as such. Tcl supports integers
(32-bit or even 64-bit wide) and \"double\" floating-point numbers. From
Tcl 8.5 on, bignums (integers of arbitrarily large precision) are
supported. Arithmetics is done with the **expr** command, which takes
basically the same syntax of operators (including ternary *x?y:z*),
parens, and math functions as C. See below for detailed discussion of
*expr*.

Control the display format of numbers with the **format** command which
does appropriate rounding:

``` tcl
expr 2/3.
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
0.666666666667
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
format %.2f [expr 2/3.]
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
0.67
```

```{=html}
</dd>
```
```{=html}
</dl>
```
Up to the 8.4 version (the present version is 8.5), Tcl honored the C
convention that an integer starting with 0 is parsed as octal, so

`0377 == 0xFF == 255`

This changes in 8.5, though - too often people stumbled over \"08\"
meant as hour or month, raised a syntax error, because 8 is no valid
octal number. In the future you\'d have to write 0o377 if you really
mean octal. You can do number base conversions with the *format*
command, where the format is %x for hex, %d for decimal, %o for octal,
and the input number should have the C-like markup to indicate its base:

``` tcl
format %x 255
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` tcl
ff
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
format %d 0xff
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` tcl
255
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
format %o 255
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
377
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
format %d 0377
```

```{=html}
<dl>
```
```{=html}
<dd>
```
:

``` text
255
```

```{=html}
</dd>
```
```{=html}
</dl>
```
Variables with integer value can be most efficiently modified with the
*incr* command:

``` tcl
incr i    ;# default increment is 1
incr j 2
incr i -1 ;# decrement with negative value
incr j $j ;# double the value
```

The maximal positive integer can be determined from the hexadecimal
form, with a 7 in front, followed by several \"F\" characters. Tcl 8.4
can use \"wide integers\" of 64 bits, and the maximum integer there is

``` tcl
expr 0x7fffffffffffffff
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
9223372036854775807
```

```{=html}
</dd>
```
```{=html}
</dl>
```
Demonstration: one more, and it turns into the minimum integer:

``` tcl
expr 0x8000000000000000
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
-9223372036854775808
```

```{=html}
</dd>
```
```{=html}
</dl>
```
**Bignums**: from Tcl 8.5, integers can be of arbitrary size, so there
is no maximum integer anymore. Say, you want a big factorial:

``` tcl
proc tcl::mathfunc::fac x {expr {$x < 2? 1: $x * fac($x-1)}}

expr fac(100)
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
```

```{=html}
</dd>
```
```{=html}
</dl>
```
**IEEE special floating-point values**: Also from 8.5, Tcl supports a
few special values for floating-point numbers, namely *Inf* (infinity)
and *NaN* (Not a Number):

``` tcl
set i [expr 1/0.]
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
Inf
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
expr {$i+$i}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
Inf
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
expr {$i+1 == $i}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
1
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
set j NaN ;# special because it isn't equal to itself
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
NaN
```

```{=html}
</dd>
```
```{=html}
</dl>
```
``` tcl
expr {$j == $j}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
#ignore this line, which is only here because there is currently a bug in wikibooks rendering which makes the 0 on the following line disappear when it is alone
0
```

```{=html}
</dd>
```
```{=html}
</dl>
```
#### Booleans

Tcl supports booleans as numbers in a similar fashion to C, with 0 being
false and any other number being true. It also supports them as the
strings \"true\", \"false\", \"yes\" and \"no\" and few others (see
below). The canonical \"true\" value (as returned by Boolean
expressions) is 1.

``` tcl
foreach b {0 1 2 13 true false on off no yes n y a} {puts "$b -> [expr {$b?1:0}]"}
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
0 -> 0
1 -> 1
2 -> 1
13 -> 1
true -> 1
false -> 0
on -> 1
off -> 0
no -> 0
yes -> 1
n -> 0
y -> 1
expected boolean value but got "a"
```

```{=html}
</dd>
```
```{=html}
</dl>
```
#### Characters

Characters are abstractions of writing elements (e.g. letters, digits,
punctuation characters, Chinese ideographs, ligatures\...). In Tcl since
8.1, characters are internally represented with Unicode, which can be
seen as unsigned integers between 0 and 65535 (recent Unicode versions
have even crossed that boundary, but the Tcl implementation currently
uses a maximum of 16 bits). Any Unicode U+XXXX can be specified as a
character constant with an \\uXXXX escape. It is recommended to only use
ASCII characters (\\u0000-\\u007f) in Tcl scripts directly, and escape
all others.

Convert between numeric Unicode and characters with

``` tcl
set char [format %c $int]
set int  [scan $char %c]
```

Watch out that int values above 65535 produce \'decreasing\' characters
again, while negative int even produces two bogus characters. format
does not warn, so better test before calling it.

Sequences of characters are called strings (see above). There is no
special data type for a single character, so a single character is just
a string on length 1 (everything is a string). In UTF-8, which is used
internally by Tcl, the encoding of a single character may take from one
to three bytes of space. To determine the bytelength of a single
character:

``` tcl
string bytelength $c ;# assuming [string length $c]==1
```

String routines can be applied to single characters too, e.g \[string
toupper\] etc. Find out whether a character is in a given set (a
character string) with

``` tcl
expr {[string first $char $set]>=0}
```

As Unicodes for characters fall in distinct ranges, checking whether a
character\'s code lies within a range allows a more-or-less rough
classification of its category:

``` tcl
proc inRange {from to char} {
    # generic range checker
    set int [scan $char %c]
    expr {$int>=$from && $int <= $to}
}
interp alias {} isGreek {}    inRange 0x0386 0x03D6
interp alias {} isCyrillic {} inRange 0x0400 0x04F9
interp alias {} isHangul {}   inRange 0xAC00 0xD7A3
```

This is a useful helper to convert all characters beyond the ASCII set
to their \\u\.... escapes (so the resulting string is strict ASCII):

``` tcl
proc u2x s {
   set res ""
   foreach c [split $s ""] {
     scan $c %c int
     append res [expr {$int<128? $c :"\\u[format %04.4X $int]"}]
   }
   set res
}
```

#### Internal representation

In the main Tcl implementation, which is written in C, each value has
both a string representation (UTF-8 encoded) and a structured
representation. This is an implementation detail which allows for better
performance, but has no semantic impact on the language. Tcl tracks both
representations, making sure that if one is changed, the other one is
updated to reflect the change the next time it is used. For example, if
the string representation of a value is \"8\", and the value was last
used as a number in an \[expr\] command, the structured representation
will be a numeric type like a signed integer or a double-precision
floating point number. If the value \"one two three\" was last used in
one of the list commands, the structured representation will be a list
structure. There are various other \"types\" on the C side which may be
used as the structured representation. As of Tcl 8.5, only the most
recent structured representation of a value is stored, and it is
replaced with a different representation when necessary. This
\"dual-porting\" of values helps avoid, repeated parsing or
\"stringification\", which otherwise would happen often because each
time a value is encountered in source code, it is interpreted as a
string prior to being interpreted in its current context. But to the
programmer, the view that \"everything is a string\" is still
maintained.

These values are stored in reference-counted structures termed objects
(a term that has many meanings). From the perspective of all code that
uses values (as opposed to code implementing a particular
representation), they are immutable. In practice, this is implemented
using a copy-on-write strategy.

### Variables

Variables can be local or global, and scalar or array. Their names can
be any string not containing a colon (which is reserved for use in
namespace separators) but for the convenience of \$-dereference one
usually uses names of the pattern \[A-Za-z0-9\_\]+, i.e. one or more
letters, digits, or underscores.

Variables need not be declared beforehand. They are created when first
assigned a value, if they did not exist before, and can be unset when no
longer needed:

``` tcl
set foo    42     ;# creates the scalar variable foo
set bar(1) grill  ;# creates the array bar and its element 1
set baz    $foo   ;# assigns to baz the value of foo
set baz [set foo] ;# the same effect
info exists foo   ;# returns 1 if the variable foo exists, else 0
unset foo         ;# deletes the variable foo
```

Retrieving a variable\'s value with the \$foo notation is only syntactic
sugar for \[set foo\]. The latter is more powerful though, as it can be
nested, for deeper dereferencing:

``` tcl
set foo   42
set bar   foo
set grill bar
puts [set [set [set grill]]] ;# gives 42
```

Some people might expect *\$\$\$grill* to deliver the same result, but
it doesn\'t, because of the Tcl parser. When it encounters the first and
second \$ sign, it tries to find a variable name (consisting of one or
more letters, digits, or underscores) in vain, so these \$ signs are
left literally as they are. The third \$ allows substitution of the
variable *grill*, but no backtracking to the previous \$\'s takes place.
So the evaluation result of *\$\$\$grill* is *\$\$bar*. Nested \[set\]
commands give the user more control.

#### Local vs. global

A local variable exists only in the procedure where it is defined, and
is freed as soon as the procedure finishes. By default, all variables
used in a proc are local.

Global variables exist outside of procedures, as long as they are not
explicitly unset. They may be needed for long-living data, or implicit
communication between different procedures, but in general it\'s safer
and more efficient to use globals as sparingly as possible. Example of a
very simple bank with only one account:

``` tcl
 set balance 0 ;# this creates and initializes a global variable

 proc deposit {amount} {
    global balance
    set balance [expr {$balance + $amount}]
 }

 proc withdraw {amount} {
    set ::balance [expr {$::balance - $amount}]
 }
```

This illustrates two ways of referring to global variables - either with
the **global** command, or by qualifying the variable name with the ::
prefix. The variable *amount* is local in both procedures, and its value
is that of the first argument to the respective procedure.

Introspection:

``` tcl
info vars ;#-- lists all visible variables
info locals
info globals
```

To make all global variables visible in a procedure (not recommended):

``` tcl
eval global [info globals]
```

#### Scalar vs. array

All of the value types discussed above in *Data types* can be put into a
scalar variable, which is the normal kind.

Arrays are collections of variables, indexed by a key that can be any
string, and in fact implemented as hash tables. What other languages
call \"arrays\" (vectors of values indexed by an integer), would in Tcl
rather be lists. Some illustrations:

``` tcl
#-- The key is specified in parens after the array name
set         capital(France) Paris

#-- The key can also be substituted from a variable:
set                  country France
puts       $capital($country)

#-- Setting several elements at once:
array set   capital         {Italy Rome  Germany Berlin}

#-- Retrieve all keys:
array names capital    ;#-- Germany Italy France -- quasi-random order

#-- Retrieve keys matching a glob pattern:
array names capital F* ;#-- France
```

A fanciful array name is \"\" (the empty string, therefore we might call
this the \"anonymous array\" :) which makes nice reading:

``` tcl
set (example) 1
puts $(example)
```

Note that arrays themselves are not values. They can be passed in and
out of procedures not as *\$capital* (which would try to retrieve the
value), but by reference. The **dict** type (available from Tcl 8.5)
might be better suited for these purposes, while otherwise providing
hash table functionality, too.

#### System variables

At startup, tclsh provides the following global variables:

argc : number of arguments on the command line\
argv : list of the arguments on the command line\
argv0 : name of the executable or script (first word on command line)\
auto_index : array with instructions from where to load further commands\
auto_oldpath : (same as auto_path ?)\
auto_path : list of paths to search for packages\
env : array, mirrors the environment variables\
errorCode : type of the last error, or {}, e.g. ARITH DIVZERO {divide by zero}\
errorInfo : last error message, or {}\
tcl_interactive : 1 if interpreter is interactive, else 0\
tcl_libPath : list of library paths\
tcl_library : path of the Tcl system library directory\
tcl_patchLevel : detailed version number, e.g. 8.4.11\
tcl_platform : array with information on the operating system\
tcl_rcFileName : name of the initial resource file\
tcl_version : brief version number, e.g. 8.4

One can use temporary environment variables to control a Tcl script from
the command line, at least in Unixoid systems including Cygwin. Example
scriptlet:

``` tcl
set foo 42
if [info exists env(DO)] {eval $env(DO)}
puts foo=$foo
```

This script will typically report

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
 foo=42
```

```{=html}
</dd>
```
```{=html}
</dl>
```
To remote-control it without editing, set the DO variable before the
call:

``` bash
DO='set foo 4711' tclsh myscript.tcl
```

which will evidently report

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
foo=4711
```

```{=html}
</dd>
```
```{=html}
</dl>
```
#### Dereferencing variables

A *reference* is something that refers, or points, to another something
(if you pardon the scientific expression). In C, references are done
with \*pointers\* (memory addresses); in Tcl, references are strings
(everything is a string), namely names of variables, which via a hash
table can be resolved (dereferenced) to the \"other something\" they
point to:

``` tcl
puts foo       ;# just the string foo
puts $foo      ;# dereference variable with name of foo
puts [set foo] ;# the same
```

This can be done more than one time with nested set commands. Compare
the following C and Tcl programs, that do the same (trivial) job, and
exhibit remarkable similarity:

``` c
#include <stdio.h>
int main(void) {
  int    i =      42;
  int *  ip =     &i;
  int ** ipp =   &ip;
  int ***ippp = &ipp;
  printf("hello, %d\n", ***ippp);
  return 0;
}
```

\...and Tcl:

``` tcl
set i    42
set ip   i
set ipp  ip
set ippp ipp
puts "hello, [set [set [set [set ippp]]]]"
```

The asterisks in C correspond to calls to `set` in Tcl dereferencing.
There is no corresponding operator to the C `&` because, in Tcl, special
markup is not needed in declaring references. The correspondence is not
perfect; there are four `set` calls and only three asterisks. This is
because mentioning a variable in C is an implicit dereference. In this
case, the dereference is used to pass its value into printf. Tcl makes
all four dereferences explicit (thus, if you only had 3 set calls,
you\'d see hello, i). A single dereference is used so frequently that it
is typically abbreviated with \$varname, e.g.

``` tcl
puts "hello, [set [set [set $ippp]]]"
```

has set where C uses asterisks, and \$ for the last (default)
dereference.

The hashtable for variable names is either global, for code evaluated in
that scope, or local to a proc. You can still \"import\" references to
variables in scopes that are \"higher\" in the call stack, with the
upvar and global commands. (The latter being automatic in C if the names
are unique. If there are identical names in C, the innermost scope
wins).

#### Variable traces

One special feature of Tcl is that you can associate traces with
variables (scalars, arrays, or array elements) that are evaluated
optionally when the variable is read, written to, or unset.

Debugging is one obvious use for that. But there are more possibilities.
For instance, you can introduce constants where any attempt to change
their value raises an error:

``` tcl
proc const {name value} {
  uplevel 1 [list set $name $value]
  uplevel 1 [list trace var $name w {error constant ;#} ]
}

const x 11
incr x
```

```{=html}
<dl>
```
```{=html}
<dd>
```
``` text
can't set "x": constant
```

```{=html}
</dd>
```
```{=html}
</dl>
```
The trace callback gets three words appended: the name of the variable;
the array key (if the variable is an array, else \"\"), and the mode:

-   r - read
-   w - write
-   u - unset

If the trace is just a single command like above, and you don\'t want to
handle these three, use a comment \";#\" to shield them off.

Another possibility is tying local objects (or procs) with a variable -
if the variable is unset, the object/proc is destroyed/renamed away.