Jump to content




Accessing Data within Multiple Tables


  • You cannot reply to this topic
4 replies to this topic

#1 QuantumGrav

  • Members
  • 36 posts
  • LocationUnited States

Posted 11 April 2013 - 01:05 PM

I am trying to get data stored in a multi-layer table, a snippet of which looks like:

table = {
  [1] = {
	[1] = "value";
	[2] = "value2"
  },
  [2] = {
	[1] = "value3";
	[2] = "value4"
  }
}

I would like to access the "value's" by using two numbers. For example, the number set 1,1 would return "value", and 2,1 would return "value3". I can do this by a very inelegant method:

-- Let x and y be the two numbers.
tHolder = table[x]
print(tHolder[y])

Is there a way to access the value with one line? Something like 'table[x].y'?

Thanks!

#2 Engineer

  • Members
  • 1,378 posts
  • LocationThe Netherlands

Posted 11 April 2013 - 01:11 PM

May simpler then you thought!:
nameOfTable[x][y] :P/>/>

And its a bad practice to use table for your table. It overrides stuff and can get you in trouble.

To get back on your nameOfTable[x].y, you can use it, but y cannot be a number. Snippet where you can use it:
t = {
  [1] = { y = 1, z = 3}
}

This is very usefull in some cases

#3 Bubba

    Use Code Tags!

  • Moderators
  • 1,142 posts
  • LocationRHIT

Posted 11 April 2013 - 01:12 PM

Edit: ninja'd, of course.

Certainly there is.

local myTable = {
  [1] = {
    [1] = "value1";
    [2] = "value2";
  };
  [2] = {
    [1] = "value1";
    [2] = "value2";
  };
}

print("Table 1, index 1 of myTable: "..myTable[1][1])


#4 SuicidalSTDz

    Permutator of Strings

  • Members
  • 1,308 posts
  • LocationPennsylvania

Posted 11 April 2013 - 01:23 PM

table = {
  [1] = {
		[1] = "value";
		[2] = "value2"
  },
  [2] = {
		[1] = "value3";
		[2] = "value4"
  }
}
for _,v in pairs(table[1]) do
 print(v)
end


This should print value 1 and value two.

#5 QuantumGrav

  • Members
  • 36 posts
  • LocationUnited States

Posted 11 April 2013 - 01:54 PM

That's perfect! Great info all, thanks a bunch!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users