CLua Documentation


📂 Include & Import (C# ↔ Lua)

These two mechanisms allow modular, structured Lua code in CLua.


🔧 include("path"[, ...])

Loads one or more Lua files and executes them immediately in the current environment.

include("utils/test");                      -- loads and runs utils/test.lua
include("utils/test", "menu/main");         -- loads utils/test.lua, then menu/main.lua

Features:

  • Included code can read and modify variables in the current environment
  • Supports an optional table as the last argument to target a specific environment
include("utils/constants", _ENV) -- force inclusion into a specific environment

Note: _ENV is the current environment — _G at the top level, or the module's own environment when called inside import.

  • When used inside an import module, include correctly loads into the module's own environment.

⚠️ tryInclude("path"[, ...])

Identical to include, but silently ignores missing files instead of throwing an error.

tryInclude("utils/optional_config") -- no effect if file does not exist

🧩 import("file"[, fallbackEnv])

Loads a Lua file as a module running in its own isolated environment. The module's environment is returned as a table.

local mymod = import("utils/mymodule")
mymod.doSomething()

Optional second parameter:

Value Behavior
Not provided Module's __index is set to the current environment (the calling script's _ENV)
A table The table is used as the __index fallback
Invalid (false, number, etc.) __index is set to the base CLua environment (sandboxed built-ins + registered C# functions)

Features:

  • Does not overwrite the global environment
  • The module cannot see the caller's local variables
  • All local functions and variables declared in the module are available in the returned table
  • Can be linked to another module or a custom environment via the second parameter

Log note:

  • Imported modules are logged after (i.e. above) the script that imported them

📌 Summary

Function Scope Sees Environment Overwrites Globals?
include shared (caller's) ✅ Yes ✅ Yes (unless local)
tryInclude shared (caller's) ✅ Yes ✅ Yes (unless local)
import isolated (_ENV) ✅ Via fallback ❌ No

✍️ Examples

Loading module sections into a module environment

local menu = import("window/menu");
include("menuSec2", "menuSec4", "menuSec3", menu);
-- menuSec*.lua are loaded into the 'menu' module's environment

Import with custom fallback environment

local fallback = { shared = true }
local mod = import("module", fallback)
print(mod.shared) -- outputs: true

Import with no fallback (clean isolated environment)

local mod = import("module", false)
-- mod has no access to any globals — fully sandboxed