You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua调用sqr()函数出现"attempt to call nil"错误求助及解决

Lua调用sqr()函数触发"attempt to call nil"错误排查

我刚接触Lua仅4天,调用自定义sqr()函数时触发attempt to call nil错误,错误位于第97行(该行仅执行sqr()调用)。sqr()返回nil,调用它的cube()函数也返回nil。我认为不存在局部变量遮蔽问题,且已定义所有变量,现将sqr()函数代码及完整程序代码附上,求助问题原因。

已解决

经验总结: 务必规范格式化代码。

出现错误的sqr()函数代码:

function sqr()
 if Y < 3 then
  local  I = 5
 else
  local I = 9
 end
for i = 1 ,I do
 fd(I)
 altTurn()
end
end

完整程序代码:

term.write("How high?")
 high = read()
term.write("How many runs?")
 runs = read()
Y = 0
x = 0
v = 0
function ht(y)
if y == 2 then
  Y = Y + 1
 else
  Y = Y - 1
end
 
function rf()
 turtle.select(1)
 turtle.refuel(2)
end
 
function fd(dis)
 for i = 1 ,dis do
 turtle.dig()
 turtle.forward()
 refuel()
 end
end
 
function turn(t,d)
 for i = 1,t do
 if d == 1 then
  turtle.turnLeft()
 else
  turtle.turnright()
 end
end
end
 
function altTurn()
  if x == 0 then
  for i = 1,2 do
   fd(1)
   turn(1,1)
  end
   x = 1
  else
  for i = 1,2 do
   fd(1)
   turn(1,2)
  end
   x = 0
  end
 x = 0
end
 
function sqr()
 if Y < 3 then
  local  I = 5
 else
  local I = 9
 end
for i = 1 ,I do
 fd(I)
 altTurn()
end
end
 
function cube()
repeat
 if Y <= 3 then
  for i = 1,3 do
   sqr()
   turtle.digUp()
   turtle.up()
   refuel()
   ht(2)
   end 
  else
   turn(1,2)
   fd(2)
   turn(1,2)
   fd(3)
   turn(2,2)
   rf()
   for i = 1 ,high-3 do
    sqr()
    turtle.digUp()
    turtle.up()
    rf()
    ht(2)
    v = v + 1
   end
  end
 until v == high-3
end
end
 
sqr()

内容的提问来源于stack exchange,提问作者TryingtoLearn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:48:17