Scope/Function names and labels: Difference between revisions

→‎{{header|Wren}}: Wasn't quite right before.
(→‎{{header|Wren}}: Wasn't quite right before.)
Line 1,303:
Firstly, Wren doesn't support labels at all.
 
Secondly, functions (as opposed to methods) are first-class objects and have the same visibility as any other object. In other words, when defineddeclared in a particular scope, they are visible from the point of declaration to the end of that scope (but see below).
 
On the other hand, methods are always public members of a class and are visible throughout that class. Although technically a top-level class is visible throughout the module in which its defined, it is null prior to its definition.
 
Technically if a class, function or other object is declared at top-level and its name begins with a capital letter, then it is visible throughout the module in which it's declared and not just from the point of declaration. However, it is null if referenced prior to its definition.
 
By convention classes in Wren begin with a capital letter and so top-level classes are always visible throughout the module. So too are capitalized top-level functions which avoids the need for forward declaration in recursive or mutually recursive scenarios.
 
The following example illustrates these points.
<syntaxhighlight lang="wren">// func.call() /* invalid, can't call func before its declareddefined */
 
var func = Fn.new { System.print("func has been called.") }
Line 1,317 ⟶ 1,321:
 
class C {
static init() { method() } // fine even though 'method' not yet declareddefined
static method() { System.print("method has been called.") }
}
 
C.init() // fine</syntaxhighlight>
 
/* Although this function is recursive, there is no need for a forward
declaration as it is top-level and begins with a capital letter. */
var Fib = Fn.new { |n|
if (n < 2) return n
return Fib.call(n-1) + Fib.call(n-2) // Fib already visible here
}
 
Fib.call(3) // fine</syntaxhighlight>
 
{{out}}
Line 1,328 ⟶ 1,341:
func has been called.
method has been called.
21
 
(with line 1 uncommented)
9,490

edits