Jump to content
  • Sky
  • Blueberry
  • Slate
  • Blackcurrant
  • Watermelon
  • Strawberry
  • Orange
  • Banana
  • Apple
  • Emerald
  • Chocolate
  • Charcoal

Archived

This topic is now archived and is closed to further replies.

MaximilianVINCENT

Black Hole Tutorial 05- Pretty Pretty Program

Recommended Posts

for OpenComputers 1.51 on Minecraft 1.7.10
Black Hole Tutorial 05- Pretty Pretty Program

"If builders built buildings the way programmers write programs, then the first woodpecker that came along would destroy civilization."

- Gerald Weinberg

Before we got into writing anything useful, I wanted to go over some commonly preferred practices to be used when writing your programs. This is purely selfish on my part, since I would like to be able to read that elegent bit of code that took you a week. These practices should also make things easier on you.

Writing your Program

1) Write the documentation first.
As in the last tutorial, knowing exactly what you want done makes writing code easier. Start by writing the .man page first.
edit /usr/man/programName.man
NAME - name of your program
SYNOPSIS - how your program is started, what arguments are used
DESCRIPTION - What does your program do? Any options available?
EXAMPLES - examples of your program in use, how arguments affect the outcome

With documentation done first, you might be able to throw out ideas you at first thought to be great without writing a line of code. Once done, your docs will guide and help keep your focus during coding.
If you do choose to do the documentation later, you will have less reason to do a good job (I know how it works, that's good enough!) and will know the program too well, probably leaving out things new readers should know.

2) Write from comments to code.
Determine the flow of your program before actual code. Start at general ideas of how you want it (put wood in furnace) and break it down. This makes it easier to see additional requirements, what is missing or backwards, etc.

put wood in furnace
move to top of furnace - drop wood in top
move back, up, back - select slot with wood - dropDown 8 at a time - return to home
t.back() t.up() t.back() - t.select(woodSlot) - while t.count() >= 8 do t.dropDown(8) end - t.forward() t.down() t.forward() - select previous slot

OK, you get the idea (and I learned a new button!)

3) Start small, test often.
Write a prototype with the most miminimal imaginable functionality (like our treeMuncher program from the last tutorial).
Gradually add features one at a time (planting a sapling, checking for a grown tree, etc) after making sure the program is currently working. When debugging you will know any problems must be in the recently added code. This is better then spending four hours writing out every part of a complicated program and then over six hours the next two days debugging it. (I would have been better starting over.)

4) Do the easy thing first.
This gives your subconscious time to break down the difficult parts.
Trying to tackle the most difficult bits first will make Reddit or Netflix look like a good alternative (Still haven't seen Game of Thrones, maybe just the first episode). You want to do it all eventually, so ease into it.
On the other hand, stay away from easy low-priority work that does not really need doing (get the furnace interaction working before playing with the soundtrack).
If you're stuck, go to bed and let your brain stew on it for a while.

5) Read (and use) other people's code.
There is always someone who is better then you, learn from them. Look at programs similiar to what you want done. If you find something useful, thank them and write it down in your notebook (If you do not have one by now, I REALLY SUGGEST getting something. A text file, wiki, pen and paper, whatever. Pale ink (or pixels) beats a bright mind.)


Formatting your Program

"Code is read much more often than it is written."  - Guido van Rossum

The following is a style guide of how to make your code look, based upon available Lua style guides online and some personal preferences.

Consistency
Consistency means to do things the same way most every time. There will be times when doing it differently makes it easier to read, the art is knowing when.
Even if you don't intend anybody to read your code but you, then think of the you twelve months from now (you are going to be amazed how bad you were back then).

Comments
Comments that contradict the code are worse than no comments at all. Keep comments up-to-date with code changes.
Use block comments (--[[ and --]]) for long comments and important notes. Use line comments (-- ) for short, unimportant and temporary comments. Keep a space between the -- and your comments.

