Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling local function inside another local function

Tags:

lua

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?

like image 526
Gabriel Avatar asked Jan 28 '26 13:01

Gabriel


2 Answers

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.

like image 82
Jack Taylor Avatar answered Jan 31 '26 04:01

Jack Taylor


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.

like image 34
blanc Avatar answered Jan 31 '26 06:01

blanc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!