1

我正在学习计算机技术(我的世界)中的编程,并且在读取一些存储单元时遇到了一些麻烦。

我正在处理的函数将遍历所有单元格并将存储容量添加到 for 循环中的变量中。

这是我到目前为止得到的

local cell1 = peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_2")
local cell2 = peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_3")
local cell3 = peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_4")
local cell4 = peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_5")
local cell5 = peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_6")
local cell6 = peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_7")

cells = {"cell1", "cell2", "cell3", "cell4", "cell5", "cell6"}

local totStorage

function getTotStorage(table)
    for key = 1,6 do
        x = table[key]
        totStorage = totStorage + x.getMaxEnergyStored()        
    end
    print(totStorage)
end

我在这条线上得到一个错误

totStorage = totStorage + x.getMaxEnergyStored()    

说“尝试调用 nil”。有什么建议么?

4

1 回答 1

1
cells = {"cell1", "cell2", "cell3", "cell4", "cell5", "cell6"}

是以下的简写:

cells = {
-- key   value
   [1] = "cell1", 
   [2] = "cell2", 
   [3] = "cell3", 
   [4] = "cell4", 
   [5] = "cell5", 
   [6] = "cell6"
}

假设您的getTotStorage电话类似于以下(您没有发布)

getTotStorage(cells)

在循环中,您尝试调用x一个字符串值的方法:

for key = 1,6 do
   x = table[key]
   totStorage = totStorage + x.getMaxEnergyStored()        
end

这本质上是试图做的:

totStorage = totStorage + ("cell1").getMaxEnergyStored()

你可以做的是重新排列你的代码,使值是返回的对象peripheral.wrap

local cells = {
  peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_2"),
  peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_3"),
  peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_4"),
  peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_5"),
  peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_6"),
  peripheral.wrap("tile_thermalexpansion_cell_reinforced_name_7"),
}

function getTotStorage(t)
  local totStorage = 0
  for i,v in ipairs(t) do
     totStorage = totStorage + v.getMaxEnergyStored()
  end
  print(totStorage)
end

几点观察:

  • 尽可能使用local(即totStorage)限制变量的范围(不需要将循环计数器作为全局)
  • 不要命名与标准 Lua 库冲突的变量(即string, table, math
  • ipairs是循环遍历序列的更好方法
于 2015-04-10T18:13:05.280 回答