Author Topic: Associative Table  (Read 1632 times)

0 Members and 1 Guest are viewing this topic.

Offline MCFX2

  • Newbie
  • *
  • Posts: 4
  • Karma: 0
    • @pump_upp - best crypto pumps on telegram !
Associative Table
« on: August 04, 2016, 05:27:25 PM »
In lua (obviously) I am trying to make a table with the following structure (variable length):

Code: [Select]
local myTable = {
{"Alice", "1234"},
{"Bob","3242"}
}
Now say we have variable foo which is a string that could equal "alice", "bob" or neither. If foo="Alice" it should return "1234" and "bob" returns "3242", neither returns some predefined string like "ERROR".

How would I implement this?

Offline roastchicken

  • Respected Community Member
  • Sr. Member
  • *****
  • Posts: 476
  • Karma: 84
  • I write code
Re: Associative Table
« Reply #1 on: August 04, 2016, 06:47:24 PM »
You can use the syntax table[ key ] to access 'key' in 'table'. So, myTable[ foo ] is what you're looking for. If foo is set to a value that isn't a key in myTable then it will return nil. If you want to return something other than nil, you can use the __index metamethod.
Give a man some code and you help him for a day; teach a man to code and you help him for a lifetime.

Offline MCFX2

  • Newbie
  • *
  • Posts: 4
  • Karma: 0
    • @pump_upp - best crypto pumps on telegram !
Re: Associative Table
« Reply #2 on: August 04, 2016, 06:52:15 PM »
Thanks a bunch! This seems to work. It's not the syntax I was hoping for, but it's good enough for me.