pesde goatsoft / lucy

Switch

An on and off switch with an optional label, for settings. The whole row is the hit area, and the switch grows on touch and console. It comes in the same sizes as the other controls, and a row is as tall as a Button of its size, so a switch lines up with buttons and toggles beside it.

Switch exampleSwitch example
Lucy.Stack.new({
    gap = "Space3",
    children = {
        Lucy.Switch.new({
            label = "Club lights",
            checked = true,
            onCheckedChange = function(on)
                app.toast(if on then "Lights up" else "Lights down")
            end,
        }),
        Lucy.Switch.new({ label = "Crowd cheers", checked = true }),
        Lucy.Switch.new({ label = "Show dance names" }),
    },
    Parent = parent,
})

Props

PropTypeDefaultState keyWhat it does
checkedbooleanfalseyesWhether it is on
labelstring""yesText beside the switch
childrentableAnything after the label in its slot, such as a "NEW" badge. They take the label's look and fade when disabled
disabledbooleanfalseyesGreys it out and ignores clicks
size"sm" | "md" | "lg" | "xl""md"yesThe track, the label's text and the row's height, as a Button of the same size
visiblebooleantrueyesShows or hides it
onCheckedChangefunctionCalled with (checked, handle) when it changes

It also takes the props every component takes.

Methods

NameWhat it does
switch:toggle()Turns it on if off, off if on

Examples

Keep a setting in app state and the switch in step:

Switch exampleSwitch example
local lights = app.state:ref("settings.lights")

Lucy.Switch.new({ label = "Club lights", checked = lights, Parent = settings })

-- Elsewhere, game code reads the same value.
Lucy.watch(lights, function(on)
    discoBall.Enabled = on
end)

Grey a switch out while something loads:

Switch exampleSwitch example
local loading = Lucy.ref(true)

Lucy.Switch.new({ label = "Light show", disabled = loading, Parent = settings })

A switch comes in the same sizes as the other controls, and each size is as tall as a Button of that size, so a row of controls lines up. Go a size up on a phone, where it needs to be easy to tap:

Switch exampleSwitch example
Lucy.Stack.new({
    gap = "Space3",
    children = {
        Lucy.Switch.new({ label = "Small", size = "sm", checked = true }),
        Lucy.Switch.new({ label = "Medium", size = "md", checked = true }),
        Lucy.Switch.new({ label = "Large", size = "lg", checked = true }),
        Lucy.Switch.new({ label = "Extra large", size = "xl", checked = true }),
    },
    Parent = parent,
})

Preview

In Studio, from the command bar: Lucy.Preview.show("Switch").