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

如何修复Lua中的"attempt to index ? (a number value)"错误?

已解决

我的收获: 在函数内使用table时,确保没有同名变量。局部变量会覆盖全局变量。希望能帮到大家!

错误出现在调用goto()函数的第112行。

我接触编程才4天,尝试编写一段引用table作为函数参数的代码。我希望调用changeD(a[4]),让checkD()运行直到返回a[4],但却出现了错误。

我的table定义如下:

a = {}
a[1] = "north"
a[2] = "east"
a[3] = "south"
a[4] = "west"

我在如下函数中引用table值作为参数:

function changeD(arg)
local dir = 0
 repeat
  if checkD() == arg then
   print("Done")
   dir = 1
  else
  turn(1,1)
  end
 until dir == 1
end 

checkD()函数会返回table中的某个值,因此changeD()函数会一直运行,直到checkD()返回的值与参数指定的table值一致。

我对table相关的术语可能使用不当,还请见谅,毕竟我还是编程新手。

以下是我的完整代码:

c = 0
a = {}
a[1] = "north"
a[2] = "east"
a[3] = "south"
a[4] = "west"
function fd(x)
 for i = 1 ,x do
  print("forward")
  turtle.dig()
  turtle.forward()
  end 
 end
 
function turn(y,x)
 if x == 1 then
  for i = 1 ,y do
  turtle.turnLeft()
  print("left")
  end
 elseif x == 2 then
  for i = 1 ,y do
  turtle.turnRight()
  print("right")
  end
 end
end
 
function checkD()
 local X, Y, Z = gps.locate()
 print(X)
 print(Y)
 print(Z)
turtle.forward()
 local x , y, z = gps.locate()
 print(x)
 print(y)
 print(z)
  c = 0
  result = false
  D = 0
repeat
 if c == 0 then 
  A = X
  B = x
 print(A.." "..B)
 else
  A = Z
  B = z
 print(A.." "..B)
 end
sleep(2)
 if A < B then
 g = 1
 elseif A > B then
 g = 2
 elseif A == B then
 c = 1
 end
print("compared values; g="..g)
if c == 0 then
 if g == 1 then
   D = a[2]
   result = true
 elseif g == 2 then
   D = a[4]
  result = true
 end
print("checked x")
print(D)
elseif not c == 0 then
 if g == 1 then
  D = a[3]
  result = true
 elseif g == 2 then
   D = a[1]
  result = true
 end
print("checked z")
end
print("Direction facing "..D)
 until result == true
 turtle.back()
 return D
end
 
function changeD(arg)
local dir = 0
 repeat
  if checkD() == arg then
   print("Done")
   dir = 1
  else
  turn(1,1)
  end
 until dir == 1
end 
local x = 0 
function goto(x,y,z)
local t = 0
local a = 0
local X, Y, Z = gps.locate()
  print(X)
  print(Y)
  print(Z)
 if X > x then
 t = X - x
 changeD(a[4])
 fd(t)
 elseif X < x then
 t = x - X
 changeD(a[2])
 fd(t)
 else
 print("cord is same")
 end
 
 if Z > z then
 t = Z - z
 change(a[1])
 fd(t)
 elseif Z < z then
 t = z - Z
 change(a[3])
 fd(t)
 else
 print("cord is same")
 end
 
 if Y > y then
  t = Y - y
  for i = 1,t do
   turtle.down()
  end
 elseif Y < y then
  t = y - Y
  for i = 1,t do
   turtle.up()
  end
 end
end

内容的提问来源于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