Module System & Python-Style Imports

PyLua modernizes Lua's modular architecture with first-class import statements, high-speed preload tables, and an intelligent package loader pipeline.

1. The `import` Statement

In PyLua, you can import built-in libraries and external scripts using clean Python-style syntax:

imports_demo.lua
import os
import engine
import vector
import hash

print("Operating System: " .. os.getenv("OS"))
v = vector.Vector2(100, 200)
print("Vector length: " .. v:length())

How the Compiler Translates `import` Under the Hood

In src/parser/impl/lparser_stat.c, the importstat function transforms import X into optimized bytecode at compile time:

Source Code: `import vector`
                   │
                   ▼
         importstat() [lparser_stat.c]
                   │
  1. Resolves `require` function via buildvar(ls, "require", &f)
  2. Pushes string literal "vector" as argument
  3. Emits OP_CALL (calls require("vector"))
  4. Automatically allocates a local variable named `vector`
  5. Assigns the return value to the new local variable!
                   │
                   ▼
Resulting Bytecode is 100% equivalent to: `local vector = require("vector")`
with ZERO runtime overhead!

2. Traditional `require()` & Backward Compatibility

Standard Lua require() is fully supported alongside import:

require_demo.lua
local math = require("math")
local customModule = require("utils.math_helpers")

3. The Module Search Pipeline (`package.searchers`)

When a module is requested via import or require(), PyLua inspects the package.loaded cache. If the module has already been loaded, the cached table is returned instantly. Otherwise, the engine queries four sequential searchers:

  1. Preload Table (package.preload): Direct C loaders. PyLua preloads native modules here (vector, hash, gui, request, engine) for instant startup without disk I/O.
  2. PyLua Source Loader (package.path): Searches disk directories matching templates like ./?.lua;./src/?.lua.
  3. C Dynamic Library Loader (package.cpath): Searches for compiled C modules matching ./?.dll (Windows) or ./?.so (Linux).
  4. All-in-One Submodule Loader: Searches for root container libraries for nested submodules.

4. Creating Custom PyLua Modules

Creating a reusable module is as simple as defining a table and returning it at the end of the file:

math_utils.lua
-- math_utils.lua
Utils = {}

function Utils.clamp(val, min, max) {
    if (val < min) { return min }
    if (val > max) { return max }
    return val
}

function Utils.lerp(a, b, t) {
    return a + (b - a) * t
}

return Utils

Consuming the module from another script:

main.lua
import math_utils

smoothedPos = math_utils.lerp(0, 100, 0.5)
print("Smoothed position: " .. smoothedPos)  -- 50.0