How do i store an array outside of a script?

Im trying to make an inventory and i want it to be accesable from anywhere in my game. How would i store my inventory table so that i can table.insert and table.remove from anywhere?

3 Likes

Use a module script. Then require the module in any script that needs access to the data.

3 Likes

every time i try to check the array it returns a nil.

heres me inventory module

local module = {}
local inventory = {}

function module.Getinventory()
	return inventory
end

function module.AddInventory(item_table)
	table.insert(inventory,item_table)
	for i,inv in pairs(inventory) do
		print(inv.inventoryName)
	end
end

return module

its printing “nil”
no matter what i add to it

There are alot of different ways you could do this but here is an example:

local Inventory = {}
Inventory.__index = Inventory --Check self for methods

--Private table of items
local Items = {} --Table of items


function Inventory.AddItem(item)
	local itemId = #Items+1
	Items[itemId] = item
	
	return itemId
end


function Inventory.GetItem(itemId)
	return Items[itemId]
end


return Inventory

--[[

Example Usage:

local inv = require("Inventory")
local picklesId = inv.AddItem("Pickles") --Adding the string pickles to the item table

print(inv.GetItem(picklesId))

--]]

You could even go as simple as something like this:

local Inventory = {}

Inventory.Pickles = "I'm a bunch of pickles!"

return Inventory
--[[
Example Usage:

local inv = require("Inventory")
inv.Cheese = "I'm a bunch of cheese!"

print(inv.Cheese)
print(inv.Pickles)

--]]
1 Like