StendhalScripting/Lua: Difference between revisions

Content deleted Content added
imported>AntumDeluge
Stendhal Application: update for changes to Lua engine
imported>AntumDeluge
Tables: accessing table values
Line 57:
 
''(<span style="color:red;">IMPORTANT NOTE: Lua table indexes begin at 1, not 0</span>)''
 
==== Creating Tables ====
 
An empty table is initialized with a pair of curly braces (<code>{}</code>):
Line 66 ⟶ 68:
<pre>
-- create a table with values
local mytable = {"foo"}
"foo"
}
 
-- add value
Line 76:
To create a key=value table, any of the following methods can be used to add values:
<pre>
-- all of these do the same thing, that is, assigning "bar" to mytable.foo
local mytable {
foo = "bar",
["foo"] = "bar",
}
 
mytable.foo = "bar"
mytable["foo"] = "bar"
</pre>
 
==== Accessing Table Values ====
 
Square brackets (<code>[]</code>) enclosing an index number are used to access values in indexed tables (''remember that Lua table indexes start at "1" not "0"''):
<pre>
local mytable = {"foo", "bar"}
 
print(mytable[1]) -- prints "foo"
print(mytable[2]) -- prints "bar"
</pre>
 
In a key=value table, values can be accessed by either enclosing the key string in square brackets or concatenating the key member using a <code>.</code>:
<pre>
local mytable = {foo="bar"}
 
-- using square brackets
print(mytable["foo"]) -- prints "bar"
 
-- using concatenated member
print(mytable.foo) -- prints "bar"
</pre>
 
==== Iterating Tables ====
 
Tables can be iterated in a ''<code>for''</code> loop using the ''<code>pairs''</code> or ''<code>ipairs''</code> iterators. Loops are terminated with the <code>end</code> keyword:
<pre>
local mytable = {"foo", "bar"}
"foo",
"bar",
}
 
print("indexes:")