M.C
M.C

Reputation: 13

Using Lua to create an Address book

I am trying to create an Address book in Lua.

I currently have 3 Tables (as an example)

Tab1 = {1, 2, 3}

Tab2 = {John, Mark, Cassie}

Tab3 = {123 , 456, 789}

I want to be able to display a list of Names to the user and then once the user clicks on the name, i want to return the corresponding values.

E.g. User selects Mark and then program will return "Contact = 2"

"Number = 456"

Upvotes: 0

Views: 169

Answers (1)

Piglet
Piglet

Reputation: 28964

First of all, unless you have assigned values to the variables somewhere, John, Mark and Cassie are nil. If you want to have the names in the table you have to use strings.

Tab2 = {"John", "Mark", "Cassie"}

Otherwise your table Tab2 will be empty.

Of course Tab1, Tab2 and Tab3 are not very clever variable names because they don't give a hint on their contents. Why not name them names, numbers and contacts for example?

Then you have to think about how to link the information between the tables.

There are many ways to do this.

If we stick to your example you would have to search Tab2 for "Mark", get the index and then use that index to get the information from the other tables.

local selectedName = "Mark"
for i,v in ipairs(Tab2) do

  if v == selectedName then
   print("Contact = " .. Tab1[i])
   print("Number = " .. Tab3[i])
  end

end

Of course this is not very nice.

Another simple way to get the number for Mark would be to store each number in a table that uses the names as keys.

local numbers = {"John" = 123, "Mark" = 456, "Cassie" = 789}

Then you can simply do something like:

print(numbers["Mark"])

Or you group all information.

local contacts = {}
contacts["Mark"] = {hairColour = "blond" ,number = 456}

Then you can do

print(contacts["Mark"].hairColour)
print(contacts["Mark"].number)

This still isn't a good solution. Just to show you some basic bricks.

Make sure you do a few tutorials and read some books and the Lua reference manual. So you'll know what is possible.

For example Lua allows to mimic object oriented programming which could be used here. Or you put everything into a database using external libraries...

Sky is the limit.

I cannot give you any advice on "clicking" a name because this is not supported in native Lua. You need libraries to create GUIs like wxLua for example.

For a simple program you can start with a console application or just hardcode the user input into your script.

Upvotes: 2

Related Questions