Scope/Function names and labels: Difference between revisions

m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
(One intermediate revision by one other user not shown)
Line 1,197:
 
The shell does not support the use of arbitrary line labels.
 
=={{header|V (Vlang)}}==
Vlang has both functions and labels.
 
A function definition, either a top level declaration or a function literal, represents a function block.
<syntaxhighlight lang="Vlang">
fn world() {
print("World!")
}
 
fn main() {
 
// anonymous function
f := fn() {
print("Hello ")
}
f() // "Hello
world() // World!"
 
// "Hello World!"
}
</syntaxhighlight>
Functions can be used before their declaration (below main), but can still be called from main.
 
This eliminates the need for header files or worrying about the order.
<syntaxhighlight lang="Vlang">
fn main() {
println(add(77, 33))
println(sub(100, 50))
}
 
fn add(x int, y int) int {
return x + y
}
 
fn sub(x int, y int) int {
return x - y
}
</syntaxhighlight>
Functions are private (not exported) by default. To allow other modules to use them, prepend pub
<syntaxhighlight lang="Vlang">
pub fn public_function() {
}
 
fn private_function() {
}
</syntaxhighlight>
Labelled break & continue:
 
You can also use break and continue followed by a label name to refer to an outer for loop.
<syntaxhighlight lang="Vlang">
outer: for i := 4; true; i++ {
println(i)
for {
if i < 7 {
continue outer
} else {
break outer
}
}
}
</syntaxhighlight>
Goto and labels:
 
1) The label name must be contained within the same function as the 'goto' statement.
 
2) Used only with 'unsafe' statements.
<syntaxhighlight lang="Vlang">
// Unsafe 'goto' pseudo example:
if x {
// ...
if y {
unsafe {
goto my_label
}
}
// ...
}
my_label:
</syntaxhighlight>
 
=={{header|Wren}}==
Line 1,206 ⟶ 1,286:
 
The following example illustrates these points.
<syntaxhighlight lang="ecmascriptwren">//func.call() /* invalid, can't call func before its declared */
 
var func = Fn.new { System.print("func has been called.") }
Line 1,228 ⟶ 1,308:
 
(with line 1 uncommented)
[./scope_function_namesScope_Function_names_and_labels line 3] Error at '}': Variable 'func' referenced before this definition (first use at line 1).
 
(with only line 7 uncommented)
func has been called.
Null does not implement 'init()'.
[./scope_function_namesScope_Function_names_and_labels line 7] in (script)
</pre>
 
9,485

edits