Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Trying to make a gift command where you can choose the amount you give someone?

game.Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(msg)
		local val = tonumber(msg)
		if msg:lower() == "/gift "..val then
			if player.Name == "RareBIue" then		
				for i,v in pairs(game.Players:GetPlayers()) do
					v.leaderstats.Coins.Value = v.leaderstats.Coins.Value + val
				end
			end
		end
	end)
end)

The error is 'attempt to concatenate string with nil'

1 comment

0

You should compare your UserId, as it is a static & unique identifier. You also spelled your username incorrectly.

2 answers

✓ Accepted answer

The tonumber() function is only capable of casting a String to a number if the String in question only contains digits. In your case, you have an alphanumeric String.

To properly extract the numerical components of your message, you can use Regular Expressions:


####Note:

You will also need to accommodate for a lack of digits, so I suggest debouncing the val variable before continuing.


local GiftAmount = tonumber(msg:match("/gift (%d.+)"))

if (GiftAmount) then
	Player.leaderstats.Coins.Value += GiftAmount
end

tonumber() cannot convert a string containing non-numerical characters to a number. In the case of it being unable to convert the string to any form of number, like in this case, it will return nil. "1string" will return nil, as will "string1". Therefore, val is nil and you are attempting to concatenate it with a string.

In this case I recommend using a string function like string.match, which is capable of making sure the prefix '/gift ' is present and then return the consequent digits using a capture. It takes a string, and a string pattern (and also where to begin the match, but it is not relevant here). Captures, indicated by () within a string pattern, are used often to return specific values or types of values indicated by the pattern within it. You can read all about string patterns and how they're useful here. In this case, your string pattern would look like this:

local val = string.match(msg, "/gift (%d+)")
--(%d+) represents a capture of as many digits as possible, succeeding '/gift '.

Simply put, it will return nil if '/gift ' is not in the message at all, and in the case that it is, it will return the numbers that are used to determine the amount gifted.

I hope this answer is relevant to you, and that it helps you resolve the issue you're having regarding your string. I've used string.match many times in the past for instances like this and I highly recommend learning patterns.

This discussion is preserved as it was. New answers, comments, and votes are closed.