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

Astrognome's Basic Lua Tutorial [1.3]

Started by Astrognome, 27 February 2012 - 06:17 PM
Astrognome #1
Posted 27 February 2012 - 07:17 PM
Last updated: 3/6/12

NOTE: I will be rewriting this on the wiki over spring break.

So you probably came to learn the basics of lua/cc. You came to the right place! This tutorial will walk you from a hello world program to a functioning door lock.

Let's get straight in.

Get a computer and place it down. Right click on the computer, and it should load up an interface where you can type stuff. You can press ctrl+s to shutdown the terminal, and ctrl+r to restart it. Go ahead and type "lua" into the terminal. You will be presented with a screen where you can type even more stuff, and experiment with actual lua commands.

Print

Go ahead and type

print("Hello World!")
then press enter. It should pop a new line that says "Hello World!".

How does it work? First, you type print. This is a function in lua. A function is a piece of preset code that is made to perform a certain action, in the case of print, it prints out a line on the screen. Then you have the (). That's where you put any arguments into a function. In this case, the argument is "Hello World!". The quotes make the Hello World! into a string, which is text. If you try typing print(Hello World!), it will throw you an error. That is because the quotes around it define it as a string, and without it, the print() function doesn't know what to do with it.

The print command also works with math. If you type

print(4+7)
it results in 11.

You can also combine 2 or more strings into one with print. So you can type

print("Hello ".."World!")
and you will get "Hello World!"


Variables
SpoilerVariables allow you to define a value. This value can be changed, and accesed. We will start with the 4 main types, which are Nil, String, bool and Number.

Nil means that the variable doesn't equal anything. String is something like "Hello World!", bool is true or false, and Number is something like 7.

To make a variable, type

local hellotext = "Hello"
The local defines it as a local variable, if you don't put it, it is a global variable. Don't change this if you don't know what you're doing.

Now type

print(hellotext.." World!")

Variables also work with numbers.

Creating a program
SpoilerGo ahead and type exit() to exit the lua console.

To make a new program, type edit <programname>. Try typing

edit Hello

It should open a blank interface. If you press control, it will pop a menu at the bottom with save and exit, and you can use this menu with arrow keys and enter. Press ctrl again to make it go away.

In this window, type

x = "World!"
print ("Hello "..x)

save then exit. Now type

Hello
and it should say "Hello World!"

User input
SpoilerUser input is a way to collect a piece of information from the user. This can be done by using the io.read() function. The io.read() will stop and sleep for the user to enter something, and it can be assigned to a variable.

Open your Hello program with "edit Hello" and change it to

print("Enter your name:")
local name = io.read()
print("Hello "..name.."!")

Save and exit, then type "Hello". You should be presented with a screen that says "Enter your name:". If we type "Steve" and hit enter, it will say "Hello Steve!"

One catch with io.read() is that it is always a string. So if you enter 7, it is considered as "7", not 7, and cannot be used in math. To fix that, we can use the tonumber() command. You input a string, and it will turn it into a number.

Example:

print("Enter a number:")
local number = io.read()
number = tonumber(number)
print("Adding 5...")
number = number+5
print("Your number is now "..number)

If statements
SpoilerIf statements are used to compare 2 values to each other.

There are many different comparisons you can do. Examples:

== Equals
&amp;gt;= Greater than or equal to
&amp;lt;= Less than or equal to
~= Not equal to
&amp;gt; Greater than
&amp;lt; Less than

Go ahead and edit your program:

print("Enter your name:")
name = io.read()
if name == "bob" then
print("Your name is bob")
end

See where it says end? You need to put that after a statement so that it knows where to stop.

More advanced? Let's try it! Go ahead, and save and exit your Hello program. Let's make a Keycode program with edit Keycode.

print("Keycode program loaded!")
local keycode = "cheese"
print("Enter keycode:")
local enteredKey = io.read()
if enteredKey == keycode then
print("access granted!")
end
if enteredKey ~= keycode then
print("access denied!")
end

This is nice, but it could be simpler. Let's learn about else, and elseif. After the original "if", if you put an else statement instead of an end, you can specify what you want it to do if the "if" conditions are not met. elseif is similar, except it allows you to re-evaluate with different parameters. Let's edit our keycode program some more:


print("Keycode program loaded!")
local keycode = "cheese"
local keycode2 = "pie"
print("Enter keycode:")
local enteredKey = io.read()
if enteredKey == keycode then
print("access granted!")
elseif enteredKey == keycode2 then
print("access granted!")
else
print("access denied!")
end

Write
SpoilerSo you've been using the print command a lot. There's another one though, called term.write(). It works the same with one exception, which is there are no linebreaks.
example:

print("Hello ")
print("world!")
produces:
Hello
world!

whereas,

term.write("Hello ")
term.write("world!")
produces:
Hello world!

Let's modify our keycode program to be a bit cleaner:

