Lucas
Lucas

Reputation: 3715

Creating Lua Advanced Table

Need to create some table so I can get an info from it in this way:

table[attacker][id]

And if I'll use

print(table[attacker][id])

It should print the value.

Tried many ways, but haven't found any good ...

I guess it should be something like this...

table.insert(table, attacker, [id] = value)

^ This does not work.

Can someone help me?


Edit

Well, when I try it this way:

x = {}
function xxx()
    if not x[attacker][cid] then
        x[attacker][cid] = value
    else
        x[attacker][cid] = x[attacker][cid] + value
    end
    print(x[attacker][cid])
end

I get an error saying:

attempt to index field '?' (a nil value)

Upvotes: 2

Views: 3058

Answers (3)

Wesker
Wesker

Reputation: 259

you should use table = {['key']='value'} makes it easier.

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473232

What is attacker? That is, what value does it contain? It doesn't really matter what it contains since Lua tables can use any Lua value as a key. But it would be useful to know.

In any case, it's really simple.

tableName = {}; --Note: your table CANNOT be called "table", as that table already exists as part of the Lua standard libraries.
tableName[attacker] = {}; --Create a table within the table.
tableName[attacker][id] = value; --put a value in the table within the table.

The problem in your edit happened because you didn't take note of step 2 above. Values in a Lua table are empty (nil) until they have a value. Therefore, until line 2, tableName[attacker] is nil. You cannot index a nil value. You therefore must ensure that any keys in tableName that you expect to index into are in fact tables.

To put it another way, you cannot do tableName[attacker][id] unless you know that type(tableName[attacker]) == "table" is true.

Upvotes: 2

Amber
Amber

Reputation: 526533

You need the curly braces to create the inner table:

table.insert(my_table, attacker, {[id]=value})

or

-- the advantage of this is that it works even if 'attacker' isn't a number
my_table[attacker] = {[id]=value}

a = 1
b = 2
c = 3
d = {}
table.insert(d, a, {[b]=c})
print(d[a][b]) -- prints '3'

Upvotes: 5

Related Questions