Skip to content

Commit 7d2308a

Browse files
committed
Lua Scripts: update
1 parent 77fc140 commit 7d2308a

File tree

1 file changed

+45
-5
lines changed

1 file changed

+45
-5
lines changed

chapters/lua.md

+45-5
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ and go over some techniques which you will probably find useful.
2020
This chapter will assume that you have had some programming experience before,
2121
even Scratch level is acceptable.
2222

23+
* Tools
24+
* Integrated Programming Environments
25+
* Local and Global
26+
* Including other Lua Scripts
27+
2328
Tools
2429
-----
2530

@@ -64,9 +69,40 @@ One such IDE is Eclipse with the Koneki Lua plugin:
6469
Local and Global
6570
----------------
6671

67-
Local should be used as much as possible.
68-
Lua is global by default, which means that variables declared in a function
69-
could be read by other functions.
72+
Whether a variable is local or global determines where it can be written to or read to.
73+
A local variable is only accessible from where it is defined. Here are some examples:
74+
75+
{% highlight lua %}
76+
-- Accessible from within this script file
77+
local one = 1
78+
79+
function myfunc()
80+
-- Accessible from within this function
81+
local two = one + one
82+
83+
if two == one then
84+
-- Accessible from within this if statement
85+
local three = one + two
86+
end
87+
end
88+
{% endhighlight %}
89+
90+
Whereas global variables can be accessed from anywhere in the script file, and from any other mod.
91+
92+
{% highlight lua %}
93+
my_global_variable = "blah"
94+
95+
function one()
96+
my_global_variable_2 = "blah"
97+
end
98+
99+
{% endhighlight %}
100+
101+
102+
### Locals should be used as much as possible
103+
104+
Lua is global by default (unlike most other programming languages).
105+
Local variables must be identified as such.
70106

71107
{% highlight lua %}
72108
function one()
@@ -78,7 +114,10 @@ function two()
78114
end
79115
{% endhighlight %}
80116

81-
This is sloppy coding, and Minetest will in fact warn you about this.
117+
This is sloppy coding, and Minetest will in fact warn you about this:
118+
119+
[WARNING] Assigment to undeclared global 'foo' inside function at init.lua:2
120+
82121
To correct this, use "local":
83122

84123
{% highlight lua %}
@@ -91,7 +130,8 @@ function two()
91130
end
92131
{% endhighlight %}
93132

94-
The same goes for functions, you should make functions as local as much as possible,
133+
The same goes for functions. Functions are variables of a special type.
134+
You should make functions as local as much as possible,
95135
as other mods could have functions of the same name.
96136

97137
{% highlight lua %}

0 commit comments

Comments
 (0)