Lua中的函数内循环,在Computercraft中使用。

我正在学习在Computercraft(Minecraft)中进行编程,并且在阅读某些存储单元方面遇到了一些麻烦。

我正在编写的函数将遍历所有单元格,并将其存储容量相加到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()

它说“尝试呼叫空值”。 有什么建议吗?

点赞
用户415823
用户415823
`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 库发生冲突的变量(即 stringtablemath
  • ipairs 是循环遍历序列的更好方法
2015-04-10 18:13:05