Invalid argument #2 (string expected, got nil)

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 table:

local shopitems = {
	["Featured"] = {
		[1] = "RA_Char_Null",
		[2] = "RA_Char_Furbies"
	},
	["Daily"] = {
		[1] = "RA_Char_Null",
		[2] = "RA_Char_Furbies",
		[3] = "RA_Char_Furbies",
		[4] = "RA_Char_Furbies",
		[5] = "RA_Char_Furbies",
		[6] = "RA_Char_Furbies"
	},
}

return shopitems

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.

2 Likes

That worked! Tysm!

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

No problem! Glad i could help you, Have a good day! :slight_smile:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.