Attempt to call a nil value (loadstring)

Hello developers. I have an admin command script that uses loadstring so I can change certain things on the fly while I am playing. The problem is whenever I try to set a value it says attempt to call a nil value but I never called any function. Here’s my script:

local Commands = {
[";s"] = {Type = 1, Function = function(Message)
	local s, e = pcall(function()
		loadstring(Message)()
	end)
	if not s then warn(e) end
end};

game.Players.PlayerAdded:Connect(function(Player)
     Player.Chatted:Connect(function(Message)
          if Player.Name == "DatabaseReplace" then
          Message = string.split(Message, " ")
	      local Command = Message[1]
	      local Parameter = Message[2]
          if Commands[Command] then
				if Commands[Command].Type == 1 then
					local s, e = pcall(function() Commands[Command].Function(Parameter) end)
					if not s then warn(e) end
               end
          end
          end
     end)
end)

If I do something like ;s print'hi', it works fine, but I do something like ;s workspace.DatabaseReplace.Humanoid.Health = 0 I get the error. Can anyone help? Thanks!

Since you’re doing string.split, you end up with:
{";s", "workspace.DatabaseReplace.Humanoid.Health", "=", "0"}

You pass the 2nd item in this table to the ;s command, which is workspace.DatabaseReplace.Humanoid.Health. That isn’t valid Lua, so loadstring returns nil followed by an error. You might need to edit how you split strings to get it to stop at a certain spot or parse it in a different way.

Also, you can do assert(loadstring(code))() for better error messages when code fails to compile. Because assert errors if a falsy value is passed to it, you’d be getting the actual error if anything fails to compile. Since it also returns the value if it doesn’t fail, you can also call it like normal.

4 Likes

Have you enabled loadstring in ServerScriptService properties?

1 Like