tags:

views:

128

answers:

2

Can someone explain this to me? I have figured it out through this tutorial that this is known as a table. Coming from a C/C++ background, can someone explain how this works (I am trying to understand some existing Lua code)?

config = {
  devices = {
    C56    = "/dev/ttyS2",
    ELTRA  = "/dev/ttyS3",
--  MICORE = "/dev/ttyS4",
    HID    = "/dev/ttyS1",

    KEYCARD = {
  --  [6] = { tty="/dev/ttyS1", speed=9600 },
      [7] = { tty="/dev/ttyS4", speed=9600 },
    },

  },
}

Is it a config table, consisting of a device table but then there is a KEYCARD table? What are C56 and ELTRA called in Lua? Are they fields?

+6  A: 

A table in Lua is just an untyped map, like Javascript objects or Python dictionaries. The table associates one value (like "devices" or 6) with another value (like "/dev/ttyS2"). The value could be another table. Tables are used to create objects, maps, and arrays.

In your example, the config variable references a table. That table has one element, "devices", whose value is another table. That table has 5 elements. Four of those elements ("C56", "ELTRA", "MICORE", and "HID") have strings as their values. The fifth element ("KEYCARD") has a table as its value. That table has two elements (6, 7) whose values are other tables (each of two elements).

Karmastan
+3  A: 

You have a config table two subtables within it, devices and Keycard, which is a subtable of devices. It's been a while since I used Lua, but to access, for example ELTRA, you'd type Config.devices.ELTRA and to access the 7 keycard you type Config.devices.KEYCARD[7] To get at the speed of the keycard, you could do speed = Config.devices.KEYCARD[7].speed

Rokujolady
Also note that Keycard[6] and MICORE are commented out.
Rokujolady
So in a sense, it is like a struct in C
0A0D
I'm sure someone is going to jump on me for being not quite technically correct here, but yes. If you are comming from c++ or c, that's a good way to think about it. A struct with losely typed members that you can add to on the fly.
Rokujolady
@Changeling: It's not like a struct in that 1) all its fields are not known when the object is first created, 2) it doesn't have a fixed layout in memory, 3) fields can be added and removed at any time, 4) its access is more like a hashtable lookup (I think) than a fixed memory offset, hence slower, 5) the syntax to access elements is different. How's it like a struct? Well, you store data in them and have a way of getting the data back out. :-)
Owen S.
@Owen: Thanks for the clarification :) I was trying to reason the meaning in my head and the only way at the time was to use the struct example albeit a poor one.
0A0D