Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is the format good or is there a better way to write it in this script?

Asked by 8 years ago

Is the format good or is there a better way?

local number = 1

function onMouseButton1Click()
    if number == 1 then
    elseif number == 2 then
    elseif number == 3 then
        number = 0
    end
    number = number + 1
end

script.Parent.MouseButton1Click:connect(onMouseButton1Click)

Thanks!

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

Referring to your "elseif" format

In Lua, there is no switch statement like other programming languages, so the whole "elseif" thing is the best way to do it. While there are other ways like using tables to connect functions together, it might just make it more complicated:

local number=1
function switch(c)
  local swtbl = {
    casevar = c,
    caseof = function (self, code)
      local f
      if (self.casevar) then
        f = code[self.casevar] or code.default
      else
        f = code.missing or code.default
      end
      if f then
        if type(f)=="function" then
          return f(self.casevar,self)
        else
          error("case "..tostring(self.casevar).." not a function")
        end
      end
    end
  }
  return swtbl
end
local number = 1

function onMouseButton1Click()
    switch(number):caseof{
    [1] = function() return "It's 1" end,
    [2] = function() return "It is 2" end,
    [3] = function() return "dudeboy, it's 3" end
    }
    number = number + 1
end
script.Parent.MouseButton1Click:connect(onMouseButton1Click)
Ad

Answer this question