Switch in Lua

Our first program demonstrates the use of switch statements to express conditionals across many branches. Here’s the full source code translated to Lua.

-- Import necessary libraries
local os = require("os")

-- Function to demonstrate basic switch-case equivalent
local function main()
    local i = 2
    print("Write " .. i .. " as ")
    
    -- Lua doesn't have direct switch-case, use if-elseif-else instead
    if i == 1 then
        print("one")
    elseif i == 2 then
        print("two")
    elseif i == 3 then
        print("three")
    end

    -- Switch-case for days of the week
    local day = os.date("*t").wday
    if day == 7 or day == 1 then
        print("It's the weekend")
    else
        print("It's a weekday")
    end

    -- Switch-case for time of day
    local hour = os.date("*t").hour
    if hour < 12 then
        print("It's before noon")
    else
        print("It's after noon")
    end

    -- Type switch-case equivalent
    local function whatAmI(i)
        local t = type(i)
        if t == "boolean" then
            print("I'm a boolean")
        elseif t == "number" then
            print("I'm a number")
        else
            print("Don't know type " .. t)
        end
    end

    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")
end

main()

Here’s how to run the program:

Save the code as switch.lua and use the Lua interpreter to execute it.

$ lua switch.lua
Write 2 as two
It's a weekday
It's after noon
I'm a boolean
I'm a number
Don't know type string

Switch statements do not exist in Lua natively, so we use if-elseif-else statements to achieve similar functionality. This example shows how you can handle conditional branching and type checking in Lua.