I am trying to grab something from my table using a variable that is a string
When I print this variable it shows it as “1” and I have something in my table called 1
Yet it gives me the error invalid argument #2 (string expected, got nil)
The script:
local shop = require(game.ReplicatedStorage.Shop)
local cosmetics = game.ReplicatedStorage.Database.Cosmetics
local item
local str
if script.Parent.Parent.Name == "Featured" then
str = string.gsub(script.Parent.Name, "Icon", "")
print(str)
item = cosmetics[shop.Featured[str]]
end
The issue seems to be related to the way you’re trying to access the Featured table. In Lua, tables can have mixed key types, meaning they can have both numeric and string keys. However, when you’re trying to access a numeric key with a string, it will return nil because "1" and 1 are not the same in Lua.
In your script, str is a string, and you’re using it to index the Featured table, which has numeric keys. This is why you’re getting nil.
To fix this, you need to convert str to a number before using it to index the Featured table.
local shop = require(game.ReplicatedStorage.Shop)
local cosmetics = game.ReplicatedStorage.Database.Cosmetics
local item
local str
if script.Parent.Parent.Name == "Featured" then
str = string.gsub(script.Parent.Name, "Icon", "")
str = tonumber(str)
item = cosmetics[shop.Featured[str]]
end