print("Keycode program loaded!")
local keycode = "cheese"
local keycode2 = "pie"
term.write("Enter keycode: ")
local enteredKey = io.read()
if enteredKey == keycode then
print("access granted!")
elseif enteredKey == keycode2 then
print("access granted!")
else
print("access denied!")
end

Loops
SpoilerNow there's currently a big problem with our keycode. Our keycode ends after one go, so you'd have to run the program again to enter again. Loops allow something to loop over and over again.

If you want to loop something, it's like this:

while true do
--code stuff to loop here
end

You can also have something loop only under a certain condition. So you could have

while num1 == num2 do
--schwoopy loopy
end

The last loop is a bit more complex. It allows you to loop something a certain number times.

for i=1,10 do
print(i)
end
The i is a variable that tracks the number. The 10 tells how many times to loop it. The i also allows you to get which loop it's on. So this will print the numbers 1-10.

Let's modify our keycode program to use a loop.

print("Keycode program loaded!")
local keycode = "cheese"
local keycode2 = "pie"
while true do
term.write("Enter keycode: ")
local enteredKey = io.read()
if enteredKey == keycode then
print("access granted!")
elseif enteredKey == keycode2 then
print("access granted!")
else
print("access denied!")
end
end

Be careful when using loops though. If you don't have anything to stop it, it will loop over and over until it crashes. Our keycode works because the io.read() command stops to sleep for input.

Clearing the screen
SpoilerIf you run your now looping keycode program, you may notice that the screen clutters fairly fast. We can solve this by having the screen clear after you're done. Rather than explain it, I'll give you an example first.

print("You won't see this")
term.clear()
term.setCursorPos(1,1)
print("You will see this")

The term.clear() clears the terminal. But if you just continue, it will just write in the next line. The term.setCursorPosition(1,1) resets the cursor back to the top left, so it starts back at the top. Let's edit our code like so:

print("Keycode program loaded!")
local keycode = "cheese"
local keycode2 = "pie"
while true do
term.clear()
term.setCursorPosition(1,1)
term.write("Enter keycode: ")
local enteredKey = io.read()
if enteredKey == keycode then
print("access granted!")
elseif enteredKey == keycode2 then
print("access granted!")
else
print("access denied!")
end
end

Comments
SpoilerNow that our code is getting rather complex, we should add comments. Comments can be put by adding "–comment here" to a line.

print("Keycode program loaded!") --program loaded
local keycode = "cheese"
local keycode2 = "pie"
while true do
term.clear()
term.setCursorPosition(1,1)
term.write("Enter keycode: ")
local enteredKey = io.read()
if enteredKey == keycode then --does enteredkey match keycode?
print("access granted!")
elseif enteredKey == keycode2 then --does enteredkey match keycode2?
print("access granted!")
else
print("access denied!") --enteredkey doesn't match keycode or keycode2.
end
end

sleep
Spoilersleep() is a command that tells your program to sleep for a certain amount of time before doing anything else. It is always measured in seconds. So sleep(300) will sleep for 5 minutes, but sleep(1) will sleep for 1 second. Let's add some cool effects to our keycode program.


print("Keycode program loaded!") --program loaded
sleep(3) --sleep a bit before starting the loop
local keycode = "cheese"
local keycode2 = "pie"
while true do
term.clear()
term.setCursorPosition(1,1) -- clear terminal and reset cursor
term.write("Enter keycode: ")
local enteredKey = io.read()
term.clear()
term.setCursorPosition(1,1) -- clear terminal and reset cursor
term.write("Processing")
for i=1,3 do --prints 3 "." spaced 0.5 seconds apart
sleep(0.5)
term.write(".")
end
if enteredKey == keycode then --does enteredkey match keycode?
print("access granted!")
sleep(2)
elseif enteredKey == keycode2 then --does enteredkey match keycode2?
print("access granted!")
sleep(2)
else
print("access denied!") --enteredkey doesn't match keycode or keycode2.
sleep(2)
end
end

Editing your program in a text editor
SpoilerAt this point, our program is complicated enough that it's tedious to do it in the terminal. Let's edit it in an external text editor.

First, you need a text editor. Here are some good one that are free:
Windows: Notepad++
Mac: Textwrangler
Linux: Gedit and Vim

So first, we need to copy our old keycode program from our world folder to our normal programs folder. First, go to your minecraft folder. Then go here:
saves/[world name here]/computer
There will be one or more folders here, labeled with numbers. If there is only one, ignore this part.

If you have multiple folders:
SpoilerIn your terminal, without editing your program, type id. It should return a number. This number is the folder you want.

Now take the folder, and open it. You should have your keycode in it. Copy the file to the following location:
mods/computercraft/lua/rom/programs/computer

Now, rename the file to keycode.txt, and open it in your text editor. You can run both minecraft, and the text editor at the same time, but restart the terminal by holding ctrl+r every time you want to run the program.

