Jump to content




How would I access a table inside of a table?


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

#1 Lego Stax

  • Members
  • 136 posts
  • LocationThe dark depths of the web

Posted 18 September 2014 - 02:30 AM

So, as the title asks, how would I access a table inside of a table? I've already looked this up and tried what I found in CC and it failed to work.
This is what I found:

local table = {
  [1] = {
	data = "stuff",
  }
}
-- The article I read stated this:
print(table[1][data])

However, that doesn't seem to work. I know for a fact that I can do this:

local ref = table[1]
print(ref.data)

But, I want to also be able to change the data variable inside of the table. So, is there something I'm doing wrong? Or, did I get misinformation? I apologize for my ignorance in advance. :P

#2 Bomb Bloke

    Hobbyist Coder

  • Moderators
  • 7,099 posts
  • LocationTasmania (AU)

Posted 18 September 2014 - 02:32 AM

This:

print(table[1]["data"])

... gets the same result as this:

print(table[1].data)

... as does this:

data = "data"
print(table[1][data])


#3 Dog

  • Members
  • 1,179 posts
  • LocationEarth orbit

Posted 18 September 2014 - 02:33 AM

try
print(table[1].data)

note the dot

EDIT: :ph34r: 'd


EDIT2: lol - Ask a Ninja...

Edited by Dog, 18 September 2014 - 02:37 AM.


#4 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 18 September 2014 - 02:34 AM

The only problem you have is the fact that data is an undefined variable, so you are accessing table[ 1 ][ nil ]... which I assume do don't want to do.

local tbl = { person = { name = "Lego" } }
print( tbl.person.name )
print( tbl[ "person" ][ "name" ] )
print( tbl[ "person"].name )

Ninja'd

Edited by KingofGamesYami, 18 September 2014 - 02:34 AM.


#5 Lego Stax

  • Members
  • 136 posts
  • LocationThe dark depths of the web

Posted 18 September 2014 - 04:33 AM

Thank you all so much! Man I feel stupid for dancing around the answer. :mellow: Well, I guess that's what I get for being ignorant. :lol: Thank you all for your help! To be honest, I was not expecting such immediate and helpful replies. Thanks again!

#6 Dragon53535

  • Members
  • 973 posts
  • LocationIn the Matrix

Posted 18 September 2014 - 04:55 AM

As an extra thing, for static table keys, such as the table inner inside the table outer you could do
local outer = {inner = {"hello"}}
print(outer.inner[1]) --# Output hello

Edit: Didn't realize yami showed this already, well shoot

Edited by Dragon53535, 18 September 2014 - 04:56 AM.






2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users