StendhalScripting/Lua: Difference between revisions
Content deleted Content added
imported>AntumDeluge →Objects and Functions: some instructions on using the "luajava" object |
imported>AntumDeluge Some basics about Lua |
||
Line 6:
Lua scripts end in the <code>.lua</code> extension & are stored in the <code>data/script</code> directory.
= Lua Basics =
For more detailed information, see the [https://www.lua.org/docs.html Lua reference manual].
== Comments ==
Lua uses double dashes (<code>--</code>) for single line comments & double dashes followed by double square brackets (<code>[[</code>) & closed with double square brackets (<code>]]</code>) for multi-line comments:
<pre>
-- a single line comment
--[[
a multi-line comment
]]
</pre>
== Variables ==
Be default, Lua variables are set in [https://en.wikipedia.org/wiki/Global_variable '''global''' scope] (meaning it is exposed to the entire Lua engine). To create a variable in [https://en.wikipedia.org/wiki/Local_variable '''local''' scope], the <code>local</code> keyword must be used:
<pre>
-- a global variable
var1 = "Hello world!"
-- a local variable
local var2 = "Hello world!"
</pre>
=== Tables ===
A Lua table is a data type similar to a list. Tables can be indexed or use key=value pairs.
''(<span style="color:red;">IMPORTANT NOTE: Lua table indexes begin at 1, not 0</span>)''
An empty table is initialized with a pair of curly braces (<code>{}</code>):
<pre>
local mytable = {}
</pre>
You can add values to indexed tables at initialization or with the <code>table.insert</code> method:
<pre>
-- create a table with values
local mytable = {
"foo"
}
-- add value
table.insert(mytable, "bar")
</pre>
To create a key=value table, any of the following methods can be used to add values:
<pre>
local mytable {
foo = "bar",
["foo"] = "bar",
}
mytable.foo = "bar"
mytable["foo"] = "bar"
</pre>
==== Iterating Tables ====
=== Functions ===
Like normal variables, functions can be declared as '''global''' or '''local''' & must be terminated with the <code>end</code> keyword.
There are two ways to declare functions:
<pre>
local function myFunction()
print("Hello world!")
end
</pre>
or
<pre>
local myFunction = function()
print("Hello world!")
end
</pre>
Functions can also be values in a table:
<pre>
local myTable = {}
function myTable.myFunction()
print("Hello world!")
end
</pre>
or
<pre>
local myTable = {}
myTable.myFunction = function()
print("Hello world!")
end
</pre>
or
<pre>
local myTable = {
myFunction = function()
print("Hello world!")
end,
}
-- execute with
myTable.myFunction()
</pre>
= Stendhal Application =
== Objects and Functions ==
| |||