1

I have a table called "inventory", initialized like so:

inventory = {}

inventory[1] = { qty = 0 }

I want to add more data to this table, at the index 1, eg:

val = { id = "example" }

inventory[1] = inventory[1], val

Is there a way I can do this while preserving the data that is already in this table at this index?

The final result should be something like:

inventory[1] = { qty = 0, id = "example" }

But if I try to print the id after trying this code I get:

print(inventory[1].id) == Nil
Doug Currie
  • 40,708
  • 1
  • 95
  • 119
Aaranihlus
  • 143
  • 2
  • 13
  • 1
    Possible duplicate of [Lua - merge tables?](https://stackoverflow.com/questions/1283388/lua-merge-tables) – J. Titus Mar 13 '18 at 17:33

2 Answers2

2
inventory[1].id = "example"

or

inventory[1]["id"] = "example"

or

this other SO answer with first_table being inventory[1] and second_table being val.

FWIW, you'd need 2 variables on the left side of the expression for inventory[1] = inventory[1], val to work: a, b = x, y.

J. Titus
  • 9,535
  • 1
  • 32
  • 45
  • Thanks for the answer! Is there a way to do it without having to say specifically inventory[1].id? The data in val = { id = "example" } may not actually be called id, and may have more than one entry with different names! – Aaranihlus Mar 13 '18 at 17:01
  • That would be where the other SO answer comes in. That answer contains code to loop through the `val` table and apply key value pairs regardless of the key names. – J. Titus Mar 13 '18 at 17:32
0

You need to take the first key in the table and use it:

local inventory = {}
inventory[1] = { qty = 0 }
local val = { id = "example" }

-- 

local KeyName = next(val)

inventory[1][KeyName] = val[KeyName]

print(inventory[1][KeyName]) 
-- or 
print(inventory[1].id) 
cyclaminist
  • 1,697
  • 1
  • 6
  • 12
Mike V.
  • 2,077
  • 8
  • 19