Local functions calling each other

烈酒焚心 提交于 2019-12-05 17:20:06

The problem is that the call to isodd in iseven uses a global variable, not the local one defined later.

Use forward declarations, as suggested by @Egor:

local iseven, isodd

function iseven(n)
...
end

function isodd(n)
...
end

...

Another way to get past this problem is to use tables. Plain local variables are probably more efficient, but with tables you dont need to manage the declarations.

local T = {}

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

function T.iseven(n)
    -- code
end

The gist of this is that because the table is defined at the top, everything below it has access to it and you can dynamically change it's contents. When evenOrOdd is called, T.iseven should already be defined by then even though it was not defined when evenOrOdd was defined.

Better check for num%2 - remainder of the division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!