In the first place, there are two types of scopes.
Each is a variable reference specification, and lexical scope is adopted in many major languages such as Ruby, Java, Javascript, and python.
It's very simple. See the code below.
var = 'I'm top level'
def a_method
return var
end
def b_method
var = 'I am the contents of the object'
return var
end
a_method
#-> 'I'm top level'
It is natural to write Ruby etc., but you cannot refer to var of b_method from a_method.
This is the ``` lexical scope
" ... !!!
However, it seems that there are languages in the world where the scope of variables is determined when a function is evaluated.
It seems that they are called dynamic scopes, but for example Lisp and Emacs seem to adopt those scopes.
This is not Ruby. Dynamic Ruby that uses a Ruby-like dynamic scope. (There is no such thing, but it is a coined word.)
def a_method
p var
end
def b_method
var = 'I'm B'
a_method
end
def c_method
a_method
end
b_method
#-> 'I'm B'
c_method
#-> undefined variable 'var'
Will be. That is, the scope is determined when you evaluate the *** function, not when you define the function. *** ***
It seems easy to implement the language w Why did Lisp, Emacs, etc. adopt it? It seems that it is written that way. Lol
Recommended Posts