Computercraft 返回一个数组的函数,使用第一个元素作为布尔值

编辑以获得更多详细信息:

我试图让一只站在树苗前面的海龟等待树苗长大后再砍下它。它将对比前面的物品和树干,直到它们匹配。我当前正在使用的系统可以工作,但我希望有一种稍微更简洁的方法来编写它。

checkTarget = {
    forward = function(tgt)
        check = {turtle.inspect()} --创建第一个元素为布尔值,第二个元素为信息表的表
        local rtn = {false, check[2]}
        if type(tgt) == "table" then
            for k, v in pairs(tgt) do
                if check[2].name == v then
                    rtn = {true, v}
                    break
                end
            end
        elseif tgt == nil then
            return check[1]
        elseif check[2].name == tgt then
            rtn[1] = true
        end
        return rtn
    end,--继续

这个函数接受一个参数,可以是字符串或字符串数组,用于进行对比。当它检查前面的方块时,将详细信息保存在 rtn 的第二个元素中,并将第一个元素默认设置为 false。如果该字符串与已检查方块的名称相匹配,则将 rtn[1] 更改为 true 并返回整个 rtn,这是在执行 checkTarget.forward("minecraft:log") 时底部的表格。

我的问题是,我当前正在创建一个用于存储从 checkTarget 返回的数组的临时变量,并调用变量的第一个元素来获取它是否为 true。我希望在 if 语句中不使用临时变量 (tempV) 的方法。

repeat
    local tempV = fox.checkTarget.forward("minecraft:log")
    if tempV[1] then
        cut()
        fox.goTo({x = 0, y = 0, z = 0})
        fox.face(0)
    end
    tempV = fox.checkTarget.forward("minecraft:log")
until not run
{
 false,
 {
   state = {
        stage = 0,
        type = "桦木",
   },
   name = "minecraft:sapling",
   metadata = 2
  }
}
点赞
用户2858170
用户2858170

将下面翻译成中文并且保留原本的 markdown 格式,

Instead of

local tempV = fox.checkTarget.forward("minecraft:log") if tempV[1] then end


You can do

if fox.checkTarget.forward("minecraft:log")[1] then end


> and then calling the variable's first element to get if it's true or
> not.

With `tempV[1]` you're not calling the first element, you're indexing it.

To call something you have to use the call operator `()` which doesn't make sense as a boolean is not callable.

翻译:

与其

local tempV = fox.checkTarget.forward("minecraft:log") if tempV[1] then end


更好的方法是

if fox.checkTarget.forward("minecraft:log")[1] then end

```

然后调用变量的第一个元素以获取它是否为真。

使用 tempV[1],你不是在调用第一个元素,而是在索引第一个元素。

要调用东西,必须使用调用运算符 (),但将布尔值用作参数是不合理的。

2019-12-15 09:23:54