Is there a better way to write this?

Is there a more efficient way to write the “action” part for the script rather than doing action == A or action == B or action == C or…

local action = script.Parent.Parent.ActionText.Text
local player = game.Players.LocalPlayer

local UserInputService = game:GetService("UserInputService")

	if action == "Barrier" then

		script.Parent.Text = `Hold <font color="rgb(225,225,0)">F</font> to repair Barrier`
	else
	if action == "AK47"	or action == "AUG" or action == "BAR" or action == "Bren" or action == "Browning M1919" or action == "Commando" or action == "DP28" or action == "FG-42" or action == "Galatic Punch" or action == "Galil" or action == "Laser" or action == "M14" or action == "M16" or action == "M1897" or action == "M1911" or action == "M60" or action == "MG42" or action == "MP5K" or action == "MiniGun" or action == "Monkey Bomb" or action == "Olympia" or action == "PPSH 41" or action == "RPK" or action == "Ray Gun" or action == "RayGun Mark II" or action == "SPAS-12" or action == "Thompson" or action == "ThunderGun" then

			script.Parent.Text = `Hold <font color="rgb(225,225,0)">F</font> to Take {action}`
		else
			script.Parent.Text = `Hold <font color="rgb(225,225,0)">F</font> to Buy {action}`
		end
	end
	

i keep the tools names stored here

is there a better way to write this ?

You can use a table where the keys are your weapon names and the values are the Text you want:

so like for example:

local gun = {}
for i,v in pairs(game.Lighting.WEAPONSBOX:GetChildren()) do
	table.insert(gun,v.Name)
end

would this work? then do like if action == gun then?

Learn about tables. You can store all the names of the objects into a table. You could also just get all the items and use the names.

local actions = {}
for i,v in pairs(Object:GetChildren()) do
    table.insert(actions,v.Name)
end

You could then check if the action is inside the table.

if table.find(actions,action) and table.find(actions,action) ~= 0 then
    --action is in table
end

If you have custom text for every item in the list, you can either use a string value for each object, or get an attribute.

local actions = {}
for i,v in pairs(Object:GetChildren()) do
    actions[v.Name] = v:GetAttribute("ActionText") or 'Hold <font color="rgb(255,255,0)>F</font> to take action'
end

I meant like this:

local weaponTexts = 
{
["Barrier"] = `Hold <font color="rgb(225,225,0)">F</font> to repair Barrier`,
-- etc
}

script.Parent.Text = weaponTexts[action]

tables worked perfectly, TYSM!!

1 Like

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