๐Ÿ”’ Locker Guide

July 25, 2025 ยท View on GitHub

Lua API Difficulty Version

๐Ÿš€ Quick Start Guide for file locking and process concurrency with LuaDoTheWorld


๐Ÿ“‹ What You'll Learn

  • โœ… How to lock and unlock files
  • โœ… How to manage concurrency between processes
  • โœ… How to use lockers in forked processes

๐Ÿ› ๏ธ Prerequisites

  • LuaDoTheWorld installed and required in your script

๐Ÿ”’ Lock and Unlock a File

local dtw = require("luaDoTheWorld/luaDoTheWorld")

local locker = dtw.newLocker()
locker.lock("a.txt")
-- Do something with the locked file
locker.unlock("a.txt")

๐Ÿค– Locking in Multiple Processes (Fork Example)

Create 30 forks, each writing its number to a file safely using a locker:

local dtw = require("luaDoTheWorld/luaDoTheWorld")

local all_forks = {}
local total_forks = 30

dtw.remove_any("a.txt")

for i = 1, total_forks do
    local fork = dtw.newFork(function()
        local locker = dtw.newLocker()
        locker.lock("a.txt")
        local old = dtw.load_file("a.txt")
        if old == nil then old = "" end
        old = old .. i .. "\n"
        dtw.write_file("a.txt", old)
        locker.unlock("a.txt")
    end)
    all_forks[i] = fork
end

-- Wait for all child processes to finish
for i = 1, total_forks do
    all_forks[i].wait(-1)
end

๐Ÿ“š Quick Reference

FunctionWhat it doesExample
dtw.newLocker()Create a new lockerlocal locker = dtw.newLocker()
locker.lock(path)Lock a filelocker.lock("a.txt")
locker.unlock(path)Unlock a filelocker.unlock("a.txt")
dtw.newFork(fn)Create a new processdtw.newFork(function() ... end)

๐Ÿ“ Notes

  • Lockers prevent file access conflicts between processes (not threads).
  • Only works if all processes use LuaDoTheWorld's locker system.

๐Ÿ†˜ Need Help?

  • ๐Ÿ“– Check the main SDK documentation
  • ๐Ÿ” Look at other example scripts in the SDK
  • ๐Ÿ› Report issues on our GitHub repository

Footer