3

I´ve tried declaring the variables with _G., and putting a return statement at the end of the functions, right before the last "end". First of which gave me an error and the other didn't solve anything.

X = 0
Y = 0
Z = 0
BedrockLevel = 0
CurrentLayer = 5
succsess = true


function DigDown(BedrockLevel, CurrentLayer, Z, succsess)
    while BedrockLevel == 0 do
        succsess = turtle.digDown()
        if succsess == false then
            succsess = turtle.down()
            if succsess == false then
                BedrockLevel = Z - 1
            else
                Z = Z - 1
            end
        end
        succsess = turtle.down()
        if succsess == true then
            Z = Z - 1
        end
    end
    while Z < BedrockLevel + CurrentLayer do
        succsess = turtle.up()
        if succsess == true then
            Z = Z + 1
        end
    end
    return BedrockLevel, CurrentLayer, Z, succsess
end


DigDown(BedrockLevel, CurrentLayer, Z, succsess)
print(BedrockLevel, X, Y, Z)

the expected outcome was: the print-funtion shows: -10 0 0 5,

but it says 0 0 0 0.

since this is the value that is assigned at the top of the code, I assume that the function doesn't change it, even though there is a return statement.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

1 Answers1

2

Your problem has to do with how you pass the values to your function, and then how your return those values.

When you pass a value to function and give it the same name as some other global variable, you have shadow the global variable. this means it is mostly inaccessible from inside the function.

Resource on shadowing:

Lua Shadowing example

As for your return, you return the values but do not assign those values to any variables. Your call should look like this:

BedrockLevel, CurrentLayer, Z, succsess = DigDown(BedrockLevel, CurrentLayer, Z, succsess)

or alternatively you can define DigDown like this:

function DigDown()

This will not shadow the global variables, so any changes made to BedrockLevel, CurrentLayer, Z, succsess will be reflected in the global variables.

Nifim
  • 4,758
  • 2
  • 12
  • 31
  • ah, tanks a lot :) i thought i would need to insert the name of the variables needed in the function, so it know where they are from. But if leaving it blank solves it thats probably the easiest solution to any problem ever :D – Nico Lindenlauf Aug 28 '19 at 15:53
  • 1
    @NicoLindenlauf I would like to point out global variables are not always the best approach. I think this answer as well as others on this question explain the issues well: https://stackoverflow.com/a/485020/7396148 – Nifim Aug 28 '19 at 15:59