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

Shared Library

Started by lionzNtiggerz, 14 April 2013 - 07:36 PM
lionzNtiggerz #1
Posted 14 April 2013 - 09:36 PM
So, I have a turtle utility library, that helps do basic/more complex turtle movement. It also keeps track of the turtle position. In the file turtleLib, there is a table:

local turtlePos = {0, 0, 0}

Now, here's the rub: I have two other files, turtleController and miningProgram which I want to use the turtleLib library. But! I don't want them to re-initialize the variable turtlePos every time. This currently happens automatically every time the file is os.loadAPI()'d because the code runs every time.

Putting the initialization of turtlePos in an init_function() doesn't work because then the it is local to the function rather than the whole file. The same problem exists with writing an if loop, or other conditional around it.

I'd rather not declare turtlePos as global because I want to distribute the program as a modular sort of thing, and its stepping over the end-users namespace.

The other thing I've considered is creating a psedo-object in the turtleLib library which contains pointers to all of the turtleLib API functions (you can do this!), including it in the main program, and passing the object to every sub-library that needs it. This is messy for the sake of a simple movement api, (and difficult to undertand if other people are trying to extend my code).

Does anyone have any better ideas?
1lann #2
Posted 15 April 2013 - 12:16 AM
Have you tried doing

if not(turtleLib or turtlePos) then
turtlePos = {0, 0, 0}
end

If so, then try to only os.loadAPI it once. I'm pretty sure os.loadAPI loads it as a global table.
Sariaz #3
Posted 15 April 2013 - 05:04 PM
You could also be saving the turtlePos variable to a file and so if that file has a position use that otherwise use 0,0,0