문제

I've been writing a bit in a dialect of BASIC that has user-defined functions which can only access local variables; for example, the following code:

let S$ = "Hello, world!"

fn.def someFunction$()
    print S$
    fn.rtn "a string"
fn.end

X$ = someFunction$()

would print a blank line, because S$ does not have a value in the context of someFunction$.

The question: are there other languages in common use that have global scope which cannot be accessed from inside a function?

도움이 되었습니까?

해결책

The basis of this question is a misunderstanding. This dialect of Basic, like most others, does not have a global scope. There are many languages in the same category.

First an explanation. Many early computer languages had a single scope in which all variables were defined. When this became too limiting they added a subroutine capability which either shared the same scope (COBOL PERFORM and BASIC GOSUB) or defined a completely separate scope with argument passing (FORTRAN CALL and RETURN).

One language was different: Algol. It defined nested lexical scope, so that a reference to a variable could be within block or to an outer nested block. This was an unusual feature and not widely copied.

Fortran also provide a linkage mechanism called COMMON. This was adopted by some other languages. C added block scope, external scope (with external linkage), but not nested functions, so functions can never access variables from another function's scope.

The dialect of Basic you are asking about belongs to the Basic/Fortran family. It has non-overlapping scopes for each of the main program and user-defined functions, but apparently no external linkage. Regardless of how they are written, user-defined functions have their own scope and of course they cannot access variables in the main program, which is in a quite different scope. Some dialects of Basic have a COMMON-like feature, but I don't think this one does.

So the answer is that most languages (of this kind) do not provide nested scopes and do not allow an inner scope to access the contents of an outer one. [The Lisp family tree is quite different, of course.]

There is one interesting exception. Object-oriented languages mostly derive from Simula which was a Pascal-like language and introduced the idea of nesting the method cope inside the class scope. That idea has definitely caught on.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top