How to save table with save.sys()?

Hi, I’m trying to figure out how to save a table (the player’s inventory) with save.sys(), but I keep running into this error:

ERROR:SCRIPT: player/inventory.gui_script:136: keys in table must be of type number or string (found table)
stack traceback:
  [C]:-1: in function save
  player/inventory.gui_script:136: in function <player/inventory.gui_script:112>

I saw in another post that save.sys() should be able to save an entire table, but it seems every time I try I get this error. I’ve been trying it like this:

local savefile_path = sys.get_save_file("MyGame", "inventory")

local listedInventory = {}

local inventory = {}

local items_list = {
	[101] = {
		name = "coffee",
		id = 101,
		qty = 0
	},
	[102] = {
		name = "soda",
		id = 102,
		qty = 0
	},
	[103] = {
		name = "tea",
		id = 103,
		qty = 0
	}
}

local function rcv_item(item_id, add_qty)
	local item = items_list[item_id]
	item.qty = item.qty + add_qty
	if not listedInventory[item] then
		table.insert(inventory, item)
		listedInventory[item] = true
	else
		inventory[item] = item
	end
end
function on_message(self, message_id, message, sender)
	if message_id == hash("rcv_item_info") then
		rcv_item(message.item_info[1], message.item_info[2])
		sys.save(savefile_path, inventory)--THIS IS WHERE THE ERROR IS
	end
end

I just can’t figure out what I’m doing wrong. I would really appreciate if someone could point it out. Thank you!

Hi,

without having tried it myself, looking at your code, I would think that this line is your problem:

inventory[item] = item

“item” indeed is a table, isn’t it? And you use it as a key, hence the error.

What you probably want to do is rather something like
inventory[item_id] = item

3 Likes

Ohhh! That makes so much sense now that you point it out. (I’m really new to coding and defold in general.)

Thank you so much for your help! :grin: