{"data":{"slug":"discovered-3c85b95f19eb944ae5d1c9c8a8daa8cc60029a58c3581009","title":"Writing Emilua Lua","summary":"Write, review, debug, and test Lua code for Emilua projects, including handling modules, error categories, and specific I\/O operations. The skill targets Emilua 0.12 and covers differences from upstream Lua.","url":"https:\/\/skillshunter.net\/skills\/discovered-3c85b95f19eb944ae5d1c9c8a8daa8cc60029a58c3581009","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-3c85b95f19eb944ae5d1c9c8a8daa8cc60029a58c3581009","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-3c85b95f19eb944ae5d1c9c8a8daa8cc60029a58c3581009.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-3c85b95f19eb944ae5d1c9c8a8daa8cc60029a58c3581009\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure the Emilua version matches 0.12, and use the `C` table and numeric `errno` results in `init.script`. Define package-owned errors in an RDF Turtle category and use `err:togeneric()` for portable error handling.","instructions":"---\nname: writing-emilua-lua\ndescription: Use when writing, reviewing, debugging, or testing Lua code for Emilua, including packages, unit tests, emilua --test, module imports\/exports, RDF error categories, fibers, byte_span buffers, stream I\/O, network protocols, regex, spawn_vm, and init.script programs.\n---\n\n# Writing Emilua Lua\n\n## Overview\n\nEmilua uses LuaJIT\/Lua 5.1 syntax, but standard Lua module, standard-library, and blocking-I\/O assumptions often do not apply. Match the project's Emilua version; these conventions target 0.12.\n\n## Choose the Environment\n\nIn normal Emilua modules and actor entry points, prefer built-in facilities over external libraries or hand-written substitutes when they meet the requirement. Use the native `regex` module (`new`, `match`, `search`, `split`, and `patsplit`) for regular expressions; it accepts strings and byte spans directly.\n\n`spawn_vm`'s `subprocess.init.script` is a different environment. It is source text running synchronously in a separate, temporary Lua state before the actor starts. This state uses upstream-style Lua libraries, including `io`, `os`, `package`, and `debug`, but does not provide the normal Emilua module environment or facilities by default.\n\n- Do not use Emilua module exports\/imports, `byte_span`, `spawn`, `stream`, fibers, or RDF error categories inside `init.script`.\n- Use the documented `C` table, optional descriptor `arg`, helper functions, strings, and numeric `errno` results. The script is not a module and has no exports.\n- `errexit` defaults to true, aborting on failed `C` calls. If disabled, check numeric results explicitly. Upstream Lua errors need their own handling.\n- Keep initialization values local to the script; they do not transfer automatically to the actor VM. Pass actor source through `source_tree_cache` when filesystem access is removed.\n\n## Modules\n\n- Export public names as intentional globals: `function new() ... end` or `reply = ...`. Keep private helpers and state `local`.\n- The importer receives the module environment. Do not export through `return` or replace the environment with `setfenv(0, ...)`.\n- From `init.lua`, import children with `require '.\/child'`. From a leaf file, import siblings with `require '..\/sibling'`. Use bare names for core\/external modules such as `require 'stream'`.\n- Use `EMILUA_PATH`, not `LUA_PATH` or `package.path`. Avoid cyclic imports. Keep imports in the module's main fiber, normally at top level; `require` may suspend.\n- Import RDF error categories with a root-qualified path such as `require '\/my_package\/error_category'`; a relative import does not resolve the `.ttl` module in 0.12.\n\n## Errors\n\nDefine package-owned errors in an RDF Turtle category. Add `cat:generic_error` mappings when a portable generic condition is meaningful. Compare error objects with `==` against category values; use `err:togeneric()` for portable generic handling. Do not parse error strings. Preserve underlying OS\/Asio errors when their original category matters.\n\n```lua\nlocal category = require '\/greeter\/error_category'\n\nfunction new(name)\n    if name == '' then\n        error(category.invalid_name)\n    end\n    return 'Hello, ' .. name .. '!'\nend\n```\n\n## Runtime and I\/O\n\n- In normal module\/actor VMs, LuaJIT provides Lua 5.1 plus selected extensions. These VMs disable `io`, `os`, `package`, and `debug`; use Emilua's `filesystem`, `file`, `system`, `time`, and related modules instead. This restriction does not apply to the separate `init.script` state.\n- `byte_span` and `spawn` are globals, not modules requiring `require`.\n- I\/O calls block only the current fiber. Use `spawn()` for concurrency; `join()` or `detach()` deliberately. Use actors when isolation is required.\n- `read_some()` and `write_some()` may transfer fewer bytes than requested. Prefer `stream.read_all()` and `stream.write_all()` when the whole buffer is required. Reads need mutable `byte_span` buffers.\n- Byte spans are 1-indexed views. Use `sub()`, `first()`, `last()`, `copy()`, and `append()`; respect length versus capacity and do not retain mutable I\/O spans as parser state.\n- Set scanner separators explicitly (`\"\\r\\n\"` for HTTP). Check `record_terminator` for EOF-terminated records. Call `remove_line()` before `buffer()`, preserve surplus bytes, and restore them with `set_buffer()` when returning to textual parsing.\n- Do not overlap composed reads or composed writes on an unsynchronized stream. Serialize same-direction operations with a mutex when necessary.\n- Suspension points are cancellation points. Use `scope()` and `scope_cleanup_push()` for cancellation-safe resource cleanup.\n\n## Unit Tests\n\n- Place in-module tests behind `if _CONTEXT == 'test' then ... end`. Run them through the application entry point with `emilua --test <entrypoint>` (for example, `emilua --test .` from a module directory), not plain `emilua`.\n- Test context propagates through relative imports, but not imported external packages. Run an external package's own entry point to execute its internal tests.\n- Use `assert()` and Emilua-native facilities rather than blocking, upstream-Lua test frameworks. Keep test-only helpers local.\n- Join spawned test fibers with `join()` so their failures propagate; do not detach test workers. Close resources and use fixed inputs rather than sleeps, timing assumptions, or external networks.\n- For golden-output suites, pair `name.lua` with `name.out` containing exact deterministic output. Upstream's Meson golden runner executes standalone test files directly; use `--test` when enabling in-module test context, not as a substitute for the golden-output comparison.\n\n## Common Mistakes\n\n| Standard-Lua habit | Emilua correction |\n|---|---|\n| `return { new = new }` | Export `new` in the module environment |\n| `require 'pkg.util'` for project files | Use the documented relative or root-qualified form |\n| Plain-string library errors | Define and raise an RDF category value |\n| `io.open`, `os.time`, `package.path` in a normal module | Use the corresponding Emilua module |\n| Using normal Emilua APIs in `init.script` | Use its separate upstream-Lua and `C` APIs |\n| Assuming full stream reads\/writes | Use composed operations or handle short transfers |\n| Discarding scanner read-ahead | Transfer the scanner buffer across parsing layers |\n| Running in-module tests with plain `emilua` | Use `emilua --test <entrypoint>` |\n| Detaching spawned test workers | Join them so assertion failures propagate |\n\nBefore finishing, identify the execution environment, inspect exports, imports, error categories, native-facility choices, short I\/O, buffer lifetimes, cleanup paths, and test-mode execution. See [reference.md](reference.md) for complete examples and official documentation links.\n","use_cases":["Writing Emilua modules with direct-global exports and private locals","Defining package-owned RDF Turtle error categories","Handling I\/O operations with `byte_span` and `stream` in Emilua","Testing Emilua code with `emilua --test` and golden-output tests"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/gitlab.com\/emilua\/agent-skills\/-\/blob\/47b1b9fc62a32492d7d632ccf917f135f083d0dd\/SKILL.md","source_commit":"47b1b9fc62a32492d7d632ccf917f135f083d0dd","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T06:54:25.000000Z","updated_at":"2026-12-03T16:19:55.000000Z","seo_title":"Writing Emilua Lua - Skill for Emilua 0.12 Development","seo_description":"Learn to write, review, debug, and test Lua code for Emilua projects with a focus on Emilua 0.12 conventions, including module environments, error handling, and I\/O.","seo_keywords":["Emilua Lua","Emilua 0.12","Lua module environments","RDF error categories","Emilua I\/O operations","Emilua testing"]}}