The following snippet
local function foo ()
print('inside foo')
bar()
end
local function bar ()
print('inside bar')
end
foo()
Results in the following output
inside foo
lua: teste.lua:3: attempt to call global 'bar' (a nil value)
stack traceback:
teste.lua:3: in function 'foo'
teste.lua:10: in main chunk
[C]: ?
If I remove the modifier local from bar declaration then it works as expected, outputting
inside foo
inside bar
How can I call bar inside foo keeping both as local?
You need to define bar before foo.
local function bar ()
print('inside bar')
end
local function foo ()
print('inside foo')
bar()
end
foo()
In your example, when you are inside the foo function, then as far as Lua is concerned bar doesn't exist yet. This means it defaults to a global variable with a value of nil, which is why you get the error "attempt to call global 'bar' (a nil value)".
If you want to define foo before bar and keep them both as local variables, you need to declare the bar variable first.
local bar
local function foo ()
print('inside foo')
bar()
end
function bar ()
print('inside bar')
end
foo()
In this example, if you want to prove to yourself that bar is a local variable, you can add the following code at the end:
if _G.bar ~= nil then
print("bar is a global variable")
else
print("bar is a local variable")
end
This checks whether "bar" is a key in _G, the table of global variables.
In fact:
local function foo () end
Equivalent to
local foo
foo = function() end
In Lua, a function is a first-class value. So, it is not usable before it is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With