Computercraft: How to get it done

  • The FTB Forum is now read-only, and is here as an archive. To participate in our community discussions, please join our Discord! https://ftb.team/discord

casilleroatr

New Member
Jul 29, 2019
1,360
0
0
Work in progress

Computercraft can be a really fun mod that is extremely versatile. All that is required to get started is a few basic minecraft resources and some Lua know-how. This guide will not be a complete guide on how to code in Lua. There are plenty of guides out there on the internet to help you understand the basics of how Lua works, not to mention the official reference manual and the computercraft wiki

The purpose of this guide is to give practical tutorials on how to accomplish certain things with computercraft. When starting out it can be pretty difficult to know all at once the things you will need to accomplish a certain task. I hope this guide might help some people with those problems.

Although a basic understanding of Lua is advised, I will put up a brief glossary of terms to make sure the guide is as un-confusing as possible. It is also a good idea to familiarise yourself with the apis that come with computercraft. Documentation can be found here
Finally, I just want to be clear that although I will do my best to make sure any information I provide is accurate, I can make mistakes so if you see any let me know and I will fix them as soon as possible. Also, there are often several ways of completing the same task. Sometimes, readers may be able to suggest a better way of doing something I suggest. I am very open to suggestions or corrections so if you see something that you feel I should be doing differently, let me know and I will consider it.

I will arrange these tutorials in projects. Some projects I have nearly finished writing and will be up soon (I mainly need to check them for confusing inconsistencies and stuff like that) and I am working slowly on the others when I get time. More projects will be added as a think of practical ones.

Projects:

  • Glossary of terms
  • Fun with the peripheral API
  • Password protection and other security measures
  • Fun with modem communication
  • Engine control
  • Tank data
  • Inventory interaction
  • Automating hard machines like the crystalliser
  • Railcraft assistance
  • +whatever else I can think of/you suggest
Please be patient as I get all these projects into a state I am happy uploading, thank you.
 

Arkandos

New Member
Jul 29, 2019
349
0
0
This could be really useful for anyone wanting to get into CC.
If you need any help with anything just send me a PM. But this is generally a good idea, would reduce the work helping the ones that don't know anything about Lua.
When this starts to take shape I'll begin redirecting people over here :D
 

Tangpau

New Member
Jul 29, 2019
56
0
0
I have been getting into various tech mods and this will be very very helpful. Thanks for the hard work.
 

casilleroatr

New Member
Jul 29, 2019
1,360
0
0
Computercraft Glossary

Woah, 4 likes and several responses on the OP and I hadn't even put down any real information yet. Thanks for the support everyone. Lets get to it.

