Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 32 ยท Real-World Lua

Lua in Games and Embedded Hosts

See how Lua lives inside other programs: the C API idea, host functions, config scripts, LOVE and Roblox Luau differences, and the basics of sandboxing scripts.

Most programming languages want to be the program. Lua was designed to be a guest. It is a small library, written in portable C, that another program links in so that the program can be scripted. The program is called the host: a game engine, a database server, a text editor, a router firmware. The host does the heavy, fast, low-level work. Lua holds the parts that change often and that non-engineers want to touch: levels, rules, menus, settings, AI behavior.

This lesson shows how that partnership works and what changes when you meet Lua inside a real product. Nothing here runs on this site, because it needs a host program, so the real Lua and C code is read-only. The two live examples are JavaScript stand-ins that model the same ideas, and we say so each time. If you want to review the language first, start from Modules and require and Coroutines.

Host and guest

Host A C or C++ program that owns the window, files and network.
Script Lua code that holds rules, levels and settings.
Bridge Functions the host registers so scripts can call back.

The script can only touch what the host chooses to give it.

1 / 2

The C API idea

The host talks to Lua through a stack. There are no wrapper objects: to call a Lua function from C you push the function and its arguments on a virtual stack, ask Lua to call it, and pop the results. To expose a C function to Lua, you write a function that reads its arguments from the stack, does its work, pushes results, and returns how many results it pushed.

Here is a small host in C. It creates a Lua state (one independent interpreter), opens the standard libraries, gives scripts a function called log, and runs a script file. This is real code for Lua 5.4, shown read-only.

C
#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

/* Called from Lua as log("text"). Returns 0 results. */
static int host_log(lua_State *L) {
    const char *message = luaL_checkstring(L, 1);
    printf("[host] %s\n", message);
    return 0;
}

int main(void) {
    lua_State *L = luaL_newstate();   /* a fresh interpreter */
    luaL_openlibs(L);                 /* string, table, math, ... */
    lua_register(L, "log", host_log); /* the bridge */

    if (luaL_dofile(L, "script.lua") != LUA_OK) {
        fprintf(stderr, "script error: %s\n", lua_tostring(L, -1));
    }
    lua_close(L);
    return 0;
}

And the script, which is plain Lua that happens to call a function it never defined:

LUA
log("script started")
local total = 0
for i = 1, 5 do
  total = total + i
end
log("sum is " .. total)

Because log is just a global set by the host, the script needs no require and no knowledge of C. If the host does not register it, the call fails with "attempt to call a nil value (global 'log')". That sentence is the whole security model in one error message: a script can only use what its host put in its world.

Every lua_State is isolated. A host can create hundreds, one per game entity, per user request or per plugin, and they share nothing unless the host connects them.

A model of the bridge

The first example is a JavaScript stand-in. The host object registers functions into a table of globals, and the "script" is a function that receives those globals, exactly like the C program above hands log to the script. A frame loop then calls the script's update function with the elapsed time, which is how game engines drive Lua.

JS Stand-in: a host registers functions and drives update()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a real game the loop is the host's, and the script is called, not the other way round:

sequenceDiagram
  participant H as Host engine
  participant L as Lua script
  H->>L: load()
  loop every frame
    H->>L: update(dt)
    L->>H: spawn(...), log(...)
    H->>L: draw()
  end

The host owns the loop and the script reacts to it.

Scripts as configuration

You do not need a game to benefit from embedding. A Lua file can be a configuration format that is also a real language: comments, computed values, loops and shared constants, with no separate parser to write. The usual pattern is a file that returns a table.

LUA
-- settings.lua
local base_port = 8000

return {
  name = "demo-server",
  ports = { base_port, base_port + 1, base_port + 2 },
  debug = false,
  limits = { users = 100, upload_mb = 20 },
}

The host loads it like any other code (dofile or require), then reads the fields. Unlike JSON, the file can compute base_port + 1. Unlike a full program, you can load it with a restricted environment, which leads to the next section.

Sandboxing basics

Running scripts written by other people (mod authors, plugin users, players) means treating them as untrusted. Lua gives you the main tool for that: the environment of a chunk. In Lua 5.4, load accepts a custom environment table, and the chunk sees only the globals in that table.

