# Lua

Source: https://libtmux.org/en/lua/v0.1.1/

> libtmux for Lua, version v0.1.1.

![](https://libtmux.org/en/brand/lua/library/logo.svg)

Drive a real tmux from Lua.

libtmux

You are reading the **v0.1.1** documentation. Use the version control in the header to move between releases, or the port dropdown to find a corresponding page in another language.

## Start with Lua

Example details

\+ Error handling + Cleanup

```lua
local adapter = require("libtmux.runtime.luv")
local uv = require("luv")


local function must(value, err)
    if err ~= nil then error(err, 0) end
    return value
end


local binary
for directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do
    local candidate = uv.fs_realpath(directory .. "/tmux")
    if candidate and uv.fs_access(candidate, "X") then
        binary = candidate
        break
    end
end
assert(binary, "tmux must be installed on PATH")


local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))
local socket = directory .. "/tmux.sock"


local function tmux(arguments)
    local args = { "-S", socket }
    for _, argument in ipairs(arguments) do
        args[#args + 1] = argument
    end


    local timer = assert(uv.new_timer())
    local process, status
    process = assert(uv.spawn(binary, {
        args = args,
        stdio = { nil, 1, 2 },
    }, function(code)
        status = code
        process:close()
        timer:stop()
        timer:close()
    end))
    timer:start(10000, 0, function()
        process:kill("sigkill")
    end)
    uv.run()
    assert(status == 0, "tmux command failed or timed out")
end


-- This Lua API connects to an existing daemon. Start our own first.
tmux({
    "-f", "/dev/null", "new-session", "-d",
    "-s", "work", "-n", "main", "/bin/sh",
})


must(adapter.run(function(runtime)
    local server = must(runtime:connect({
        binary = binary,
        socket_path = socket,
    }):await())


    local created = must(server:new_session({
        name = "quickstart",
        window_name = "main",
        argv = { "/bin/sh" },
    }):await())


    local logs = must(created.session:new_window({
        name = "logs",
        argv = { "/bin/cat" },
    }):await())
    must(logs.pane:split({
        direction = "right",
        percent = 40,
        argv = { "/bin/cat" },
    }):await())


    local marker = "libtmux-ready"
    local quoted = "'" .. binary:gsub("'", "'\\''") .. "'"
    local command = ("printf '\\nlibtmux ready\\n'; "
        .. "%s wait-for -S %s"):format(quoted, marker)
    must(created.pane:send_text(command):await())
    must(created.pane:send_keys({ "Enter" }):await())
    must(server:command(
        { "wait-for", marker },
        { timeout = 10000 }
    ):await())


    local capture = must(created.pane:capture():await())
    assert(must(capture:text()):find(
        "\nlibtmux ready\n", 1, true
    ), "pane output was not captured")
    print("libtmux ready")


    must(server:close():await())
    return true
end))
```

```lua
local adapter = require("libtmux.runtime.luv")
local uv = require("luv")


local function must(value, err)
    if err ~= nil then error(err, 0) end
    return value
end


local binary
for directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do
    local candidate = uv.fs_realpath(directory .. "/tmux")
    if candidate and uv.fs_access(candidate, "X") then
        binary = candidate
        break
    end
end
assert(binary, "tmux must be installed on PATH")


local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))
local socket = directory .. "/tmux.sock"


local function tmux(arguments)
    local args = { "-S", socket }
    for _, argument in ipairs(arguments) do
        args[#args + 1] = argument
    end


    local timer = assert(uv.new_timer())
    local process, status
    process = assert(uv.spawn(binary, {
        args = args,
        stdio = { nil, 1, 2 },
    }, function(code)
        status = code
        process:close()
        timer:stop()
        timer:close()
    end))
    timer:start(10000, 0, function()
        process:kill("sigkill")
    end)
    uv.run()
    assert(status == 0, "tmux command failed or timed out")
end


local ok, failure = xpcall(function()
    -- This Lua API connects to an existing daemon. Start our own first.
    tmux({
        "-f", "/dev/null", "new-session", "-d",
        "-s", "work", "-n", "main", "/bin/sh",
    })


    must(adapter.run(function(runtime)
        local server = must(runtime:connect({
            binary = binary,
            socket_path = socket,
        }):await())


        local created = must(server:new_session({
            name = "quickstart",
            window_name = "main",
            argv = { "/bin/sh" },
        }):await())


        local logs = must(created.session:new_window({
            name = "logs",
            argv = { "/bin/cat" },
        }):await())
        must(logs.pane:split({
            direction = "right",
            percent = 40,
            argv = { "/bin/cat" },
        }):await())


        local marker = "libtmux-ready"
        local quoted = "'" .. binary:gsub("'", "'\\''") .. "'"
        local command = ("printf '\\nlibtmux ready\\n'; "
            .. "%s wait-for -S %s"):format(quoted, marker)
        must(created.pane:send_text(command):await())
        must(created.pane:send_keys({ "Enter" }):await())
        must(server:command(
            { "wait-for", marker },
            { timeout = 10000 }
        ):await())


        local capture = must(created.pane:capture():await())
        assert(must(capture:text()):find(
            "\nlibtmux ready\n", 1, true
        ), "pane output was not captured")
        print("libtmux ready")


        must(server:close():await())
        return true
    end))
end, debug.traceback)


if not ok then error(failure, 0) end
```

```lua
local adapter = require("libtmux.runtime.luv")
local uv = require("luv")


local function must(value, err)
    if err ~= nil then error(err, 0) end
    return value
end


local binary
for directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do
    local candidate = uv.fs_realpath(directory .. "/tmux")
    if candidate and uv.fs_access(candidate, "X") then
        binary = candidate
        break
    end
end
assert(binary, "tmux must be installed on PATH")


local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))
local socket = directory .. "/tmux.sock"


local function tmux(arguments)
    local args = { "-S", socket }
    for _, argument in ipairs(arguments) do
        args[#args + 1] = argument
    end


    local timer = assert(uv.new_timer())
    local process, status
    process = assert(uv.spawn(binary, {
        args = args,
        stdio = { nil, 1, 2 },
    }, function(code)
        status = code
        process:close()
        timer:stop()
        timer:close()
    end))
    timer:start(10000, 0, function()
        process:kill("sigkill")
    end)
    uv.run()
    assert(status == 0, "tmux command failed or timed out")
end


local ok, failure = pcall(function()
    -- This Lua API connects to an existing daemon. Start our own first.
    tmux({
        "-f", "/dev/null", "new-session", "-d",
        "-s", "work", "-n", "main", "/bin/sh",
    })


    must(adapter.run(function(runtime)
        local server = must(runtime:connect({
            binary = binary,
            socket_path = socket,
        }):await())


        local created = must(server:new_session({
            name = "quickstart",
            window_name = "main",
            argv = { "/bin/sh" },
        }):await())


        local logs = must(created.session:new_window({
            name = "logs",
            argv = { "/bin/cat" },
        }):await())
        must(logs.pane:split({
            direction = "right",
            percent = 40,
            argv = { "/bin/cat" },
        }):await())


        local marker = "libtmux-ready"
        local quoted = "'" .. binary:gsub("'", "'\\''") .. "'"
        local command = ("printf '\\nlibtmux ready\\n'; "
            .. "%s wait-for -S %s"):format(quoted, marker)
        must(created.pane:send_text(command):await())
        must(created.pane:send_keys({ "Enter" }):await())
        must(server:command(
            { "wait-for", marker },
            { timeout = 10000 }
        ):await())


        local capture = must(created.pane:capture():await())
        assert(must(capture:text()):find(
            "\nlibtmux ready\n", 1, true
        ), "pane output was not captured")
        print("libtmux ready")


        must(server:close():await())
        return true
    end))
end)


local cleaned, cleanup_error = pcall(function()
    if uv.fs_stat(socket) then tmux({ "kill-server" }) end
    local removed, _, code = uv.fs_unlink(socket)
    assert(removed or code == "ENOENT", "could not remove owned socket")
    assert(uv.fs_rmdir(directory))
end)


if not cleaned then io.stderr:write(tostring(cleanup_error), "\n") end
if not ok then error(failure, 0) end
assert(cleaned, "cleanup failed; retained " .. directory)
```

```lua
local adapter = require("libtmux.runtime.luv")
local uv = require("luv")


local function must(value, err)
    if err ~= nil then error(err, 0) end
    return value
end


local binary
for directory in (os.getenv("PATH") or ""):gmatch("[^:]+") do
    local candidate = uv.fs_realpath(directory .. "/tmux")
    if candidate and uv.fs_access(candidate, "X") then
        binary = candidate
        break
    end
end
assert(binary, "tmux must be installed on PATH")


local directory = assert(uv.fs_mkdtemp("/tmp/ltx-lua-home-XXXXXX"))
local socket = directory .. "/tmux.sock"


local function tmux(arguments)
    local args = { "-S", socket }
    for _, argument in ipairs(arguments) do
        args[#args + 1] = argument
    end


    local timer = assert(uv.new_timer())
    local process, status
    process = assert(uv.spawn(binary, {
        args = args,
        stdio = { nil, 1, 2 },
    }, function(code)
        status = code
        process:close()
        timer:stop()
        timer:close()
    end))
    timer:start(10000, 0, function()
        process:kill("sigkill")
    end)
    uv.run()
    assert(status == 0, "tmux command failed or timed out")
end


local ok, failure = xpcall(function()
    -- This Lua API connects to an existing daemon. Start our own first.
    tmux({
        "-f", "/dev/null", "new-session", "-d",
        "-s", "work", "-n", "main", "/bin/sh",
    })


    must(adapter.run(function(runtime)
        local server = must(runtime:connect({
            binary = binary,
            socket_path = socket,
        }):await())


        local created = must(server:new_session({
            name = "quickstart",
            window_name = "main",
            argv = { "/bin/sh" },
        }):await())


        local logs = must(created.session:new_window({
            name = "logs",
            argv = { "/bin/cat" },
        }):await())
        must(logs.pane:split({
            direction = "right",
            percent = 40,
            argv = { "/bin/cat" },
        }):await())


        local marker = "libtmux-ready"
        local quoted = "'" .. binary:gsub("'", "'\\''") .. "'"
        local command = ("printf '\\nlibtmux ready\\n'; "
            .. "%s wait-for -S %s"):format(quoted, marker)
        must(created.pane:send_text(command):await())
        must(created.pane:send_keys({ "Enter" }):await())
        must(server:command(
            { "wait-for", marker },
            { timeout = 10000 }
        ):await())


        local capture = must(created.pane:capture():await())
        assert(must(capture:text()):find(
            "\nlibtmux ready\n", 1, true
        ), "pane output was not captured")
        print("libtmux ready")


        must(server:close():await())
        return true
    end))
end, debug.traceback)


local cleaned, cleanup_error = pcall(function()
    if uv.fs_stat(socket) then tmux({ "kill-server" }) end
    local removed, _, code = uv.fs_unlink(socket)
    assert(removed or code == "ENOENT", "could not remove owned socket")
    assert(uv.fs_rmdir(directory))
end)


if not cleaned then io.stderr:write(tostring(cleanup_error), "\n") end
if not ok then error(failure, 0) end
assert(cleaned, "cleanup failed; retained " .. directory)
```

Run this example

POSIX shell, Git, tmux 3.3a or newer, Lua 5.5.1, LuaRocks 3.13.0, CMake and a C compiler; setup installs luv 1.52.1-0.

Save the program above as `quickstart.lua` in a new directory, along with the files below.

Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes. The program stops its private tmux server and removes any temporary files it created when it finishes. Error handling adds diagnostics; every version checks required results and deadlines.

### Setup and run

```bash
git init -q source
git -C source fetch -q --depth=1 \
  https://github.com/libtmux/libtmux-lua.git \
  0395620d362ef75c74cd488f9577afda68922586
git -C source checkout -q --detach FETCH_HEAD
luarocks --tree .rocks install luv 1.52.1-0
(cd source && luarocks --tree ../.rocks make \
  rockspecs/libtmux-scm-1.rockspec)
```

```bash
unset TMUX TMUX_PANE
export ENV=/dev/null BASH_ENV=/dev/null SHELL=/bin/sh
eval "$(luarocks --tree .rocks path)"
lua quickstart.lua
```

### Expected output

```text
libtmux ready
```

Library revision: [0395620d362e](https://github.com/libtmux/libtmux-lua/tree/0395620d362ef75c74cd488f9577afda68922586).

[More Lua examples →](https://libtmux.org/en/lua/v0.1.1/examples/)

### Install `libtmux`

```console
$ luarocks --local install libtmux
```

### [Topics](https://libtmux.org/en/lua/v0.1.1/topics/)

[Subject-by-subject, with Lua in every code block.](https://libtmux.org/en/lua/v0.1.1/topics/)

### [Guides](https://libtmux.org/en/lua/v0.1.1/guides/)

[Task guides for Lua.](https://libtmux.org/en/lua/v0.1.1/guides/)

### [Examples](https://libtmux.org/en/lua/v0.1.1/examples/)

[Complete programs, sourced from the code each port tests.](https://libtmux.org/en/lua/v0.1.1/examples/)

### [Concepts](https://libtmux.org/en/lua/v0.1.1/concepts/)

[The domain model every port shares.](https://libtmux.org/en/lua/v0.1.1/concepts/)

## Packages and integrations

### [luv and Neovim](https://libtmux.org/en/lua/v0.1.1/guides/runtime/)

[Use the documented libuv and Neovim runtime integrations.](https://libtmux.org/en/lua/v0.1.1/guides/runtime/)

## API references

### [Official reference](https://libtmux.org/en/lua/v0.1.1/reference/)

[Lua API signatures and documentation, with links to related guides and APIs in other languages.](https://libtmux.org/en/lua/v0.1.1/reference/)

[All Lua versions and install instructions](https://libtmux.org/en/lua/)
