Getting Started (ComputerCraft)

From Feed The Beast Wiki
Jump to: navigation, search

The Basics[edit | edit source]

Introduction[edit | edit source]

ComputerCraft consists primarily of three major components: the Computer, Turtles, and the Peripherals that attach to both to extend their basic functionality. It is possible to craft all three without ever writing an actual program, just using the built-in programs provided by the mod... but by doing so one ignores the true potential of ComputerCraft. This guide assumes that the user has no to little experience with Lua, the programming language used by ComputerCraft and will give some basics as it progresses. Please also note that this guide is only going to touch on some of the basic concepts and components of ComputerCraft; additional information can be found at ComputerCraft's Official Site as well as throughout this wiki and guides that will come at later dates.

The Computer[edit | edit source]

The first and most basic component of ComputerCraft is the Computer. The recipe is fairly inexpensive and can be made relatively early if one lucks out finding redstone. The computer may be placed down wherever the player likes and can be picked up again by breaking it with any tool.

Right-clicking on the Computer brings up the CraftOS command line (CraftOS is the default operating system for computers); it's from here where most users run programs on their computers.

Basic CraftOS Commands[edit | edit source]

The basic commands used in CraftOS are, for the most part, either identical or very similar to the basic commands used in nearly all distributions of *nix operating systems; as such, most users (even those who have only occasionally used a command line in other OS's, such as Windows or OSX) should be familiar or easily able to become familiar with them. All commands are run from the CraftOS. Note that parameters in italics are considered optional.

command/command alias <parameters> Command description/use
help <topic name> On its own, returns a list of help topics. Specifying the topic after the command returns information on that topic.
programs Lists the available programs to be run.
apis Returns a list of available APIs (application programming interfaces) that one can use (via Lua) from within CraftOS. More information on various APIs can be obtained by typing using the help command followed by the API name.
ls/list <directory> Lists the contents of a directory. If no directory is given lists the contents of the current one.
cd <directory> Changes the current directory; can be used to go to the parent directory of where the command is issued.
mkdir <directory name> Creates a new directory with the given name.
mv/move/rename <source file> <destination file> If used without a directory path in the destination, renames the file; otherwise, will move and rename the file.
edit <filename> Opens a simple text editor to edit the file named. If the file doesn't exist, it will be created when the contents are saved. Pressing CTRL will switch to the command menu, where one can save or exit the editor.
reboot Restarts CraftOS.
pastebin <get/put> Important: This command will only work if the HTTP API is enabled (it is by default with most FTB packs, but it may be turned off for various reasons by server admins or mod pack creators).

Retrieves the contents of the supplied Pastebin code and saves it as the file specified. The code is typically the numbers/letters found in the Pastebin link after (for example, if the link is then NotValid1 is the code). This command is immensely useful for sharing code that one has created as well as allowing one to write code in an external editor and importing it into the game. Pastebin has 2 main arguments, put and get. Pastebin get <code> <filename> allows you to save Pastebins to the computer, whereas Pastebin put <filename> will put the file specified on Pastebin as a public post made by a guest, and will also tell you the code needed to use to get it.

There are many more commands, but one can easily read up on those by using the help command.

Keyboard Shortcuts[edit | edit source]

The following keyboard shortcuts can be used to control the computer and are handy for escaping from an infinite loop or testing startup scripts.

Key Combination Result
CTRL + T This will forcefully terminate (exit) a program.
CTRL + R This will force the computer to reboot.
CTRL + S This will force the computer to shutdown.

Programming[edit | edit source]

To start a new program, simply type edit followed by a file name. This guide will start with the first two obvious programs to get the user's feet wet, but will quickly move to specific examples that apply to CraftOS and ComputerCraft's interaction with other objects in the world. Functions and API methods used in examples will have links that will explain them further.

Hello World[edit | edit source]

The traditional first step in almost any programming language is learning how to output a simple line of text (usually "Hello world.") to the screen. This example will show the reader how to do that via basic use of the print() function.

Open a new program file in the editor (recommended name: hello), and type the following:

print("Hello world.")

Simple, right? Save the file and exit the editor, then type in the name of the program. All going well, the following will appear in the CraftOS window:

> hello
Hello world.

Congratulations on taking the first step in any programming language. Although only one line, this program demonstrates how to output text to the window. This is usually the primary way to return information to a user (aside from graphics, which are beyond the scope of this guide).

Hello Username[edit | edit source]

While outputting text is important, it is also important to receive input (whether it is information to be used by the program or navigation through a program's interface). This program will expand upon the print() function, as well as introduce variables and the read() and write() functions.

Open a new program file in the editor (recommended name: hello2). Enter the following in...

write("Please enter your name: ")
local username = read()
print("Hello ", username, ".")

Save and exit the editor, then execute the program. It will expect some input from the user, but the output should overall look like this:

> hello2
Please enter your name: CoderJ
Hello CoderJ.

The print function in this example concentrates the multiple arguments (ie

print("Hello "..username..".")

is the same as

print("Hello ", username, ".")

This example shows how to create a program, how to simply print information to the screen, simply reading input, and storing data in a variable.

Computer Light Switch[edit | edit source]

This example requires a little more setup than just the basic computer. To the left of the computer, place either some redstone or red alloy wire (only one block is needed). Next to that, place a lamp (it doesn't matter which type). Please note one can place this setup on any side of the computer, however, the placement will affect how the code needs to be written (it is pretty self explanatory, though).

In this example, quite a few new functions/statements are introduced including the while loop, if...then...else statements, os.pullEvent(), print() which is, redstone.setOutput(), and comments (for ease of navigating/identifying sections of code). Comments are the text that is after a --

Enter the following code (feel free to omit comments; they are there for ease of reading the code but it's understandable if one feels it's a bit much to type in):

-- Computer Light Switch
local side = "left"      -- Set the side for the redstone output
local userinput = ""     -- Initialize user input
local event = ""         -- Initialize event

redstone.setOutput(side, false)    -- Clear output, just in case.

while true do

-- First part of the loop, lamp is off.
  term.clear()                       -- clear the screen
  term.setCursorPos(1,1)             -- Put the cursor at the top left corner.
  print("To turn lamp on, press L.")
  print("To exit, press any other key.")
-- Wait for user input (as a character), convert it to uppercase.
  event, userinput = os.pullEvent("char")
  userinput = string.upper(userinput)

-- Check to see if the input is an L, otherwise, break the loop.
  if userinput == "L" then
    redstone.setOutput(side, true) -- Turn on the redstone output

  term.clear()                     -- clear the screen
  term.setCursorPos(1,1)           -- Put the cursor at the top left corner
  print("To turn lamp off, press L.")
  print("To exit, press any other key.")

-- Wait for user input (as a character), convert it to uppercase.
  event, userinput = os.pullEvent("char")
  userinput = string.upper(userinput)

-- Check to see if the input is an L, otherwise, break the loop.
  if userinput == "L" then
    redstone.setOutput(side, false) -- Turn off the redstone output

end -- End of while true loop.

Running this code will show something like the following on the screen:

 To turn lamp on, press L.
 To exit, press any other key.

(Assuming user presses L, the lamp turns on and the following shows up...)

To turn lamp off, press L.
To exit, press any other key.

Pressing any other key will return the user to the CraftOS prompt. This program looks complicated, but in reality it's just very messy (and actually violating a few conventions). However, writing this code shows the user the essence of what is happening and sets one up for the next example.

Computer Light Switch Mk. II[edit | edit source]

This example will use the setup from the previous example. Here, the user will learn to use functions as well as other aspects of the Redstone API to control the lamp and avoid "bulky" code. It is recommended to start a new program file rather than editing the old one (due to the way the CraftOS editor works). For simplicity I will omit most of the previous comments to allow the code to be seen easier. This program uses a new part of the redstone API, redstone.getOutput(side), which allows the computer to read whether the computer is powering redstone or not, and takes only one argument: side.

local side = "left"      
local userInput = ""     
local event = ""      
redstone.setOutput(side, false)   
-- because we are doing something repetitively in the previous program, a function can greatly simplify it
-- however the function is like a new room, it cannot access any variables unless it is given them, in this case the first argument will be named whichSide inside this room.
local function redraw(whichSide)
  if redstone.getOutput(whichSide) then -- here the lamps state is checked by reading if the Redstone is on
    print("To turn lamp off, press L.")
  else -- if it is not on then
    print("To turn lamp on, press L.")
  print("To exit, press any other key.")
while true do
  -- this will run the code in the function, but the function needs to know what side in order to check if the lamp is on, so the first argument we give it is side, which tells the room that whichSide is side
  event, userInput = os.pullEvent("char")
  userInput = string.upper(userInput)
  if userInput == "L" and not redstone.getOutput(side) then
    redstone.setOutput(side, true) -- Turn on the redstone output
  elseif userInput == "L" and redstone.getOutput(side) then
    redstone.setOutput(side, false) -- Turn off the redstone output
  if event=="char" and userInput~="L" then

The set of If statements can be simplified to:

if userInput == "L" then
  -- if false set true, if true set false
  redstone.setOutput(side, not redstone.getOutput(side))
elseif event == "char" then
  -- you already know userInput ~="L"

Smart Computer Light Switch[edit | edit source]

Content coming.

Advanced Concepts[edit | edit source]

Advanced Examples[edit | edit source]

Smart Whole House Lighting[edit | edit source]

What To Do When Things Don't Work[edit | edit source]

It will happen; one will spend time meticulously writing code only to save and run their program to won't work. There's usually a few important things to check before throwing the mouse at the nearest innocent bystander...

  1. Check the error message... 99.999% of the time it will tell one exactly where the mistake was made (improper syntax, missing end statement, etc).
  2. Check the use of case (upper and lower case letters). Remember, functions usually start with a lower case letter but additional 'words' will have upper case in them (for example - redstone.setOutput).
  3. Check control statements (while, for, if, etc). Make sure they're declared right and terminated correctly (sometimes a missing end statement won't register for quite a few lines).
  4. When in doubt, write it out. One can sometimes be surprised how glaring an error is when rewriting something...despite missing it the first time.
  5. Ask the Community. Sometimes things are trickier than they appear to be but chances are someone has made the same mistake and figured it out, however, there's also a good chance that with another pair of eyes on the problem everyone can learn how to do it... maybe even find a better way! Just remember to search the forums for previous posts before making a new thread.

See also[edit | edit source]

Other languages:
Deutsch • ‎English • ‎français • ‎italiano • ‎Nederlands • ‎српски / srpski