luacomputercraft

Computercraft function that returns an array, use first element for boolean


Edited for more details:

I'm trying to have a turtle that is sitting in front of a sapling wait for it to grow before cutting it down. It compares the log to the item in front until it matches. The system I'm currently using works, but I was hoping there was a slightly more minimal way to write it.

checkTarget = {
    forward = function(tgt)
        check = {turtle.inspect()} --creates table with first as boolean, second as information table
        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,--continued 

This takes an argument, either a string or an array of strings, to compare against. When it checks the block in front it saves the detailed information to the second element in rtn and the first to a default of false. If the string matches the checked block's name, then it changes rtn[1] to true and returns all of it, which is the table at the bottom when doing checkTarget.forward("minecraft:log").

My question was, I am currently making a disposable variable to store the array that is returned from checkTarget, and then calling the variable's first element to get if it's true or not. I was hoping there was a way to include it in the if statement without the disposable variable (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 = "birch", 
   }, 
   name = "minecraft:sapling", 
   metadata = 2 
  } 
}

Solution

  • 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.