LUA
local source = [[
  local total = 0
  for _, n in ipairs({ 3, 4, 5 }) do total = total + n end
  return "sum=" .. total
]]

local env = {
  ipairs = ipairs,
  tostring = tostring,
  string = { format = string.format },
}

-- "t" refuses precompiled bytecode: only source text is accepted.
local chunk, err = load(source, "=user-script", "t", env)
if not chunk then
  print("syntax error: " .. err)
else
  local ok, result = pcall(chunk)
  print(ok, result)
end

Inside that chunk os, io, require, load and debug simply do not exist. A script that calls os.execute("...") gets an error about indexing a nil global instead of running a command. Two more habits complete the basics:

  • Limit time. An infinite loop in a script would freeze the host. A common technique is to run the script in a coroutine and install a count hook with debug.sethook(co, hook, "", 100000) that raises an error after that many VM instructions.
  • Limit memory and surface. Strings can be made huge with string.rep, and the shared string metatable is reachable from any string value. A hand-built environment narrows this, but for genuinely hostile code the safe answer is also to isolate the whole process at the operating-system level.

An environment table is a strong first layer, not a guarantee. Treat it as "scripts can't call what they can't see", and add process-level isolation when the stakes are high.

Our second example models the same idea in JavaScript: the script receives a proxy that raises a Lua-style error for any name the host did not allow.

JS Stand-in: a script that can only see allowed globals

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Lร–VE and Roblox Luau

Two popular platforms use Lua-family languages, and they differ from the standard interpreter in ways that matter when you copy code between them.

Lร–VE (also called Love2D) is a 2D game framework. Your project is a main.lua that defines callbacks the framework calls for you: love.load() once at start, love.update(dt) every frame, love.draw() to render, and input callbacks such as love.keypressed(key). Lร–VE runs on LuaJIT, a fast implementation of Lua 5.1 with extensions, so newer 5.3 and 5.4 features differ: there is no integer subtype and no // operator (LuaJIT does support goto). Tables, closures, metatables and coroutines work as you learned.

Roblox uses Luau, a language derived from Lua 5.1 with its own additions: optional type annotations, continue in loops, compound assignment (x += 1), string interpolation with backticks, and a different standard library (task.wait, table.create, the game object with its services). Scripts run inside the platform's sandbox, so io, os and require of files are not available the way they are in standalone Lua. The mental model is the same, but treat Luau as a close cousin rather than the same language.

Topic Standard Lua 5.4 Lร–VE (LuaJIT) Roblox Luau
Integer vs float Separate subtypes One number type One number type
continue Use goto continue Use goto Built-in continue
x += 1 Not available Not available Available
Entry point Your script main.lua callbacks Scripts in the platform tree
File access io library love.filesystem Not available

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a host program do before running a script so that the script can call log(...)?

    Scripts only see what the host provides. With the C API this is done with lua_register or by setting a global, which makes the bridge function visible to the script.
  2. 2. What does the 'attempt to call a nil value (global ...)' error tell you when a script uses a host function?

    A missing global is nil, and calling nil fails. In an embedded script this usually means the host did not expose that name, or exposed it under a different one.
  3. 3. How do you give an untrusted chunk only a few safe globals in Lua 5.4?

    load(source, name, mode, env) runs the chunk with env as its global table, so names that are not in env do not exist for that chunk.
  4. 4. Which statement about Roblox Luau is accurate?

    Luau is derived from Lua 5.1 with additions such as optional types and continue, and it runs inside Roblox's sandbox rather than as a standalone interpreter.

Summary

  • Lua is built to be embedded: a small C library that a host program links to so it can be scripted.
  • The C API passes values through a stack; the host registers functions so scripts can call back into it.
  • Hosts usually own the main loop and call script callbacks such as update(dt).
  • A Lua file that returns a table makes a flexible configuration format.
  • load(source, name, "t", env) runs untrusted code with a limited environment; add time and memory limits, and process isolation for hostile code.
  • Lร–VE runs LuaJIT with framework callbacks, and Roblox Luau is a Lua 5.1 descendant with its own features and sandbox.

Next: Project: A To-Do List Manager