Posted by
| Nick Gammon
Australia (22,973 posts) bio
Forum Administrator |
Message
| Tables are a fundamental part of the Lua design. You can make your own very easily, and store anything you like in them (including other tables).
For example, say you want to keep track of some mobs:
mobs = {} -- create mobs table
The above line creates a table, which you can then put data into, in various ways. Let's make an individual mob another table, and then store relevant parts keyed by name:
mobs.kobold = {
name = 'killer',
hp = 22,
gold = 5,
location = 'city square'
}
-- and another one ...
mobs.worm = {
name = 'gordon',
hp = 4,
gold = 15,
location = 'underground'
}
Now we can start to look at this data. First, we'll print the mobs table:
print (mobs) --> table: 00629490
You can type these examples into the MUSHclient command window (prefixed by the scripting prefix "/"), or into the Immediate scripting window.
It is all very well knowing we have a table, but what is in it? A useful feature of Lua is the "table.foreach" instruction which lets you iterate over a table. eg.
table.foreach (mobs, print)
-- output:
worm table: 006303E0
kobold table: 00630560
This is printing (ie. doing a world.Note) each entry in the table. First you see the key, and then the data. The data in this case is another table.
An alternative way of doing this is with a loop:
for k, v in pairs (mobs) do
print ("key = ", k, " value = ", v)
end
-- output:
key = worm value = table: 006303E0
key = kobold value = table: 00630560
But what is the value for the kobold? Well, we just repeat the exercise for the sub-table:
table.foreach (mobs.kobold, print)
-- output:
name killer
gold 5
location city square
hp 22
We can also access individual fields by delimiting them with dots, like this:
print (mobs.kobold.hp) --> 22
Recursive table printer
If you are playing with tables a lot, a recursive printing function might be helpful. Here is an example:
function tprint (t, indent, done)
done = done or {}
indent = indent or 0
for key, value in pairs (t) do
Tell (string.rep (" ", indent)) -- indent it
if type (value) == "table" and not done [value] then
done [value] = true
Note (tostring (key), ":");
tprint (value, indent + 2, done)
else
Tell (tostring (key), "=")
print (value)
end
end
end
To use this, just call it with a table, eg.
tprint (mobs)
-- output:
worm:
name=gordon
gold=15
location=underground
hp=4
kobold:
name=killer
gold=5
location=city square
hp=22
That is neat - now we can see the table, and any sub-tables, in a single command.
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|