本地功能相互呼叫 [英] Local functions calling each other
问题描述
我有两个偶尔互相调用的函数,而且它们是使用它们构建另一个函数的模块的本地。这个模块有点类似于这段代码:
本地函数iseven(n)
if n == 1然后
返回false
else
返回isodd(n - 1)
结束
结束
本地函数isodd(n)
如果n == 1,则
返回true
else
return iseven(n - 1)
end
end
local evenOrOdd =函数(n)
return iseven(n)和Even或Odd
end
return evenOrOdd
问题是,当从另一个文件调用 evenOrOdd
时,我得到错误尝试调用全局'isodd'(一个零值)
。
我注意到,如果我设置
我甚至尝试过放置一个虚拟函数声明(<$ c )到global,但我想让它们保持在我的模块本地。在声明 iseven
的行之前使用$ c> local function isodd()end )。我也尝试在虚函数声明的位置插入 local isodd
,但两种方式都不起作用,我得到了不同类型的错误。
我知道这是因为Lua已经关闭了,并且声明了 iseven
它会捕获 isodd的实际值,它是
nil
或者是虚拟函数,并且修改它后不计算,但是有没有办法绕过这个?
问题在于中的
使用一个全局变量,而不是稍后定义的局部变量。 isodd
> iseven
使用正向声明@Egor:
本地iseven,isodd
函数iseven(n)
.. 。
end
function isodd(n)
...
end
...
I have two functions that occasionally call each other, and they are local to a module that uses them to build 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, when calling evenOrOdd
from another file I get the error attempt to call global 'isodd' (a nil value)
.
I noticed that this doesn't happen if I set iseven
to global, but I would like to keep them local to my module.
I even tried putting a dummy function declaration (local function isodd() end
) before the line where iseven
is declared. I also tried inserting just local isodd
in the place of the dummy function declaration, but in both ways it doesn't work and I get different kind of errors.
I know this is because Lua has closures and when iseven
is declared it catches the actual value of isodd
, which is either nil
or the dummy function, and modifying it after doesn't count, but is there a way to bypass this?
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
...
这篇关于本地功能相互呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!