06.07.2013 Views

Scilab Bag Of Tricks - Claymore

Scilab Bag Of Tricks - Claymore

Scilab Bag Of Tricks - Claymore

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7.<br />

->a<br />

a =<br />

3.<br />

Obviously, a is unchanged by the calls to baz. What happens is the following:<br />

Chapter 2. Pitfalls<br />

1. A local variable named a is created, and the contents of a from the enclosing scope is copied<br />

into it. Within baz the local a is changed.<br />

2. When the thread of control leaves baz the previous value of a is restored.<br />

In other words: A local variable cannot influence a variable of the same name in any enclosing<br />

scope. The only ways to “export” a – possibly modified – value is either via the list of return values,<br />

which is the preferred way, or with a global variable.<br />

As strange as this may sound to programmers accustomed to languages that require an explicit<br />

declaration of all variables, this is a necessary feature in <strong>Scilab</strong> as variables are created when they are<br />

first written to (e.g. as in Perl and Python). If a local variable in a function would change a global<br />

variable or local variable of the same name in another function, adding a new function to an existing<br />

system or library became a major maintenance headache.<br />

2.5.2. Global Variables<br />

The global attribute of a variable var is often misunderstood. It does not place var in an all<br />

encompassing name space so that it could be accessed from everywhere without further ado. Instead,<br />

global places the variable var in a separate name space; separate from the interpreter’s name<br />

space, and separate from all local functions’ name spaces. — And this is only the first half of the<br />

story.<br />

->v = -1<br />

v =<br />

- 1.<br />

->global(’v’)<br />

->who(’global’)<br />

ans =<br />

v<br />

->clear v<br />

->who(’global’)<br />

ans =<br />

v<br />

->deff(’y = useglobal()’, ’y = v’)<br />

26

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!