Local functions calling each other

I have two functions that sometimes call each other, and they are local to the module that uses them to create another function. The module is somewhat similar to this piece of code:

local function iseven(n)
    if n == 1 then
        return false
    else
        return isodd(n - 1)
    end
end

local function isodd(n)
    if n == 1 then
        return true
    else
        return iseven(n - 1)
    end
end

local evenOrOdd = function(n)
    return iseven(n) and "Even" or "Odd"
end

return evenOrOdd

The problem is that when I call evenOrOddfrom another file, I get an error message attempt to call global 'isodd' (a nil value).

I noticed that this will not happen if I set it isevento global, but I would like to keep them local in my module.

I even tried putting the declaration of a dummy function ( local function isodd() end) before the line where it was declared iseven. I also tried to insert only local isoddinstead of declaring a dummy function, but in both cases it does not work, and I get different errors.

, , Lua iseven, isodd, nil, , , ?

+4
3

, isodd iseven , , .

, @Egor:

local iseven, isodd

function iseven(n)
...
end

function isodd(n)
...
end

...
+5

- . , , , .

local T = {}

local function evenOrOdd(n)
    return T.iseven(n) and "Even" or "Odd"
end

function T.iseven(n)
    -- code
end

, , , , . evenOrOdd, T.iseven , , evenOrOdd.

+2

Better check num%2- remainder of division

-1
source

Source: https://habr.com/ru/post/1648640/


All Articles