Lua Scripting: Improve chapter

This commit is contained in:
Ezhh 2021-01-25 08:35:55 +00:00 committed by rubenwardy
parent 80bc6d32d8
commit d12e5244b3

View File

@ -9,8 +9,8 @@ redirect_from: /en/chapters/lua.html
## Introduction <!-- omit in toc --> ## Introduction <!-- omit in toc -->
In this chapter we will talk about scripting in Lua, the tools required, In this chapter we'll talk about scripting in Lua, the tools required
and go over some techniques which you will probably find useful. to assist with this, and some techniques which you may find useful.
- [Code Editors](#code-editors) - [Code Editors](#code-editors)
- [Coding in Lua](#coding-in-lua) - [Coding in Lua](#coding-in-lua)
@ -27,8 +27,11 @@ and go over some techniques which you will probably find useful.
## Code Editors ## Code Editors
A code editor with code highlighting is sufficient for writing scripts in Lua. A code editor with code highlighting is sufficient for writing scripts in Lua.
Code highlighting gives different colours to different words and characters Code highlighting uses different colours for words and characters
depending on what they mean. This allows you to spot mistakes. depending on what they represent. This allows you to easily notice
mistakes and inconsistencies.
For example:
```lua ```lua
function ctf.post(team,msg) function ctf.post(team,msg)
@ -46,30 +49,32 @@ function ctf.post(team,msg)
end end
``` ```
For example, keywords in the above snippet are highlighted such as if, then, end, and return. Keywords in this example are highlighted, including `if`, `then`, `end`, and `return`.
table.insert is a function which comes with Lua by default. Functions which come with Lua by default, such as `table.insert`, are also highlighted.
Here is a list of common editors well suited for Lua. Commonly used editors which are well-suited for Lua include:
Other editors are available, of course.
* Windows: [Notepad++](http://notepad-plus-plus.org/), [Atom](http://atom.io/), [VS Code](https://code.visualstudio.com/) * [VSCode](https://code.visualstudio.com/) -
* Linux: Kate, Gedit, [Atom](http://atom.io/), [VS Code](https://code.visualstudio.com/) open source (as Code-OSS or VSCodium), popular, and has
* OSX: [Atom](http://atom.io/), [VS Code](https://code.visualstudio.com/) [plugins for Minetest modding](https://marketplace.visualstudio.com/items?itemName=GreenXenith.minetest-tools).
* [Notepad++](http://notepad-plus-plus.org/) - Windows-only
* [Atom](http://atom.io/)
Other suitable editors are also available.
## Coding in Lua ## Coding in Lua
### Program Flow ### Program Flow
Programs are a series of commands that run one after another. Programs are a series of commands that run one after another. We call these
We call these commands "statements." commands "statements." Program flow is how these statements are executed, and
Program flow is how these statements are executed. different types of flow allow you to skip or jump over sets of commands.
Different types of flow allow you to skip or jump over sets of commands.
There are three main types of flow: There are three main types of flow:
* Sequence: Just run one statement after another, no skipping. * Sequence: runs one statement after another, with no skipping.
* Selection: Skip over sequences depending on conditions. * Selection: skips over sequences depending on conditions.
* Iteration: Repeating, looping. Keep running the same * Iteration: repeats the same statements until a condition is met.
statements until a condition is met.
So, what do statements in Lua look like? So, what do statements in Lua look like?
@ -81,16 +86,21 @@ a = a + 10
print("Sum is "..result) print("Sum is "..result)
``` ```
Whoa, what happened there? In this example, `a`, `b`, and `result` are *variables*. Local variables are
declared by using the `local` keyword, and then given an initial value. Local
a, b, and result are *variables*. Local variables are declared will be discussed later, because it's part of a very important concept called
by using the local keyword, and then given an initial value.
Local will be discussed in a bit, as it's part of a very important concept called
*scope*. *scope*.
The `=` means *assignment*, so `result = a + b` means set "result" to a + b. The `=` means *assignment*, so `result = a + b` means set "result" to a + b.
Variable names can be longer than one character unlike in mathematics, as seen with the "result" variable. Variable names can be longer than one character unlike in mathematics, as seen
It's also worth noting that Lua is *case-sensitive*; A is a different variable to a. with the "result" variable. It's also worth noting that Lua is *case-sensitive*;
A is a different variable to a.
The `=` sign means *assignment*, so `result = a + b` means set the value of
`result` to the value of `a + b`. Variable names can be longer than one
character, as seen with the `result` variable. It's also worth noting that, like
most languages, Lua is *case-sensitive*; `A` is a different variable to `a`.
### Variable Types ### Variable Types
@ -102,14 +112,14 @@ It's good practice to make sure a variable is only ever nil or a single non-nil
|----------|---------------------------------|----------------| |----------|---------------------------------|----------------|
| Nil | Not initialised. The variable is empty, it has no value | `local A`, `D = nil` | | Nil | Not initialised. The variable is empty, it has no value | `local A`, `D = nil` |
| Number | A whole or decimal number. | `local A = 4` | | Number | A whole or decimal number. | `local A = 4` |
| String | A piece of text | `local D = "one two three"` | | String | A piece of text. | `local D = "one two three"` |
| Boolean | True or False | `local is_true = false`, `local E = (1 == 1)` | | Boolean | True or False. | `local is_true = false`, `local E = (1 == 1)` |
| Table | Lists | Explained below | | Table | Lists. | Explained below. |
| Function | Can run. May require inputs and may return a value | `local result = func(1, 2, 3)` | | Function | Can run. May require inputs and may return a value. | `local result = func(1, 2, 3)` |
### Arithmetic Operators ### Arithmetic Operators
Not an exhaustive list. Doesn't contain every possible operator. Operators in Lua include:
| Symbol | Purpose | Example | | Symbol | Purpose | Example |
|--------|----------------|---------------------------| |--------|----------------|---------------------------|
@ -120,9 +130,12 @@ Not an exhaustive list. Doesn't contain every possible operator.
| A ^ B | Powers | 2 ^ 2 = 2<sup>2</sup> = 4 | | A ^ B | Powers | 2 ^ 2 = 2<sup>2</sup> = 4 |
| A .. B | Join strings | "foo" .. "bar" = "foobar" | | A .. B | Join strings | "foo" .. "bar" = "foobar" |
Please note that this is not an exhaustive list; it doesn't contain every
possible operator.
### Selection ### Selection
The most basic selection is the if statement. It looks like this: The most basic method of selection is the if statement. For example:
```lua ```lua
local random_number = math.random(1, 100) -- Between 1 and 100. local random_number = math.random(1, 100) -- Between 1 and 100.
@ -133,12 +146,14 @@ else
end end
``` ```
That example generates a random number between 1 and 100. It then prints This generates a random number between 1 and 100. It then prints "Woohoo!" if
"Woohoo!" if that number is bigger than 50, otherwise it prints "No!". that number is bigger than 50, and otherwise prints "No!".
What else can you get apart from '>'?
### Logical Operators ### Logical Operators
Logical operators in Lua include:
| Symbol | Purpose | Example | | Symbol | Purpose | Example |
|---------|--------------------------------------|-------------------------------------------------------------| |---------|--------------------------------------|-------------------------------------------------------------|
| A == B | Equals | 1 == 1 (true), 1 == 2 (false) | | A == B | Equals | 1 == 1 (true), 1 == 2 (false) |
@ -151,7 +166,9 @@ What else can you get apart from '>'?
| A or B | either or. One or both must be true. | (2 > 1) or (1 == 2) (true), (2 > 4) or (1 == 3) (false) | | A or B | either or. One or both must be true. | (2 > 1) or (1 == 2) (true), (2 > 4) or (1 == 3) (false) |
| not A | not true | not (1 == 2) (true), not (1 == 1) (false) | | not A | not true | not (1 == 2) (true), not (1 == 1) (false) |
That doesn't contain every possible operator, and you can combine operators like this: Please note that this doesn't contain every possible operator.
It is also possible to combine operators. For example:
```lua ```lua
if not A and B then if not A and B then
@ -159,10 +176,10 @@ if not A and B then
end end
``` ```
Which prints "Yay!" if A is false and B is true. This prints "Yay!" if A is false and B is true.
Logical and arithmetic operators work exactly the same; Logical and arithmetic operators work the same way; they both accept inputs and
they both accept inputs and return a value which can be stored. return a value which can be stored. For example:
```lua ```lua
local A = 5 local A = 5
@ -175,22 +192,23 @@ end
## Programming ## Programming
Programming is the action of taking a problem, such as sorting a list Programming is the action of taking a problem, such as sorting a list
of items, and then turning it into steps that a computer can understand. of items, and turning it into steps that a computer can understand.
Teaching you the logical process of programming is beyond the scope of this book; Teaching you the logical process of programming is beyond the scope of this book;
however, the following websites are quite useful in developing this: however, the following websites are quite useful in developing this:
* [Codecademy](http://www.codecademy.com/) is one of the best resources for * [Codecademy](http://www.codecademy.com/) is one of the best resources for
learning to 'code', it provides an interactive tutorial experience. learning to write code. It provides an interactive tutorial experience.
* [Scratch](https://scratch.mit.edu) is a good resource when starting from * [Scratch](https://scratch.mit.edu) is a good resource for starting from
absolute basics, learning the problem-solving techniques required to program.\\ absolute basics, and learning the problem-solving techniques required to program.\\
Scratch is **designed to teach children** how to program and isn't a serious Scratch is *designed to teach children* how to program and isn't a serious
programming language. programming language.
## Local and Global Scope ## Local and Global Scope
Whether a variable is local or global determines where it can be written to or read to. Whether a variable is local or global determines where it can be written to or
A local variable is only accessible from where it is defined. Here are some examples: read from. A local variable is only accessible from where it is defined. Here
are some examples:
```lua ```lua
-- Accessible from within this script file -- Accessible from within this script file
@ -207,25 +225,8 @@ function myfunc()
end end
``` ```
Whereas global variables can be accessed from anywhere in the script file, and from any other mod. In contrast, global variables can be accessed from anywhere in the script file, and
from any other mod.
```lua
my_global_variable = "blah"
function one()
my_global_variable = "three"
end
print(my_global_variable) -- Output: "blah"
one()
print(my_global_variable) -- Output: "three"
```
### Locals should be used as much as possible
Lua is global by default (unlike most other programming languages).
Local variables must be identified as such.
```lua ```lua
function one() function one()
@ -240,11 +241,9 @@ one()
two() two()
``` ```
dump() is a function that can turn any variable into a string so the programmer can Local variables should be used whenever possible. Mods should only create one
see what it is. The foo variable will be printed as "bar", including the quotes global at most, with the same name as the mod. Creating other globals is sloppy
which show it is a string. coding, and Minetest will warn about this:
This is sloppy coding and Minetest will, in fact, warn about this:
Assignment to undeclared global 'foo' inside function at init.lua:2 Assignment to undeclared global 'foo' inside function at init.lua:2
@ -263,12 +262,11 @@ one()
two() two()
``` ```
Remember that nil means **not initialised**. Remember that nil means **not initialised**. The variable hasn't been assigned a
The variable hasn't been assigned a value yet, value yet, doesn't exist, or has been uninitialised (meaning set to nil).
doesn't exist, or has been uninitialised (ie: set to nil).
The same goes for functions. Functions are variables of a special type, and Functions are variables of a special type, but should also be made local,
should be made local, as other mods could have functions of the same name. because other mods could have functions with the same names.
```lua ```lua
local function foo(bar) local function foo(bar)
@ -276,7 +274,9 @@ local function foo(bar)
end end
``` ```
API tables should be used to allow other mods to call the functions, like so: To allow mods to call you functions, you should create a table with the same
name as the mod and add your function to it. This table is often called an API
table or namespace.
```lua ```lua
mymod = {} mymod = {}
@ -308,6 +308,5 @@ local ret = dofile(minetest.get_modpath("modname") .. "/script.lua")
print(ret) -- Hello world! print(ret) -- Hello world!
``` ```
Later chapters will discuss how to split up the code of a mod in a lot of detail. [Later chapters](../quality/clean_arch.html) will discuss how best to split up
However, the simplistic approach for now is to have different files for different code for a mod.
types of things - nodes.lua, crafts.lua, craftitems.lua, etc.