Inline Comments
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. Inline comments are unnecessary and in fact distracting if they state the obvious. Tell us why, not what.
Example: xMax = x + 1  -- Increment x  Leave room for window frame

Indentation
I indent two spaces, though I've seen three and four used as well.
Spaces are the preferred indentation method. Tab sizes can vary by user and editor. This helps to keep code easy to follow by eye, find missing closures, etc.

 

Bad Example:

if next(idx) == nil then
print this and that
show some examples
else
for i,v in pairs(idx) do
all of this and that
end
end

Good Example:

if next(idx) == nil then
  print this and that
  show some examples
else
  for i,v in pairs(idx) do
    all of this and that
  end
end

Naming
It's a general rule that variable names with larger scope (seen by more of the program) should be more descriptive than those with smaller scope. For example, 'x' is probably a poor choice for a global variable in a large program (better would be 'homeCoordX'), but it's fine as a counter in a small loop.

Constants:
Constants, particularly ones that are simple values, are often given in ALL_CAPS, with words optionally separated by underscores.
Example: CONNECT_RETRY_FOR = 300  -- in seconds

Lua internal variables:
Names starting with an underscore followed by uppercase letters are reserved for internal global variables used by Lua.
Example: _VERSION

Variables:
should start with a lower case letter with each embedded word capitalised.
Examples: maxTreeLevel, moveToTarget, HTTPAddress (while not consistent it is easier to read, so a good exception to the rule)

Functions:
Functions follow similar rules as variables. A function name consisting of multiple words may run together (getmetatable), as done in the standard Lua functions, though you may choose to use underscores (get_metatable) or like variables (getMetaTable).

Booleans:
It can be helpful to prefix variables that contain or functions that return only boolean values with 'is'
Example: isChickenDone = false

Names to Avoid:
Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.


Code
Compartmentalize your program
Always start with a comment header, then keep similar parts of your program together: required libraries, variable and constants definitions, etc. Keep functions close to where they are called from.

Use local variables rather than globals whenever possible.

When you type anything that requires closure, do it now and move back.

This way you are done and have no need to remember to do it later.
Examples:
 ( ), " ", [ ], --[[ --]]
 function() end
 if then end  -- Ooh, triple word score (might be tired)
 
When unsure, parenthesize.
While the order of operations is correct for our needs, parentheses will ensure future readability. Even if you are absolutely sure it doesn't need them, consider the next person who uses the code without you there, who will probably put parentheses in the wrong place.

 

Editor

While editing a program in the Robot works fine for simple programs and bug hunting, you'll eventually find yourself wanting to use a proper IDE(Integrated Development Environment). An IDE will use color to highlight key parts, hide function bodies you don't need to be looking at, have multiple files open or the same program open at different points, auto-completion of variable or function names and much more. Just try one and then go back, I dare ya.

If you want to be editing your programs while Minecraft is running, you need to open /config/opencomputers.cfg and change bufferChanges to false.

These are some free IDEs I have tested.

  • Been some time since I used Windows, but I remember Notepad++ being my primary choice for an editor.
  • Currently I am running Kubuntu, so Kate is available. Works fine for my simple stuff and what I use most often.
  • Zerobrane Studio: This is the one I would recommend, the interface is fairly intuitive and I like the amount of documentation. Available for Linux, Mac and Windows.
  • jEdit:I have spent the least amount of time with this one, so I can't say much other than it works.

Liscense
Only because this is a silly world we live in. If you worry about how others might use your programs, I suggest learning about the GNU General Public License, here is how to use it.

 

Least Signifigant Bits

  • OK, I lied. This is actually for me. I get ideas popping and then get messy and then have to start over. You can use it if you want.
  • In the next tutorial we are playing with computers and cards!
  • If you are having problems, post it on the Support Sub-Forum. Additional information, constructive critism or praise of this tutorial should be posted below.

End of Line.

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use and Privacy Policy.