Message string from .Chatted returns nil when sent to module script

  1. What is the issue? So I’m scripting admin commands and I want to make it more organized by making module scripts for each command and then firing their functions whenever a game moderator types a command in the chat but for some reason the message string returns nil when I send it over to the module script.

Server script:

game.Players.PlayerAdded:Connect(function(plr)
    plr.Chatted:Connect(function(msg)
        -- rest of the code (there are a lot of commands)
        elseif string.match(msg, "!kill") and table.find(CommandsWhitelist, plr.UserId) then
	        Kill.Main(msg)
        end
        -- rest of the code (there are a lot of commands)
    end)
end)

Module script:

local Kill = {}

function Kill:Main(msg)
	if (string.sub(msg, 7)) ~= "all" then
		for i, v in pairs(game.Players:GetPlayers()) do
			if v.Name:lower() == (string.sub(msg, 7)):lower() or v.DisplayName:lower() == (string.sub(msg, 7)):lower() then
				v.Character.Humanoid.Health = 0
			end
		end
	else
		for i, v in pairs(game.Players:GetPlayers()) do
			v.Character.Humanoid.Health = 0
		end
	end
end

return Kill

Try changing the function header to

function Kill.Main(msg)

I think what’s happening is self (a reference to the Kill table basically) is getting implicitly passed as the first parameter to the function (which is msg) so instead of holding the message that was sent, it holds the table object (Kill) instead.

Might throw a type error not really sure, but see if that works for you.

yo thanks mate! this worked! what do you think, should I use function ModuleName.Main() or function ModuleName:Main()?

It doesn’t really matter. The key though is calling the function the same way that it was defined, otherwise unexpected results will take place with how the ‘self’ argument is implicitly passed. Again, self is just a reference to the table object that was indexed. (e.g: in Kill.Main(), Kill is the the table that is being indexed with Main.)

In short, if you define a member function of a table with : then you should also call it the same way. Likewise if you define it with .

If I am designing classes to work with OOP, I will typically define these functions with :, and call them the same way. Lua will implicitly specify a self parameter I can use within these functions to reference the table object that was indexed.

Understandable. I’ll never understand the self keyword though. Well thanks for the solution, I took note of it and I’ll mark your post as solution : D

1 Like

Glad I could help.

If you’re interested in learning more about what self does, you can reference this article here, which gives some pretty good documentation on object-oriented programming in Lua:

1 Like

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