Scripting with Lua and sol2
The engine is written in C++ for speed and control; a lot of game code doesn't need either. Quest logic, dialogue triggers, AI tuning, UI flows and level events change daily during development, and recompiling and restarting a C++ build for each tweak is slow. A scripting layer lets that code be edited while the game runs, by people who may not be C++ programmers, in a sandbox that cannot crash the engine.
Lua is the classic choice: a small interpreter written in C, fast for an interpreter, easy to embed, and used by many shipped games (and the Lua course teaches the language). sol2 (ThePhD, MIT) is a header-only C++ binding library that turns the Lua C API's manual stack pushing into one-line bindings.
What a binding layer does, modelled
Every scripting integration has the same pieces, whatever the language:
| Piece | Purpose |
|---|---|
| binding table | the only engine functions scripts can reach (the sandbox) |
| argument conversion | script values ⇄ C++ types, with errors instead of crashes |
| entry points | engine calls named script functions on events (on_spawn, on_hit) |
| error reporting | a failing script logs file and line and the game carries on |
The model below has a deliberately tiny "script language" (one command per line) so the whole thing fits on screen, but the engine side is exactly what you build around Lua:
#include <functional>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
struct Enemy { std::string name; int hp; double speed; };
class ScriptHost {
using Fn = std::function<std::string(const std::vector<std::string>&)>;
std::map<std::string, Fn> bindings;
public:
void bind(const std::string& name, Fn fn) { bindings[name] = std::move(fn); }
// runs a script; one bad line logs an error and the rest still runs
void run(const std::string& file, const std::string& source) {
std::istringstream lines(source);
std::string line;
for (int n = 1; std::getline(lines, line); n++) {
std::istringstream words(line);
std::string cmd, w;
std::vector<std::string> args;
words >> cmd;
while (words >> w) args.push_back(w);
if (cmd.empty() || cmd[0] == '-') continue; // blank line or comment
auto it = bindings.find(cmd);
std::string err = it == bindings.end() ? "unknown function '" + cmd + "'" : it->second(args);
if (!err.empty()) std::cout << "[script error] " << file << ":" << n << ": " << err << "\n";
}
}
};
int main() {
std::map<std::string, Enemy> enemies;
ScriptHost host;
host.bind("spawn", [&](const std::vector<std::string>& a) -> std::string {
if (a.size() != 2) return "spawn expects 2 arguments, got " + std::to_string(a.size());
enemies[a[0]] = {a[0], std::stoi(a[1]), 1.0};
return "";
});
host.bind("set_speed", [&](const std::vector<std::string>& a) -> std::string {
if (a.size() != 2) return "set_speed expects 2 arguments";
auto it = enemies.find(a[0]);
if (it == enemies.end()) return "no enemy named '" + a[0] + "'";
try { it->second.speed = std::stod(a[1]); } catch (...) { return "'" + a[1] + "' is not a number"; }
return "";
});
host.bind("log", [&](const std::vector<std::string>& a) -> std::string {
std::cout << "[lua]";
for (auto& s : a) std::cout << " " << s;
std::cout << "\n";
return "";
});
std::string level1 =
"-- level1.lua\n"
"spawn goblin 30\n"
"spawn troll 120\n"
"set_speed goblin 2.5\n"
"set_speed trol 0.5\n" // typo
"delete_save_file\n" // not bound: unreachable from scripts
"set_speed troll fast\n"
"log level ready\n";
host.run("level1.lua", level1);
for (auto& [name, e] : enemies) std::cout << name << ": hp " << e.hp << ", speed " << e.speed << "\n";
// hot reload: same entry point, edited source, no restart
host.run("level1.lua", "set_speed troll 0.8\nlog reloaded\n");
std::cout << "troll speed after reload: " << enemies["troll"].speed << "\n";
}[script error] level1.lua:5: no enemy named 'trol'
[script error] level1.lua:6: unknown function 'delete_save_file'
[script error] level1.lua:7: 'fast' is not a number
[lua] level ready
goblin: hp 30, speed 2.5
troll: hp 120, speed 1
[lua] reloaded
troll speed after reload: 0.8
Three script mistakes produced three log lines with file and line numbers, and the game state stayed valid. delete_save_file simply does not exist from the script's point of view: the binding table is the sandbox.
The same with sol2
#define SOL_ALL_SAFETIES_ON 1 // type checks on every call; worth it outside hot loops
#include <sol/sol.hpp>
struct Vec3 { float x = 0, y = 0, z = 0; };
struct Enemy { std::string name; int hp = 100; float speed = 1.0f; Vec3 position; };
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::math, sol::lib::string, sol::lib::table);
// not io or os: scripts shouldn't touch files or run programs
lua.new_usertype<Vec3>("Vec3",
sol::constructors<Vec3(), Vec3(float, float, float)>(),
"x", &Vec3::x, "y", &Vec3::y, "z", &Vec3::z);
lua.new_usertype<Enemy>("Enemy",
"name", sol::readonly(&Enemy::name),
"hp", &Enemy::hp,
"speed", &Enemy::speed,
"position", &Enemy::position);
lua.set_function("log", [](const std::string& msg) { engineLog(LogLevel::Info, "lua", msg); });
lua.set_function("spawn", [&world](const std::string& kind, Vec3 at) -> Enemy& { return world.spawn(kind, at); });
auto loaded = lua.safe_script_file("scripts/goblin.lua", sol::script_pass_on_error);
if (!loaded.valid()) {
sol::error err = loaded;
engineLog(LogLevel::Error, "lua", err.what()); // includes file:line
}
sol::protected_function onUpdate = lua["on_update"];
for (Enemy& e : world.enemies) {
auto result = onUpdate(e, dt); // pcall: errors come back as values
if (!result.valid()) { sol::error err = result; engineLog(LogLevel::Error, "lua", err.what()); }
}-- scripts/goblin.lua
function on_update(enemy, dt)
enemy.position.x = enemy.position.x + enemy.speed * dt
if enemy.hp < 20 then
enemy.speed = 3.0 -- flee
log(enemy.name .. " is fleeing")
end
endPoints to watch:
- Use
protected_functionandsafe_scriptfor everything that runs untrusted or frequently edited code. An unprotected Lua error longjmps or throws out of your frame. - Lifetimes cross the boundary. Returning
Enemy&to Lua gives the script a pointer; if the enemy is destroyed while a script still holds it, the next access is a use-after-free. Expose stable handles (see Generational Handles) or entity IDs to scripts, and validate them on every call. - Don't call Lua per entity per frame for thousands of entities. The C++/Lua transition costs far more than a C++ call. Scripts should react to events and set parameters; C++ systems should do the per-entity loops.
- Hot reload is
safe_script_fileagain on the changed file (watch the file, as in the Hot Reload lesson). Keep state in C++ components or in a table you deliberately preserve, not in script globals that a reload resets. - Build: vcpkg ports
sol2(sol2::sol2) andlua(find_package(Lua), thenLUA_INCLUDE_DIRandLUA_LIBRARIES). sol2 also supports LuaJIT; check its documentation for the Lua versions your sol2 release supports.
Alternatives
| Option | Notes |
|---|---|
| Lua + sol2 | smallest footprint, huge game-industry track record |
| LuaJIT | much faster Lua 5.1 dialect; not allowed where JIT is banned (iOS, consoles) |
| Luau | Roblox's typed, sandboxed Lua derivative, open source |
| AngelScript, Wren, Squirrel | C-like syntax, built for embedding in games |
| C# (.NET hosting) | what Unity and Godot offer; heavier runtime |
| Hot-reloaded C++ DLLs | no language boundary; tools such as Live++ or a DLL reload loop |
| Visual scripting | node graphs for designers (Unreal Blueprints); a large tool investment |
Test yourself
In an embedded scripting layer, what acts as the sandbox?
- The script file extension
- The set of functions and types the engine explicitly binds; scripts can reach nothing else
- Running scripts on the GPU
- Compiling scripts to C++
Why prefer sol::protected_function for calling script entry points?
- It is faster
- Errors are returned as a result you can check and log instead of unwinding through engine code
- It runs on another thread
- It disables the garbage collector
Why is exposing raw C++ references to long-lived Lua variables risky?
- Lua can't read references
- The C++ object may be destroyed while the script still holds it, leading to use-after-free
- References are copied every frame
- It disables hot reload