How would i optimize a code for this (example)

how would i optimize a code that works like this?

example:

there are 3 buttons on the screen

local gui = script.parent

local red = gui.red
local blue = gui.blue
local yellow = gui.yellow

local r = false
local b = false
local y = false

red.activated:connect(function()
if r == false then
r = true
b = false
y = false
--do stuff
else
r = false
--do stuff
end

blue.activated:connect(function()
if b == false then
r = false
b = true
y = false
--do stuff
else
b = true
--do stuff
end

yellow.activated:connect(function()
if y == false then
r = false
b = false
y = true
--do stuff
else
y = true
--do stuff
end
1 Like

Why do you need the r, b, and y variables? You left one of the most important parts of the code out.

1 Like

despite syntax and lack of indentation, this is probably not in need of optimizing in terms of speed. none of the lines take any longer than like one millisecond to run.

however, in terms of organization, you can set a bunch of variables to different ones on the same line by doing this:

local r = false
local b = false
local y = false

r, b, y = true, false, false --sets r to true and the rest to false

r, b, y = false, true, false --sets b to true and the rest to false

r, b, y = false, false, true --sets y to true and the rest to false

also, i’m not sure if it’s just because you wrote an example script inside of the devforum, but Activated should be capitalized, Connect should be capitalized, and every time you open an if statement you should use indents.

hope this helps!

2 Likes

Yeah its just an example not the real code and thanks!

1 Like
local gui = script.parent

local red = gui.red
local blue = gui.blue
local yellow = gui.yellow

local data = {r=false,b=false,y=false}

function dataExecute(key)
  for i,v in pairs(data) do
    if i == key then 
      data[i] = not data[i]
     else
      data[i]=false
    end
  end
end

red.activated:connect(function()
  dataExecute("r")
end)

blue.activated:connect(function()
  dataExecute("b")
end)

yellow.activated:connect(function()
  dataExecute("y")
end)
1 Like

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