About Us
Products
Purchase
Downloads
Support
Forums
Contact Us
Site
 Register to post in forums, or Log in to your existing account
 

 Related 
Contents
Using Lua in CMUD
  -1: Introduction
  0: For the Novice
  1: Numbers and Maths
  2: Words
  3: Variables
  4: Simple Functions
  5: Tables
  6: Branching
  7: More Flow Control
  8: Writing Functions
  9: CMUD Examples
  10: Beyond This Guide
Related Links:
  4: Simple Functions
5: Tables [[cmud_tut_lua_5]] 
Say you wanted to write a script that'd keep asking you for things you need to buy from the supermarket, and then when you type "end" instead of a real item, the script will print it sorted alphabetically. How would you go about it?

It's a trick question - we haven't learnt enough to be able to do it yet! We need some sort of a list, a place to keep an unknown number of words together in one place before we go through them to sort them. What we need is a table.

Numerical Tables

To define a new table, we use curly brackets: {} is a new, blank table just like "" is a blank string. Here are some more tables.


{}
{1,3,5,7,9}
{"haddock","porcelain","irate"}

NotATable = "Fang Xianfu"
{ 275.252332 , NotATable , {"bread","cheese"}}

Let's take a minute on that last one. The first item in the list is a number, that's easy enough - but the second is a string. Remember that variables are just signposts - in this case, it points to my name. The second item in the table now points to my name as well, and it'll keep on doing that even if the NotATable variable is changed. The third item in the list is another table.

To help you pick out an item from the table, each "slot" in the table is given a number. Unsurprisingly, the numbers start at 1 and increase from there. Here's a list of my shopping:


shopping = {"bread","cheese","sausage"}

print(shopping[1])
print(shopping[2])
print(shopping[3])
print(shopping[4])

bread
cheese
sausage
nil

I included shopping[4] there just to show you what would happen. We got the answer nil. nil basically means "nothing" - it's what variables point at when you haven't told them what to point at yet. And since we didn't give shopping[4] a value, it points to nil.

You can give shopping[4] its own value very simply.


shopping[4]="herrings"
print(shopping[4])

herrings

You can only do this if shopping is already pointing at a table, even if it's an empty one.

Table Functions

Table functions start with - you've guessed it - table..

table.concat will make a string from our table. Its first parameter is the table, and its second parameter is what to separate them with.


names = {"Ben","Harold","Claudia"}
print(table.concat(names," "))
print(table.concat(names,", "))

Ben Harold Claudia
Ben, Harold, Claudia


table.maxn returns the number of items in a table.


names = {"Ben","Harold","Claudia"}
print(table.maxn(names))

3


Until now, we've only discussed functions that returned values, but some functions don't just create new things and return them - they can also do things. You've already met one - print, which doesn't return a value but just puts its parameters on the screen. If you read the Random Number section you also met math.randomseed.

table.insert and table.remove are different to the other table. functions - they actually edit the table, changing what your variable points to. insert adds an item to the end of your list and remove takes away the last item of the list and returns the item. Here it is in action:


planets = {}
table.insert(planets,"Mercury")
table.insert(planets,"Venus")
print(table.concat(planets," "))

print(table.remove(planets))
print(table.concat(planets," "))

Mercury Venus
Venus
Mercury

You can also tell Lua where to put the item you're inserting, or where to take it from, and Lua will very smartly bump items up to make gaps and bump them down to close them.


plants = {"elm", "oak", "hyacinth"}
print(table.concat(plants," "))

table.insert(plants,2,"lily")
print(table.concat(plants," "))

table.remove(plants,1)
print(table.concat(plants," "))
print(plants[1])

elm oak hyacinth
elm lily oak hyacinth
lily oak hyacinth
lily

When "elm" is removed, Lua bumps all the other items down the list to close the gap, making "lily" the new plants[1].

The Anatomy of a Table

Lets get our words sorted out before we continue.


example = {}
example[1] = "shrews"

example is the name of the variable that's holding the table. The curly brackets are a blank table. On the next line, 1 is the key (you could think of a table as a row of locked boxes - you need the key to the box to get what's inside). "shrews" is the value, same as variables.

String tables

So far our tables only have numbers as keys. This is good, because all the table. functions expect a table where the keys are numbers. But they don't have to be that way - you can have strings for keys as well. Here's an example of defining and using a string table:


example1 = {haddock = "tasty" , cheese = "less tasty"}
example1["zinfandel"] = "YUM!"
print(example1["haddock"])
print(example1["cheese"])
print(example1["zinfandel"])

tasty
less tasty
YUM!

Keys of tables don't have to be just one type. You can mix up numbers and letters as much as you like, it's up to you how you organise your tables. But be careful! Remember how I told you waaaaay back in chapter 3 that there was a difference between "7" and 7? This is it. Watch:


example2={}
example2[7]="the number 7"
example2["7"]="the string 7"
print(example2[7])
print(example2["7"])

the number 7
the string 7

Lua also gives you a shortcut for the (rather long) example["whatever"] syntax - example.whatever. Try it out on some tables of your own, but remember that example.whatever is short for example["whatever"] and not example[whatever] - if you start doing things like pets.7, make sure you mean it!

You can also use variables to hold keys:

shortname = "A really really really really really really really really really really really long string."

example3={}
example3[shortname]="hello"
print(example3[shortname])
print(example3["A really really really really really really really really really really really long string."])

hello
hello


Deleting items

I already mentioned how variables that don't contain a value contain nil. You can delete an item from a table by making it equal to nil, like so:


shopping = { "bread", "cheese", "sausage", "herrings" }
print(table.maxn(shopping))
shopping[4]=nil
print(table.maxn(shopping))

4
3


You can do a huge number of things with tables, so many that I couldn't possibly name them all here.

Once you're finished playing with tables, it's time to move on to branching.

Tim Toady

Really, the ways of making tables that you've learnt so far are just shortcuts:


{"first","second","third"}
{[1]="first",[2]="second",[3]="third"}

{first =  "one", second = "two", third = "three"}
{["first"] = "one", ["second"] = "two", ["third"] = "three"}

Inside those square brackets, you can add, multiply, concat, refer to variables, anything you like.

Remember how back in the Variables chapter I said that doing var1=var2 creates a copy of that value? This isn't strictly true when we're talking about tables. It's weird, but doing var1=var2 makes var1 contain the exact same table that var2 contains. If you make any changes to the table, both variables will be updated to reflect this.


var1={}
var2=var1
var1[1]="boo!"
print(var2[1])

boo!


Here's something really interesting. Anything that can be the value of a variable can be a value in a table, but anything can be a key, too. Read that again just to make sure it sunk in. Yes, that does mean you can use tables as keys, like table[{}]="wow!". Remember that every time you use {}, you're actually creating a new table in the computer's memory, so once this is set, you can't easily get it back out again:


example4 = {}
example4[{}] = "goodbye, cold, cruel world!"
print(example4[{}])

nil

There's only one way to get that string back out (but I won't talk about that until much later), making this great for hiding values away where someone can't easily edit them. The only exception to this is nil - you can't use nil as a key in a table.
Viewer Comments [0 - Post your comments]

Jump to:  

© 2009 Zugg Software. Hosted by Wolfpaw.net