Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to use tables inside tables?

Asked by 7 years ago

Sorry for asking such a simple question, but for some reason I can't figure out why this table isn't working?

items = {}
items[1]['Name'] = 'A killing machine'
items[1]['Desc'] = "Nobody can afford it.. it's unknown why it's so expensive.."
items[1]['Cost'] = 9999999999999999999999999999999999999999999999999999999999999999999

I also tried..

items = {}
items[1]['Name'] = {'A killing machine'}
items[1]['Desc'] = {"Nobody can afford it.. it's unknown why it's so expensive.."}
items[1]['Cost'] = {9999999999999999999999999999999999999999999999999999999999999999999}

I have plenty of experience, am I just forgetting something again?

2 answers

Log in to vote
0
Answered by 7 years ago

When you have tables inside tables it is commonly called a nested table.

The problem with your code is that you have not added this nested table in, so to resolve this simply add a table in at the index e.g.:-

items = {}
items[1] = {} -- adds a table in index 1
items[1]['Name'] = 'A killing machine'
items[1]['Desc'] = "Nobody can afford it.. it's unknown why it's so expensive.."
items[1]['Cost'] = 9999999999999999999999999999999999999999999999999999999999999999999

print(items[1]['Name'])

Hope this helps.

Ad
Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

Here's a clearer way to think about it:

-- on its own, an item is an object:
local item = {}
item.Name = "Blah"
item.Desc = "foo foo foo"
item.Cost = 999
-- (it exists without having to worry about its context,`items`)

-- you just happen to put that object into another one:
items[1] = item

Of course, you can also write this as table literals:

local item = {
    Name = "Blah",
    Desc = "foo foo foo",
    Cost = 999
}

items = {item}

Answer this question