Detecting if a passed argument is a

Alright so right now I’m trying to create a universal gamepads reward module so I can use it across all the games I make and it will make my job a lot easier, now the issue I’m currently running into is detecting if an argument passed into a function is a list or a single variable / instance.

Here’s an example of what I mean;

function rewardhandler.rewardtool_serverlife(plr,tool)
	local rewardgiven,err = pcall(function()
		local Reward = tool:Clone()
		Reward.Parent = plr.Backpack
		
		plr.CharacterAdded:Connnect(function()
			
			Reward = tool:Clone()
			Reward.Parent = plr.Backpack
			
		end)
	end)
	if rewardgiven then return true else warn(err) end
end

Now what if someone were to pass a list of weapons into that function like;

local weapons = {game.ServerStorage.Sword1,game.ServerStorage.Sword2}
rewardhandler.rewardtool_serverlife(plr,weapons)

I’m wondering if there is any way for me to detect if the “tool” argument is a list or not?

You can use the type() built-in function to check data types:

print(type({}))
> table

You can call the type function on the tool parameter which returns the data type as a string and have an if statement to denote whatever behavior you want if it’s a table like so:

if type(tool) == "table" then
	-- tool is a table/list
end

Use the function typeof. This will check the type of the argument you pass to it. It includes Lua primitives as well as Roblox datatypes. If you are looking to pass either an instance or a table to your function, use typeof over type.

In the case of type, it will only check Lua primitives. Therefore, if you get a userdata back, you will need to check if it’s an Instance as well otherwise you could run into some bad cases (e.g. calling functions or indexing properties that don’t exist). You’d just end up using both type and typeof here.

Using typeof, you can handle cases directly as "table" or "Instance" without anything extra.

Tested types:

print(typeof({})) -- table
print(typeof(1)) -- number
print(typeof(Instance.new("Folder"))) -- Instance
print(typeof(Vector3.new())) -- Vector3

Use example:

if typeof(arg) == "table" then
    -- table tool
elseif typeof(arg) == "Instance" and arg:IsA("Tool") then
    -- instance tool
end
3 Likes

To add on to @colbert2677’s response, if you ever want to validate argument types, you can also use the “t” library, which serves as a runtime typechecker, i.e. it ensures all arguments passed to a given function are of the correct type.

1 Like

If you’re never going to construct a list of weapons to give dynamically, there’s an even better way to express this:

function give(player, ...)
    local weaponsTable = {...}
    --as before...
end

give(p, weapon1)
give(p, weapon1, weapon2)
--or any number of weapons