2

One thing that seems to set Lua apart from the languages I'm used to is that it's important what order you put variable and function declarations in. In a function, you can't access local variables that were declared after the function. For example:

local function foo()
 return bar
end
local bar = 4
print(foo()) -- prints nil instead of 4

The same is true if you're trying to access a local function from a function that's declared before it.

In some cases this can all work out if you're just careful about declaring things in the right order. But what if you have two or more functions that all need to call each other? Do the functions have to be global, or is there some way to do this with local functions?

Kyle Delaney
  • 11,616
  • 6
  • 39
  • 66

1 Answers1

3

Okay, I worked it out. It's just a matter of declaring things before you define them. I wasn't sure it would work with functions, but I should've known.

local foo, bar
function foo(a)
 print 'foo'
 if a == 3 then
  bar(4)
 end
end
function bar(b)
 print 'bar'
 if b == 4 then
  foo(2)
 end
end
foo(3)
-- foo
-- bar
-- foo
Kyle Delaney
  • 11,616
  • 6
  • 39
  • 66
  • Oh! After testing this code I learnt that functions with identifiers aren't always declared globally. –  Dec 10 '16 at 17:40
  • What do you mean by identifiers? – Kyle Delaney Dec 11 '16 at 19:12
  • Valid identifier names —> `a`, `b`, `foo` and `bar` –  Dec 11 '16 at 19:35
  • Okay, but scope only applies to variables, right? And a function identifier is exactly the same as a variable in Lua. It wouldn't make sense to think of an anonymous function as being local or global, would it? – Kyle Delaney Dec 12 '16 at 20:35
  • I didn't say that, I tried to mean that I thought that functions declared like this —> `function foo() end` would be declared globally, while `local function foo() end` would generate a local, but if there's a local with name `foo`, `function foo() end` will assign the last local named `foo` it has access to. So, that's what I didn't know about –  Dec 12 '16 at 20:43
  • All right, well non-function variables work the same way. – Kyle Delaney Dec 13 '16 at 22:31