Lua Scripts: Correct syntax errors and explain dump and nil

gh-pages
rubenwardy 2015-02-24 09:53:25 +00:00
parent 705670e476
commit ad04ccd951
1 changed files with 18 additions and 2 deletions

View File

@ -227,9 +227,12 @@ Whereas global variables can be accessed from anywhere in the script file, and f
my_global_variable = "blah" my_global_variable = "blah"
function one() function one()
my_global_variable_2 = "blah" my_global_variable = "three"
end end
print(my_global_variable) -- Output: "blah"
one()
print(my_global_variable) -- Output: "three"
{% endhighlight %} {% endhighlight %}
@ -246,8 +249,15 @@ end
function two() function two()
print(dump(foo)) -- Output: "bar" print(dump(foo)) -- Output: "bar"
end end
one()
two()
{% endhighlight %} {% endhighlight %}
dump() is a function that can turn any variable into a string so the programmer can
see what it is. The foo variable will be printed as "bar", including the quotes
which show it is a string.
This is sloppy coding, and Minetest will in fact warn you about this: This is sloppy coding, and Minetest will in fact warn you about this:
[WARNING] Assigment to undeclared global 'foo' inside function at init.lua:2 [WARNING] Assigment to undeclared global 'foo' inside function at init.lua:2
@ -262,8 +272,14 @@ end
function two() function two()
print(dump(foo)) -- Output: nil print(dump(foo)) -- Output: nil
end end
one()
two()
{% endhighlight %} {% endhighlight %}
Nil means **not initalised**. The variable hasn't been assigned a variable yet,
doesn't exist or has been uninitalised (ie: set to nil)
The same goes for functions. Functions are variables of a special type. The same goes for functions. Functions are variables of a special type.
You should make functions as local as much as possible, You should make functions as local as much as possible,
as other mods could have functions of the same name. as other mods could have functions of the same name.
@ -281,7 +297,7 @@ you add them all into a table with the same name as the mod:
mymod = {} mymod = {}
function mymod.foo(bar) function mymod.foo(bar)
return foo .. "bar" return "foo" .. bar
end end
-- In another mod, or script: -- In another mod, or script: