StendhalScripting/Lua: Difference between revisions
Jump to navigation
Jump to search
Content deleted Content added
imported>AntumDeluge →Stendhal Application: update for changes to Lua engine |
imported>AntumDeluge →Tables: accessing table values |
||
| Line 57: | Line 57: | ||
''(<span style="color:red;">IMPORTANT NOTE: Lua table indexes begin at 1, not 0</span>)'' |
''(<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>): |
An empty table is initialized with a pair of curly braces (<code>{}</code>): |
||
| Line 66: | Line 68: | ||
<pre> |
<pre> |
||
-- create a table with values |
-- create a table with values |
||
local mytable = { |
local mytable = {"foo"} |
||
"foo" |
|||
} |
|||
-- add value |
-- add value |
||
| Line 76: | Line 76: | ||
To create a key=value table, any of the following methods can be used to add values: |
To create a key=value table, any of the following methods can be used to add values: |
||
<pre> |
<pre> |
||
-- all of these do the same thing, that is, assigning "bar" to mytable.foo |
|||
local mytable { |
local mytable { |
||
foo = "bar", |
foo = "bar", |
||
["foo"] = "bar", |
["foo"] = "bar", |
||
} |
} |
||
mytable.foo = "bar" |
mytable.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> |
</pre> |
||
==== Iterating Tables ==== |
==== Iterating Tables ==== |
||
Tables can be iterated in a |
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> |
<pre> |
||
local mytable = { |
local mytable = {"foo", "bar"} |
||
"foo", |
|||
"bar", |
|||
} |
|||
print("indexes:") |
print("indexes:") |
||