This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
lecrouch's profile picture

Function/variable not working properly

Started by lecrouch, 20 September 2015 - 06:40 AM
lecrouch #1
Posted 20 September 2015 - 08:40 AM
Hey, guys, I 've been working on this little turtle mining script for awhile now, and have sorted out most of my bugs. I however have one lingering one that seems to be in my returnAndUnload() function.

Source:
http://pastebin.com/XQaq8neb

And I finally got wise and had program generate a log, which is here:
http://pastebin.com/tdUt6QeG

Looking at the log and the program itself, it works fine until it reaches a point where it has to go back to the starting position for any reason (full inv./ no fuel) Inside the returnAndUnload function() it saves it's location to a variable lastGoodLoc, then exits into another function to travel (travelTo()) back to the starting position, startLoc. Once traveled, it returns back into the returnAndUnload() func. but all of the sudden the lastGoodLoc is wiped, and no longer points to where it should.

All this can be pretty easily found by looking at the two files. However, for the life of me I can't figure out where the error is. I'm guessing it's a lifespan or related issue?

Anyway, any help would be amazing, since I'm tearing my hair out!

Cheers!
-Julian

Edit: forgot to mention, travelTo() is @ line 250, and returnAndUnload is @ line 322
Edited on 20 September 2015 - 06:41 AM
Bomb Bloke #2
Posted 20 September 2015 - 11:45 AM
Tables (and functions and coroutines) aren't assigned directly to your variables. Instead, pointers are assigned - think of these as being like shortcuts, or aliases, leading to the actual object of interest.

If you copy the content of a variable pointing to a table into another variable, you're not copying the table, but the pointer. You end up with two variables that lead to the exact same area of memory.

For example:

a = {}
b = a
b.text = "Hello"
print(a.text)  --> "Hello"

You're copying the pointer to your "currentLoc" table into "lastGoodLoc" - try changing your saveLoc() function to generate a copy of the table instead:

local function saveLoc()
        local myNewTable = {}
        for i = 1, #currentLoc do myNewTable[i] = currentLoc[i] end
        return myNewTable
end
lecrouch #3
Posted 20 September 2015 - 04:45 PM
Oh man! That's super interesting that tables function like pointers in Lua. Thanks for the pointer! Ha.

If you've never seen this, I think it'd be right up your alley: https://xkcd.com/138/

cheers
Bomb Bloke #4
Posted 21 September 2015 - 12:11 AM
Yes, I'm a great fan of xkcd. :)/>