In this post I will attempt to introduce and define in simple terms all the jargon that it will be helpful to know about for the following guides. You do not have to read this post but it might be helpful if you are new to Lua. Definitions provided are done to the best of my understanding and my sometimes feeble explanation skills. If anyone notices a mistake I would be grateful to hear about it (although some definitions may be a little bit incomplete because I don't think it is worth overcomplicating it for an introduction). Likewise if something makes no absolutely no sense I would like to hear about it so I can change things up if necessary. This glossary can not be the definitive Lua guide, just a practical aide. The official Lua reference manual is perfect for a more thorough treatment of everything I have written here and more.
  • Comments – A comment is a piece of text embedded into a program that is ignored by the computer when it runs the program. In Lua, they are initiated by using a double hyphen. When you put a double hyphen, everything on that line after the hyphen will be ignored. You can also use long brackets <[[ ]]> to encapsulate a multi-line comment. You use the double hyphen like normal and then open long brackets and write as much or as little text as you want and then close the long brackets. Long comments are sometimes used to temporarily disable large chunks of code. Examples of both type of comment are featured below.

Code:
print(“Hello Juditffh”) --This is a comment

print(“Girls”) --[[
   Oh like Gossip girl?
   No, Girls, like Gossip girl only with more t...
   We are all multi-line comment in here
   ]]

print(“Resuming executable code”)
  • Keywords – Lua contains several keywords, also known as reserved words, that are used to perform certain tasks in Lua. If you use a decent text editor like notepad++ or are typing your program on an advanced computer, you will be able to tell if a word is a keyword because it will appear in a different colour. You cannot name variables after these keywords. Keywords are always written in lower case. You can find a list of all keywords in the Lua reference manual.
  • Math, logic and relation – All of the standard mathematical operators are available to use in Lua, +,-,*,/,^. There is also a modulo operator (%) which is like a division except that instead of returning the quotient you get the remainder. For example, 5%2 = 1. You can also perform Boolean logic with Lua. Boolean refers to true or false values and it is similar to logic gates from redpower 2 or project red. The logical operators are
    • and
    • or
    • not
They must all be spelt in lower case. By default, when evaluating a logical statement, the order of precedence goes, not then and then or. You can group parts of a complicated logic statement into parentheses to force the order.

Finally, you can also use relational operators to compare values, e.g:
  • == - double equals sign tests for equality
  • < - less than
  • > - greater than
  • <= - less than or equal to
  • >= - greater than or equal to
  • ~= - not equal to
For details on the order of precedence for all of these operators, look here: http://www.lua.org/pil/3.5.html At the end it advises, when in doubt always use explicit parentheses. This is good practice.

Here are some examples. If you want, try opening a Lua shell by typing Lua into a computercraft computer and test these examples:

Code:
(5*3) == 15
--true

(true or false) and (not (false or false)
--true

2^16<= 1
--false
  • Variables – A variable in Lua is a piece of data stored to memory that can be used or manipulated by different parts of your program. The variable itself must have a name and it contains a value. The values also have a type. Lua assigns types for values automatically and you can query this type by using the type(variable) function on the variable. There are 8 value types in Lua, although 2 of those are possibly less important for the purposes of these guides (and I don't understand them too well). Here is a list of types:
  1. string – A string is a sequence of characters bound by a matching pair of speech marks (“ “) or quotation marks (' ') If your string is meant to contain speech marks, you can avoid the string being cut off prematurely by using a backslash <\>. This ensures that a character is treated as part of the string when otherwise it might not be.

  2. number – This needs little explanation to be honest. It is just a number, and you can perform maths on them.

  3. boolean – A true or false value. A boolean can only be one of those two values. They are useful for binary systems, like detecting if a redstone signal is on or off.

  4. nil – A nil value is a variable with no data in it. Its primary function is to be different from all other variables or to denote a lack of useful data.

  5. function – A function is a piece of code that is stored as a whole and can be called and manipulated by different parts of your program. When calling a function you can pass parameters to functions to change the way they work depending on how they were written. They can also return other values which can be stored inside other variables. To call a function you write the function name followed by a pair of parentheses which will contain any parameters.

  6. table – A table is a special variable that can store multiple values at once. It references values by using keys. A key is like a sub name for the a variable within a table. Think of it like a vanilla chest. The chest is a table, the keys are the slot numbers, and the values in these keys are the items in the slots. Ultimately everything is still in the same chest. Key names can be any non-nil value. Values can be anything except nil, this includes functions and other tables. In lua, the components of a table do not all have to be of the same type. They are very flexible that way. (Keys with a value of nil are not considered part of the table and a value referred to with a non-existent key has a nil value). When storing a function in a table it is important to distinguish of you want to store the actual function or the return value of that function. If the return value then call the function inside the table using parentheses as you would anywhere else. If you are storing the actual code, omit the parentheses. There a several ways to construct tables listed here: http://www.lua.org/pil/3.6.html. I won't go into each one but I will show some examples in a bit.

  7. The other value types are called userdata and threads. I am pretty sure that userdata will be irrelevant to everything in these guides unless if I am in for a big surprise. Either way I am not qualified to give them a decent explanation yet. Threads are something else I don't fully understand and seem to be to do with coroutines, something I have not yet got my head fully around. If it becomes relevant in the future I will explain it properly, or maybe someone else in the community will. For more information go here: http://www.lua.org/manual/5.2/manual.html
Here is an example of declaring variables. (Take not of the fact that I am using the keyword local on some of the declarations. This makes it a local variable which limits variable scope which is an important concept for later on. If you do not use the local keyword when declaring a variable, Lua automatically makes it a global variable which can be seen and manipulated by all parts of your program).
Code:
str = “String theory, get it” -- This is a global string variable
local pauline = 9 --A number variable

--Now I am going to define a function, using a new keyword function

function foo(bar)
   print(bar) –- [[bar is a parameter, which can be any type of variable. This function will attempt to          print that parameter]]
end -- end is another keyword. It is used to close functions and other blocks of code.

local booleanVar = true or false --[[This is an example of an expression being evaluated so and the evaluation will be stored in the variable booleanVar]]

print(booleanVar)
--true

pauline = pauline+5 -- [[I am manipulating the pauline variable here. Now that it has been declared and localised already, I don't need to write local in front of it again. Doing so will reinitialise the variable.]]

local tableOfVariables = {} -- A table must be bound by matching curly brackets. All data goes inside them.

--I have initialised a table now I can add keys in anyway I like. Keys go in square brackets

tableOfVariables["hello"] = "world"
tableOfVariables["how"] = "are you"
tableOfVariables["pleased"] = "I am one with the wind and sky"

--All of those keys were added to the table. I can remove a key be assigning a nil value to it

tableOfVariables["hello"] = nil

--[[You can also construct a table in one line go like this and have a comma separated list of variables inside the curly brackets]]

local newTable = {"I", "know", "that\'s", "what", "makes", "me", "so", "nice"}

--[[Because I didn't give these keys explicit names, Lua assigned numeric values to them, starting at one and going up. You can give explicit key names if you want and spread it across multiple lines for improved readability if you like.]]

local newNewTable = {
[INDENT]["gee"] = "geegeegeebabybabybaby",
["Homecoming Queen"] = "Part-time model",
["Excuse me, Sir"] = "He is a prince",
["storeFunction"] = foo,
["howManyPaulines"] = pauline,[/INDENT]
}

--You can call different parts of the table using the right key like any other variable.

print( newNewTable["Excuse me, sir"])
--He is a prince

--[[Other table constructors exist like I said, but this is how I usually do it so I am limiting this explanation to that. You are free to make up your own minds though of course.]]
  • Naming conventions - There are some rules for naming variables in Lua, and some commonly observed conventions as well. Conventions are helpful to follow because they aid in human readability, especially when multiple people are working on the same code, but they are not compulsorary. The rules for naming variables are as follows:
    • A variable can not begin with a number
    • It must be one word
    • It cannot be a reserved word
    • Other than that it can be any combination of letters, numbers and underscores
    By convention, names are written in camelcase, whereby the first letter is written in lowercase and the first letter of each subsequent word in the name is written in uppercase e.g.
    • girlsThatGlitterLoveTheDark
    • scotchWhisky
    • aBlooBlooBloo
    A final not about names, case is very important. You don't have to use camelcase, uppercase or lowercase or whatever for any one particular variable, but once you have decided you need to consistent because varName ~= Varname.
  • Scope and blocks - As a mentioned earlier, variables can be local or global. This refers to scope. A global variable's scope extends to the entire program. As a result, it can be used and edited by any part of your program. On the other hand, the scope of a local variable is limited by the block it is declared in. A local variable can only be seen or edited inside a block, or in child blocks while the parent block is still active. That may make little sense to you right now, but bare with me. When you are running some code, you are in a parent block. Every variable declared inside this block is visible inside that block. If you then call a function, or open a loop or conditional statement, you open a child block, but you do not close the parent block. Variables declared inside the parent block will be visible inside the child block and can also be edited inside the child block. When the code inside the child block is ended, you close the child block and return to the parent. The parent will be able to act on those variables that were edited by the child, using the edited values. If a variable was declared inside the child block, it won't be visible to any other block, including the parent, after the child block has closed. I hope that makes sense. If you want more information, this link may be helpful. http://lua-users.org/wiki/ScopeTutorial

    New blocks are opened in serveral situations, including calling a function, opening a loop, or making a conditional. Another way to force a new block is called a do end block. Basically, that means any code that is started by the do keyword and closed by the end keyword. They are useful for deliberately limiting the scope of a variable/ group of variables.
  • Local versus global - The general rule is that all variables should be local unless it is absolutely necessary that all parts of your program access the same variable. Even if it is a small program that you are writing, it is good to get into the habit of localising your variables as much as possible. The reason for this is that local variables won't unduly influence other parts of your code which can cause errors.
I have ran out of time for this morning but I was going to add loops and conditionals to this glossary. I have a busy day starting in about an hour but I might be able to finish it when I get back home later. Then I will start finalizing the "fun with the peripheral API" guide.