【问题标题】:For loop inside a function in Lua, Computercraft在 Lua 中的函数内循环,Computercraft
【发布时间】:2015-04-11 02:13:05
【问题描述】:

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

我正在处理的函数将遍历所有单元格并将存储容量添加到 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”。 有什么建议么?

【问题讨论】:

    标签: function lua computercraft


    【解决方案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 库冲突的变量(即stringtablemath
    • ipairs 是循环序列的更好方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多