Counter control

In our Lua API, we give users the ability to make their own custom menu controls. Here's an example on how to make a simple counter:

local Counter = {} do
  -- Create the metatable for this control.
  Counter.__index = gui.LuaControlProto()

  -- Specify any initial data. This is propagated to any LuaControl initialized with this metatable.
  Counter.__index.initialData = {
    counter = 0
  }

  -- Override any methods you wish.
  function Counter.__index:onRender(contents, scrollbar, mins, maxs)
    contents:AddRectFilled(draw.Rect(mins, maxs), draw.color.White())

    contents.font = draw.fonts['gui_bold']
    contents:AddText(mins + draw.Vec2(5, 5), tostring(self.data.counter), draw.color.Black())
    contents.font = nil
  end

  function Counter.__index:onMouseDown(key)
    if key == gui.MouseButton.LEFT then
      self.data.counter = self.data.counter + 1
      self:LockInput() -- Makes sure you can't drag the menu while clicking.
    end
  end

  function Counter.__index:onMouseUp(key)
    if key == gui.MouseButton.LEFT then
      self:UnlockInput() -- Makes sure you can drag menu again after clicking.
    end
  end

  function Counter.create(id, initialValue)
    local control = gui.LuaControl(id, Counter.__index, draw.Vec2(), draw.Vec2(0, 24)) do
      control.sizeToParentW = true -- Resizes the control to the width of the container.
      control.data.counter = initialValue or 0
      control.margin = draw.Rect(3, 7, 3, 7) -- Default control margin
    end

    return control
  end
end

gui.ctx:find('lua>elements a'):add(Counter.create('counter'))

With that, you'll have an extremely simple counter that you can click on to increment.

Last updated