Functions and Errors
Scope
Local Names
Function arguments are local to the function call. Reusing a name inside the function does not overwrite the outer value.
Program
Play the script to see outer x stay 5 while the function uses its own x.
scope.R
Replay: real traced execution (multi-file project)
x <- 5
bump <- function(x) { x + 1 }
inside <- bump(10)
label <- paste(x, inside, sep = ":")
cat(label, "\n", sep = "")
x ← 5
1x <- 52bump <- function(x) { x + 1 }values this step5xbump ← function(x)
1x <- 52bump <- function(x) { x + 1 }3inside <- bump(10)values this stepfunction(x)bumpinside ← 11
2bump <- function(x) { x + 1 }3inside <- bump(10)4label <- paste(x, inside, sep = ":")values this step11inside10argument xlabel ← 5:11
3inside <- bump(10)4label <- paste(x, inside, sep = ":")5cat(label, "\n", sep = "")values this step5:11label5x11insidecat(label, " ", sep = "")
4label <- paste(x, inside, sep = ":")5cat(label, "\n", sep = "")output5:11values this step5:11label
Follow the Names
- The outer
xstarts as5. bump(10)passes10as the function's local argumentx.- Inside the call, local
x + 1gives11. insidestores11.paste(x, inside, sep = ":")uses outerxandinside, giving5:11. | name | value | where it is used | | --- | --- | --- | | outerx| 5 | final label | | argumentx| 10 | insidebump| |inside| 11 | final label | |label| 5:11 | stdout |
scope
Scope controls which value a name refers to.
argument
The function argument `x` is local to the call.
outer value
The outer `x` remains unchanged after `bump(10)`.
Exercise: scope.R
Reproduce the output 5:11, then trace why the outer x stays 5 while bump(10) returns 11.