该函数按预期执行,直到我尝试让它返回一个包含 2 个条目的表。相反,它返回 nil。
我正在 ZeroBrane Studio 中使用我认为是最新的 Lua 版本。
function round(n)
local up = math.ceil(n)
if up - (n + 0.5) <= 0 then return math.ceil(n)
else return math.floor(n) end
end
function neighbors(t, x)
local mid = round(#t/2)
local tt = {}
if #t == 2 then
print("Finished Search; returning {"..t[1]..", "..t[2].."}.")
return t
end
if x >= t[mid] then
for i = mid, #t do
table.insert(tt, t[i])
end
elseif x < t[mid] then
for i = 1, mid do
table.insert(tt, t[i])
end
end
print(table.concat(tt, ", "))
neighbors(tt, x)
end
test = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
nn = neighbors(test, 14.25)
print(nn)
我希望调试输出为“table: 0x000291f8”或类似的东西,但我得到的是 nil。
最佳答案
您缺少 return
在你的 neighbors
的末尾功能。应该是:
return neighbors(tt, x)
你的错误是返回t
程序的第 11 行不会将值一直返回到递归调用链上,它只会将其返回到调用 neighbors
的最后一个函数。 .
添加return neighbors(tt, x)
将导致实际获得 t
的调用将链上的值一直返回到第一次调用neighbors
这是一个常见递归程序的简单示例:
function factorial(n)
if (n == 0) then
return 1
else
return n * factorial(n - 1) --note we return this line not just call it.
end
end
关于algorithm - 函数按预期执行,但在循环结束时返回 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738697/