ddulaney
ddulaney

Reputation: 1101

How can a function access local variables defined on a higher level?

I'm just starting with Lua, and I have a problem with functions accessing local variables. The naive approach, just trying to access a variable, doesn't seem to work.

function fn1()
  print(foo)
end

local foo = "Hello, world"
fn1()         -- Prints nil

In this case, I could just pass foo to the function (as in fn(foo)), but that gets tricky with more complex cases.

function fn1()
  fn2()
end

function fn2()
  print(foo)
end

local foo = "Hello, world"
fn1(foo)         -- Also prints nil

What is the correct way to access foo from inside the inner function? Passing foo to fn1 then to fn2 would work, but that gets difficult when there are several variables and functions involved. I would prefer not to make foo global. Are there any other ways to make this work?

Upvotes: 1

Views: 725

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

You can do the following which puts the local in scope of both the functions.

local foo = "Hello, world"

function fn1()
  fn2()
end

function fn2()
  print(foo)
end

fn1()

Upvotes: 2

Related Questions