222 posts
Posted 29 September 2012 - 09:01 AM
Hello! I'm new to ComputerCraft and lua an I'm trying to figure it out.
I tried to understand the built-in excavate program (and write my own variant), and I noticed that almost all the functions in that program are local. So, when should I use local functions and when - global ones?
1111 posts
Location
Portland OR
Posted 29 September 2012 - 09:34 AM
You should pretty much always use local unless you have a specific need to use global.
222 posts
Posted 29 September 2012 - 09:44 AM
Um… OK, thank you. Is it true for API functions too?
And can I have an example of that "specific need"?
1111 posts
Location
Portland OR
Posted 29 September 2012 - 09:55 AM
For API functions you will want to do them as global. You can use local vars, but the functions will not be able to be accessed by an external program if they are local to the API.
The only time I've had a need to do global anything was when making API's. The rest of the time local functions/vars have always worked for what I was doing.
222 posts
Posted 29 September 2012 - 10:14 AM
OK, thank you for the explanation ^_~
214 posts
Posted 04 October 2012 - 05:24 PM
to be honest it doesent really matter. if you find your using some code a lot in computercraft just put it in a program and make it a function. then you can call it when ever you want with ease. an example would be if your always clearing the screen and resetting the cursor to the top you could do this:
function reset()
term.clear()
term.setCursorPos(1,1)
end
now if you have that on your computer you can then just do
reset()
in your code and it will clear the screen and reset the cursor to the top left.
hope this helped
1111 posts
Location
Portland OR
Posted 04 October 2012 - 10:22 PM
to be honest it doesent really matter. if you find your using some code a lot in computercraft just put it in a program and make it a function. then you can call it when ever you want with ease. an example would be if your always clearing the screen and resetting the cursor to the top you could do this:
function reset()
term.clear()
term.setCursorPos(1,1)
end
now if you have that on your computer you can then just do
reset()
in your code and it will clear the screen and reset the cursor to the top left.
hope this helped
Make two programs on a computer with that reset function, In one of them modify it to where it does something different, say different cursor position and have it print something.
Now run the program with the modified reset, then run the original.
You don't always want the same command to do the same function. And its real easy to accidentally over write something in one of your other programs or even worse something from the core CraftOS. Then you find yourself digging through code trying to find what you messed up, good times…
If you want functions available to all of the programs on your computer then do it the correct way and make an API.
Edited on 04 October 2012 - 08:25 PM