How to Define a table with a name that is not known yet (solved)

I need to get price from a table , but The script can’t use the name of the BuyObject or “object” to find the table apparently.

Basically need to have a object and search table with its name, search the table for the level its at, and finally get the price from it.



local event = game:GetService("ReplicatedStorage"):FindFirstChild("Purchase") --example event
local function Purchase (Player, Object)

local BuyObject = Player.Unlocks:FindFirstChild(Object) -- this works

local level = BuyObject.Value -- its a num value , btw

local LevelName =  "level"..level

local  car = {
		Level0 =   8,
		Level1 =  14,
		Level2 =  23,
		Level3 =  33,
	}
	local Boat = {
		Level0 =  10,
		Level1 =  23,
		Level2 =  34,
		Level3 =  55,
	}
--here I need to get the specific thing I am buying's Level from the Player and The Price From the table for that specific thing for example the "car", and depending on the level of it we determine the price from the table.

--I get the Error "Invalid argument (table expected, got nil)", it seems it can't find the name and instead finds an object!

--I tried : 
local Table = table.find[Object] -- on the client side it sends the name of the object (.name) so Object should be Object.Name already.
--then I tried something like  Table.find(Object, LevelName)
--I also tried some RecursionFind, but I could not seem to get the job done since it had the same problem for me.



Event.OnServerEvent:Connect(Purchase)
end

Have you tried combining them into a single table?

local vehicles = {
    car = {
       --...data
    },

    boat = {
       --...data
    }
}

You can go through the table and check everything from there:

local price = vehicles[Object:lower()][LevelName] 
-- make sure the contents of the 'LevelName' variable matches the casing of the Key in the table
-- ex:
-- 'Level0' is not the name as 'level0'

Arrays cannot be identified, so you should use Dictionaries instead

Essentially, in a table you can put ["A"] = {1,2,3} as a key and then you can call that table later as Table["A"]

local Objects = {
	["Car"] = {
		Level0 = 8;
		Level1 = 14;
		Level2 = 23;
		Level3 = 33;
	};
	["Boat"] = {
		Level0 = 10;
		Level1 = 23;
		Level2 = 34;
		Level3 = 55;
	};
}

if typeof(Object) == "string" then -- Sanity Check
	if Objects[Object] then
		print(Objects[Object])
	end
end
2 Likes