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

How to shorten script + what goes instead of or?

So here's a pretty self-explanatory script (it prints if the Target is a human or not).

script.Parent.Equipped:connect(function(mouse)
	mouse.Button1Down:connect(function()
		local part = mouse.Target.Name
		if part == "Head"
		or Part == "Torso"
		or Part == "Left Leg"
		or Part == "Right Leg"
		or Part == "Right Arm"
		or Part == "Left Arm"
			 then print("It's a  human")
			else print("It's not a human")
		end
	end)
end)

But before you comment, I know that the or operator is not what should be used there, but I have no idea what I am supposed to use. What word means "in addition to if"?

Also as a secondary question, is there a way to make the script shorter so that I don't have to type out if part == every time?

1 answer

✓ Accepted answer

or is the correct term. This script is correct -- except:

You are using Part instead of part in all of the subsequence == expressions (variable names are case sensitive).


How or works:

  • true or false is true
  • true or true is true
  • false or true is false
  • false or false is false

And because or (ignoring execution order / short circuiting) is associative / commutative, you can just string them together:

A or B or C or D is the same as A or (B or (C or D))


Unfortunately there isn't a much shorter way to do this. We could use a hashtable (also called a dictionary):

local humanParts = {
	Head=true, Torso=true, ["Left arm"]=true,
	["Right arm"]=true, ["Left leg"]=true, ["Right leg"]=true
};

if humanParts[partName] then

Lua doesn't have a built in way to find objects in a table (which is sad).

If we implement one, though, then this condition is much shorter (but now we have a 7 line function definition -- that hopefully you find other uses for, but fair chance not):

function tableFind(list,value)
	for i, v in pairs(list) do
		if v == value then
			return i;
		end
	end
end

...

if tableFind(
	{"Head","Torso","Left arm","Right arm","Left leg","Right leg"}
	, partName) then

(I've changed part to partName in both examples because it is a more descriptive variable name; the variable is actually a string and not the object itself, so part is misleading. If you don't like the long name partName, then name is probably better than part)


A warning: mouse.Target can be nil (pointing at sky or, rarely, objects too far away). You should check that mouse.Target is an object before continuing, or line 03 in your snippet will error.

1 comment

0

Oh, I didn't even realize I was capitalizing! Also, thank you for that last tip as well, because it was breaking when I point it to the sky. Great answer!

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