More to come!</programname>
Advert #2
Posted 27 February 2012 - 09:40 PM
Good start, but I think you're lacking some detail.


I'd recommend going over: What a function is, what arguments are, multiple arguments in print, why print(Hello World!) won't work, …

Things I'd recommend changing (because they're simply bad practice): using global variables, using ambiguous variable names (x).

Once you fix that, I think you have potential for a decent guide here. :P/>/>

I'd recommend making it more practical, though:
No one wants to have their computer print 'Hello, World!', but they want it to lock/unlock doors, etc; Making a tutorial for this would make a lot of people happy.
Astrognome #3
Posted 27 February 2012 - 10:28 PM
Good start, but I think you're lacking some detail.


I'd recommend going over: What a function is, what arguments are, multiple arguments in print, why print(Hello World!) won't work, …

Things I'd recommend changing (because they're simply bad practice): using global variables, using ambiguous variable names (x).

Once you fix that, I think you have potential for a decent guide here. :P/>/>

I'd recommend making it more practical, though:
No one wants to have their computer print 'Hello, World!', but they want it to lock/unlock doors, etc; Making a tutorial for this would make a lot of people happy.
Yeah. It was a quick thing I made in study hall today, and I had to finish it up before the end. I'm on it now though.
Kane Hart #4
Posted 29 February 2012 - 12:06 PM
Hope you keep adding to this!
David2b #5
Posted 01 March 2012 - 01:38 PM
Any chance on a tut on how to combine two programmes? Like a login id then password verification?
Liraal #6
Posted 01 March 2012 - 03:24 PM
well, david, write a program like:
shell.run(program1)
shell.run(program2)
Astrognome #7
Posted 01 March 2012 - 06:31 PM
well, david, write a program like:
shell.run(program1)
shell.run(program2)
Listen to this guy.
Astrognome #8
Posted 01 March 2012 - 06:42 PM
added a bunch of stuff. I added for loops, and the wait. Working on redstone now.
Astrognome #9
Posted 02 March 2012 - 06:24 PM
I did redstone, but it got erased. Working on it again :unsure:/>/>
David2b #10
Posted 03 March 2012 - 05:36 PM
@Liraal Thanks :3

Also, may I ask is there a way to delay an action?
Advert #11
Posted 03 March 2012 - 07:01 PM
@Liraal Thanks :3

Also, may I ask is there a way to delay an action?

You can use sleep(delay); but this will cause events to be ignored until the time has passed.
MysticT #12
Posted 03 March 2012 - 07:17 PM
You should change the Wait tutorial, since there's no function wait(), it's sleep() :unsure:/>/>
Astrognome #13
Posted 04 March 2012 - 06:21 AM
You should change the Wait tutorial, since there's no function wait(), it's sleep() :unsure:/>/>
I knew I screwed something up.
Astrognome #14
Posted 06 March 2012 - 06:54 PM
You should change the Wait tutorial, since there's no function wait(), it's sleep() :unsure:/>/>
Finally got around to fixing the wait tutorial.
Smeany #15
Posted 06 March 2012 - 09:22 PM
I really like this tutorial! B)/>/>
But youve written term.setCursorPosition(1,1)
I think it's too old :unsure:/>/> people got lazy and just write term.setCursorPos(1,1)
Cuz otherwise it didnt work for me on my 1.3 computer…

Sorry for my bad english it's just confusing me.
Keep Going!
Astrognome #16
Posted 08 March 2012 - 08:32 PM
I really like this tutorial! ;)/>/>
But youve written term.setCursorPosition(1,1)
I think it's too old :mellow:/>/> people got lazy and just write term.setCursorPos(1,1)
Cuz otherwise it didnt work for me on my 1.3 computer…

Sorry for my bad english it's just confusing me.
Keep Going!
Okay! And you have pretty good english to me.
Chlorek #17
Posted 11 March 2012 - 01:10 AM
Nice tut, but that should be something more, that are LUA rules, and only few simple functions. You should write more about functions to control enviorment. I know it's "Basic LUA tutorial", but remember about other things.
hamish1001 #18
Posted 23 March 2012 - 11:21 PM
nice tutorial
Banjo_0 #19
Posted 07 April 2012 - 08:25 AM
Nice tutorial I've been using this a lot since I got the mod :P/>/> but you could have a few simple "practical" programs as well (door opening and stuff) I think someone else also mentioned it… But maybe also a little bit of stuff on turtles?
Noodle #20
Posted 08 April 2012 - 12:32 AM
Make a floppy disk tutorial with this!
Matrixmage #21
Posted 17 July 2012 - 01:35 AM
Hi, I'm just wondering if you can access your programs on disks or computers outside of game if you made them on a tekkit server, I'm trying to write a program and I want to be able to work on it and not have to be on the server, I am the server admin, so I can access the server through FTP if needed.

Thanks in advance!
-Matrixmage