From 08fa9da2bb89b34f8c83d958784f0d06bf4ef59d Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Fri, 29 May 2026 10:11:55 -0400 Subject: [PATCH 1/5] feat(vm): configurable max call depth MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a `:max_call_depth` option to `Lua.new/1` so embedders can bound recursion. When a script nests function calls deeper than the limit, the VM raises a catchable `"stack overflow"` runtime error instead of letting runaway recursion exhaust the host process. Defaults to `:infinity` (no limit), preserving existing behavior. Depth is tracked as an O(1) integer counter (`State.call_depth`) that moves in lockstep with the existing `call_stack` push/pop at all 13 call sites across the executor and dispatcher — `length(call_stack)` per call would be O(n²) on this hot path. The guard (`State.check_call_depth!/1`) is a function-head no-op for `:infinity` and under-limit, relying on Erlang term ordering (integers sort before atoms) so unlimited VMs pay nothing. Known limitation: native->Lua re-entries via `Executor.call_function/3` in interpreted mode (pcall, table.sort comparators, metamethods, iterators) don't push their own call_stack frame, so a pure pcall-bomb that grows the BEAM stack without growing call_stack isn't directly bounded (the Lua calls inside it still are). Mirrors PUC-Lua's separate LUAI_MAXCCALLS; closeable later by guarding call_function itself. --- lib/lua.ex | 19 +++++++- lib/lua/vm/dispatcher.ex | 46 +++++++++++++----- lib/lua/vm/executor.ex | 16 ++++++- lib/lua/vm/state.ex | 27 +++++++++++ test/lua/vm/recursion_depth_test.exs | 70 ++++++++++++++++++++++++++++ 5 files changed, 163 insertions(+), 15 deletions(-) create mode 100644 test/lua/vm/recursion_depth_test.exs diff --git a/lib/lua.ex b/lib/lua.ex index ea60ff9b..33d94fbb 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -86,13 +86,20 @@ defmodule Lua do * `:exclude` - list of paths to exclude from the sandbox, e.g. `exclude: [[:require], [:package]]` * `:debug` - (default `false`) when `true`, internal Lua VM frames are preserved in stack traces instead of being pruned. Useful when debugging library bugs. + * `:max_call_depth` - (default `:infinity`) caps the depth of nested function calls. When a + script recurses deeper than this, a catchable `"stack overflow"` runtime error is raised + instead of letting the recursion exhaust the host process. Accepts a positive integer or + `:infinity` for no limit. + + iex> Lua.new(max_call_depth: 500) """ def new(opts \\ []) do - opts = Keyword.validate!(opts, sandboxed: @default_sandbox, exclude: [], debug: false) + opts = Keyword.validate!(opts, sandboxed: @default_sandbox, exclude: [], debug: false, max_call_depth: :infinity) exclude = Keyword.fetch!(opts, :exclude) debug = Keyword.fetch!(opts, :debug) + max_call_depth = validate_max_call_depth!(Keyword.fetch!(opts, :max_call_depth)) - state = Lua.VM.Stdlib.install(State.new()) + state = %{Lua.VM.Stdlib.install(State.new()) | max_call_depth: max_call_depth} opts |> Keyword.fetch!(:sandboxed) @@ -100,6 +107,14 @@ defmodule Lua do |> Enum.reduce(%__MODULE__{state: state, debug: debug}, &sandbox(&2, &1)) end + defp validate_max_call_depth!(:infinity), do: :infinity + defp validate_max_call_depth!(depth) when is_integer(depth) and depth > 0, do: depth + + defp validate_max_call_depth!(other) do + raise ArgumentError, + ":max_call_depth must be a positive integer or :infinity, got: #{inspect(other)}" + end + @doc """ Write Lua code that is parsed at compile-time. diff --git a/lib/lua/vm/dispatcher.ex b/lib/lua/vm/dispatcher.ex index 52fc804c..66eaee1b 100644 --- a/lib/lua/vm/dispatcher.ex +++ b/lib/lua/vm/dispatcher.ex @@ -567,7 +567,14 @@ defmodule Lua.VM.Dispatcher do {code, pc + 1, regs, upvalues, proto, cont, :discard, state.open_upvalues} call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - state = %{state | call_stack: [call_info | state.call_stack], open_upvalues: %{}} + State.check_call_depth!(state) + + state = %{ + state + | call_stack: [call_info | state.call_stack], + call_depth: state.call_depth + 1, + open_upvalues: %{} + } dispatch( callee_proto.bytecode, @@ -583,9 +590,10 @@ defmodule Lua.VM.Dispatcher do {:lua_closure, _, _} = closure -> args = collect_args(regs, base + 1, arg_count) call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - state = %{state | call_stack: [call_info | state.call_stack]} + State.check_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} {_results, state} = Executor.call_function(closure, args, state) - state = %{state | call_stack: tl(state.call_stack)} + state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) _ -> @@ -612,7 +620,14 @@ defmodule Lua.VM.Dispatcher do {code, pc + 1, regs, upvalues, proto, cont, base, state.open_upvalues} call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - state = %{state | call_stack: [call_info | state.call_stack], open_upvalues: %{}} + State.check_call_depth!(state) + + state = %{ + state + | call_stack: [call_info | state.call_stack], + call_depth: state.call_depth + 1, + open_upvalues: %{} + } dispatch( callee_proto.bytecode, @@ -628,9 +643,10 @@ defmodule Lua.VM.Dispatcher do {:lua_closure, _, _} = closure -> args = collect_args(regs, base + 1, arg_count) call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - state = %{state | call_stack: [call_info | state.call_stack]} + State.check_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} {results, state} = Executor.call_function(closure, args, state) - state = %{state | call_stack: tl(state.call_stack)} + state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} first = case results do @@ -1004,7 +1020,14 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, dest, state.open_upvalues} call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - state = %{state | call_stack: [call_info | state.call_stack], open_upvalues: %{}} + State.check_call_depth!(state) + + state = %{ + state + | call_stack: [call_info | state.call_stack], + call_depth: state.call_depth + 1, + open_upvalues: %{} + } dispatch( callee_proto.bytecode, @@ -1020,9 +1043,10 @@ defmodule Lua.VM.Dispatcher do {:lua_closure, _, _} = closure -> args = collect_args(regs, base + 1, total_args) call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - state = %{state | call_stack: [call_info | state.call_stack]} + State.check_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} {results, state} = Executor.call_function(closure, args, state) - state = %{state | call_stack: tl(state.call_stack)} + state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} apply_multi_call_result(result_count, base, results, code, pc + 1, regs, upvalues, proto, state, cont, frames) _ -> @@ -1263,7 +1287,7 @@ defmodule Lua.VM.Dispatcher do # Every dispatcher frame corresponds to a Lua-level call that pushed a # call_stack entry. Pop it on the way out — the interpreter's # `do_frame_return/6` does the same at executor.ex:1767. - state = %{state | open_upvalues: saved_open, call_stack: tl(state.call_stack)} + state = %{state | open_upvalues: saved_open, call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} case dest do :discard -> @@ -1298,7 +1322,7 @@ defmodule Lua.VM.Dispatcher do defp return_multi(results, state, [frame | rest_frames]) do {code, pc, regs, upvalues, proto, cont, dest, saved_open} = frame - state = %{state | open_upvalues: saved_open, call_stack: tl(state.call_stack)} + state = %{state | open_upvalues: saved_open, call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} case dest do :discard -> diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index de20b805..6d070674 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -984,7 +984,14 @@ defmodule Lua.VM.Executor do call_info = %{source: proto.source, line: line, name: hint_name(name_hint)} - state = %{state | call_stack: [call_info | state.call_stack], open_upvalues: %{}} + State.check_call_depth!(state) + + state = %{ + state + | call_stack: [call_info | state.call_stack], + call_depth: state.call_depth + 1, + open_upvalues: %{} + } # Tail call — Erlang stack does not grow do_execute( @@ -1869,7 +1876,12 @@ defmodule Lua.VM.Executor do open_upvalues: saved_open_upvalues } = frame - state = %{state | call_stack: tl(state.call_stack), open_upvalues: saved_open_upvalues} + state = %{ + state + | call_stack: tl(state.call_stack), + call_depth: state.call_depth - 1, + open_upvalues: saved_open_upvalues + } case result_count do -1 -> diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index c65e8944..cbd161f0 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -6,6 +6,12 @@ defmodule Lua.VM.State do alias Lua.VM.Table defstruct call_stack: [], + # Call depth tracked as an O(1) counter that moves in lockstep + # with `call_stack` — `length(call_stack)` would be O(depth) per + # call. `max_call_depth` bounds it; `:infinity` (the default) + # means no limit. See `check_call_depth!/1`. + call_depth: 0, + max_call_depth: :infinity, metatables: %{}, upvalue_cells: %{}, open_upvalues: %{}, @@ -23,6 +29,8 @@ defmodule Lua.VM.State do @type t :: %__MODULE__{ call_stack: list(), + call_depth: non_neg_integer(), + max_call_depth: pos_integer() | :infinity, metatables: map(), upvalue_cells: map(), tables: %{optional(non_neg_integer()) => Table.t()}, @@ -46,6 +54,25 @@ defmodule Lua.VM.State do %{state | g_ref: g_ref} end + @doc """ + Guards against unbounded recursion. + + Raises a Lua `"stack overflow"` runtime error when the call depth has + reached `max_call_depth`. Call it immediately before pushing a frame + onto `call_stack`. + + No-op when depth is under the limit or when `max_call_depth` is + `:infinity` (the default). The clauses are ordered so both common cases + resolve in a single function-head match with no struct rebuild. + """ + @spec check_call_depth!(t()) :: :ok + def check_call_depth!(%__MODULE__{max_call_depth: :infinity}), do: :ok + def check_call_depth!(%__MODULE__{call_depth: depth, max_call_depth: max}) when depth < max, do: :ok + + def check_call_depth!(%__MODULE__{call_stack: call_stack}) do + raise Lua.VM.RuntimeError, value: "stack overflow", call_stack: call_stack + end + @doc """ Returns the `_G` table reference. """ diff --git a/test/lua/vm/recursion_depth_test.exs b/test/lua/vm/recursion_depth_test.exs new file mode 100644 index 00000000..61bc42ed --- /dev/null +++ b/test/lua/vm/recursion_depth_test.exs @@ -0,0 +1,70 @@ +defmodule Lua.VM.RecursionDepthTest do + @moduledoc """ + Pins the `:max_call_depth` recursion limit: deep recursion raises a + catchable Lua `"stack overflow"` error, the depth counter unwinds on + return and after a caught error, and `:infinity` (the default) imposes + no bound. + """ + use ExUnit.Case, async: true + + alias Lua.RuntimeException + + defp eval!(lua, code), do: Lua.eval!(lua, code) + + describe ":max_call_depth enforcement" do + test "recursion deeper than the limit raises stack overflow" do + lua = Lua.new(max_call_depth: 10) + + assert_raise RuntimeException, ~r/stack overflow/, fn -> + eval!(lua, "local function f(n) if n > 0 then f(n - 1) end end f(50)") + end + end + + test "recursion under the limit returns normally and the VM stays usable" do + lua = Lua.new(max_call_depth: 100) + + # deep(50) nests 50 frames — comfortably under the cap — and returns n. + {[50], lua} = + eval!(lua, "local function deep(n) if n > 0 then deep(n - 1) end return n end return deep(50)") + + # The depth counter must have unwound back to 0: a second deep call works. + assert {[50], _lua} = + eval!(lua, "local function deep(n) if n > 0 then deep(n - 1) end return n end return deep(50)") + end + + test "pcall catches the overflow and the VM keeps working afterward" do + lua = Lua.new(max_call_depth: 50) + + {[false, err], lua} = + eval!(lua, "local function f(n) f(n + 1) end return pcall(f, 1)") + + assert err =~ "stack overflow" + + # call_depth was restored on the rescue, so the VM is healthy. + assert {[2], _lua} = eval!(lua, "return 1 + 1") + end + end + + describe "default behavior (:infinity)" do + test "moderately deep recursion runs with no limit" do + {[200], _lua} = + Lua.eval!( + Lua.new(), + "local function deep(n) if n > 0 then deep(n - 1) end return n end return deep(200)" + ) + end + end + + describe ":max_call_depth validation" do + test "rejects non-positive integers and non-integers" do + assert_raise ArgumentError, ~r/:max_call_depth/, fn -> Lua.new(max_call_depth: 0) end + assert_raise ArgumentError, ~r/:max_call_depth/, fn -> Lua.new(max_call_depth: -5) end + assert_raise ArgumentError, ~r/:max_call_depth/, fn -> Lua.new(max_call_depth: "big") end + end + + test "accepts :infinity and positive integers" do + assert %Lua{} = Lua.new(max_call_depth: :infinity) + assert %Lua{} = Lua.new(max_call_depth: 1) + end + end +end From aeaba6f61e73d50bc7d005645669d8dd09e999dd Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Fri, 29 May 2026 12:39:17 -0400 Subject: [PATCH 2/5] docs(vm): demonstrate max_call_depth effect in doctest --- lib/lua.ex | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/lua.ex b/lib/lua.ex index 33d94fbb..2af10e80 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -91,7 +91,10 @@ defmodule Lua do instead of letting the recursion exhaust the host process. Accepts a positive integer or `:infinity` for no limit. - iex> Lua.new(max_call_depth: 500) + iex> lua = Lua.new(max_call_depth: 10) + iex> {[false, message], _lua} = Lua.eval!(lua, "local function f() return f() end return pcall(f)") + iex> message =~ "stack overflow" + true """ def new(opts \\ []) do opts = Keyword.validate!(opts, sandboxed: @default_sandbox, exclude: [], debug: false, max_call_depth: :infinity) From beeb56ead7aa8bf93113bcd3545486e6e65f12c9 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Fri, 29 May 2026 13:19:10 -0400 Subject: [PATCH 3/5] feat(website): cap playground recursion at 200 frames Untrusted playground snippets now run under max_call_depth: 200 so a stack-growing recursion bomb fails with a catchable "stack overflow" instead of growing the BEAM stack. 200 mirrors PUC-Lua's LUAI_MAXCCALLS. (Infinite tail recursion / loops remain bounded by the LiveView timeout.) --- website/lib/website/lua_sandbox.ex | 98 ++++++++++++------------------ 1 file changed, 38 insertions(+), 60 deletions(-) diff --git a/website/lib/website/lua_sandbox.ex b/website/lib/website/lua_sandbox.ex index 2e8a9d1d..76fc5993 100644 --- a/website/lib/website/lua_sandbox.ex +++ b/website/lib/website/lua_sandbox.ex @@ -16,6 +16,12 @@ defmodule Website.LuaSandbox do alias Lua.Compiler.Prototype + # Cap recursion so a runaway snippet (`local function f() return f() end`) + # fails with a catchable "stack overflow" instead of growing the BEAM + # stack until the process dies. 200 mirrors PUC-Lua's LUAI_MAXCCALLS, so + # the limit lands where a Lua author expects it to. + @max_call_depth 200 + @doc """ Compiles a Lua snippet into a `Lua.Chunk` (without running it) and returns the chunk plus the disassembled prototype tree. Returns @@ -54,12 +60,10 @@ defmodule Website.LuaSandbox do output_pid = start_output_collector() lua = - Lua.new() + [max_call_depth: @max_call_depth] + |> Lua.new() |> Lua.set!([:print], fn args -> - line = - args - |> Enum.map(&to_lua_string/1) - |> Enum.join("\t") + line = Enum.map_join(args, "\t", &to_lua_string/1) send(output_pid, {:line, line}) [] @@ -209,8 +213,7 @@ defmodule Website.LuaSandbox do acc = [block | acc] next_index = next_index + 1 - Enum.reduce(Enum.with_index(proto.prototypes), {acc, next_index}, fn {child, child_local_idx}, - {acc, next_idx} -> + Enum.reduce(Enum.with_index(proto.prototypes), {acc, next_index}, fn {child, child_local_idx}, {acc, next_idx} -> name = "function ##{next_idx} (proto[#{child_local_idx}])" walk_proto(child, name, next_idx, acc) end) @@ -237,12 +240,9 @@ defmodule Website.LuaSandbox do :equal, :less_than, :less_equal - ], - do: "r#{a}, r#{b}, r#{c}" + ], do: "r#{a}, r#{b}, r#{c}" - defp format_op_args(op, [a, b]) - when op in [:negate, :not, :length, :bitwise_not, :move], - do: "r#{a}, r#{b}" + defp format_op_args(op, [a, b]) when op in [:negate, :not, :length, :bitwise_not, :move], do: "r#{a}, r#{b}" defp format_op_args(:load_constant, [d, val]), do: "r#{d}, #{format_lit(val)}" defp format_op_args(:load_nil, [d, count]), do: "r#{d}, #{count}" @@ -260,11 +260,9 @@ defmodule Website.LuaSandbox do defp format_op_args(:get_field, [d, t, name | _]), do: ~s|r#{d}, r#{t}.#{name}| defp format_op_args(:set_field, [t, name, v | _]), do: ~s|r#{t}.#{name}, r#{v}| - defp format_op_args(:set_list, [t, s, c, o]), - do: "r#{t}, start=#{s}, count=#{count(c)}, off=#{o}" + defp format_op_args(:set_list, [t, s, c, o]), do: "r#{t}, start=#{s}, count=#{count(c)}, off=#{o}" - defp format_op_args(:call, [b, ac, rc | _]), - do: "r#{b}, args=#{count(ac)}, results=#{count(rc)}" + defp format_op_args(:call, [b, ac, rc | _]), do: "r#{b}, args=#{count(ac)}, results=#{count(rc)}" defp format_op_args(:tail_call, [b, ac | _]), do: "r#{b}, args=#{count(ac)}" defp format_op_args(:return, [b, c]), do: "r#{b}, count=#{count(c)}" @@ -280,7 +278,7 @@ defmodule Website.LuaSandbox do defp format_op_args(:generic_for, [b, vc | _]), do: "r#{b}, vars=#{vc}" defp format_op_args(:scope, [n | _]), do: "registers=#{n}" defp format_op_args(:source_line, [ln]), do: "line #{ln}" - defp format_op_args(_op, args), do: args |> Enum.map(&pretty_arg/1) |> Enum.join(", ") + defp format_op_args(_op, args), do: Enum.map_join(args, ", ", &pretty_arg/1) defp pretty_arg({:constant, val}), do: format_lit(val) defp pretty_arg({:global, name}), do: ~s|<#{name}>| @@ -501,8 +499,7 @@ defmodule Website.LuaSandbox do %{ id: "sandbox", title: "Sandbox escape", - blurb: - "Watch the VM refuse to run dangerous stdlib calls. This is the reason it's agent-ready.", + blurb: "Watch the VM refuse to run dangerous stdlib calls. This is the reason it's agent-ready.", source: """ -- The host process never had to defend itself. local ok, err = pcall(function() @@ -655,8 +652,7 @@ defmodule Website.LuaSandbox do two subtypes (64-bit *integer* and *float*) and Lua tracks which is which. Strings are interned immutable byte sequences. """, - exercise: - "Add a line that prints `type(3.0 == 3)` and predict the result before running.", + exercise: "Add a line that prints `type(3.0 == 3)` and predict the result before running.", source: """ print(type(nil), type(true), type(1), type(1.5)) print(type("hi"), type(print), type({})) @@ -708,7 +704,7 @@ defmodule Website.LuaSandbox do `(cond and a) or b` is Lua's ternary expression. """, exercise: - "Make `(false and \"a\") or \"b\"` return `\"b\"`. Now make it return `false` when the first branch is false. Why is `(c and a) or b` unsafe when `a` can be `false`?", + ~s{Make `(false and "a") or "b"` return `"b"`. Now make it return `false` when the first branch is false. Why is `(c and a) or b` unsafe when `a` can be `false`?}, source: """ print(0 and "zero is truthy") print("" and "empty string is truthy") @@ -760,8 +756,7 @@ defmodule Website.LuaSandbox do slug: "tables", title: "Tables are everything", chapter: :basics, - objective: - "Build arrays, records, and nested tables, and know what `#t` actually counts.", + objective: "Build arrays, records, and nested tables, and know what `#t` actually counts.", body: """ Tables are *the* data structure: arrays, hash maps, records, modules, all tables. Indexed from `1` by convention. `#t` is @@ -770,7 +765,7 @@ defmodule Website.LuaSandbox do literal. """, exercise: - "Add `user.prefs.shortcuts = { save = \"⌘S\" }` and print `user.prefs.shortcuts.save`. Then add `user[5] = \"trailing\"`. What does `#user` return now?", + ~s(Add `user.prefs.shortcuts = { save = "⌘S" }` and print `user.prefs.shortcuts.save`. Then add `user[5] = "trailing"`. What does `#user` return now?), source: """ local user = { "first row", -- user[1] @@ -793,8 +788,7 @@ defmodule Website.LuaSandbox do slug: "iteration", title: "Iteration", chapter: :basics, - objective: - "Use `pairs` for hash walks, `ipairs` for sequences, and write your own iterator.", + objective: "Use `pairs` for hash walks, `ipairs` for sequences, and write your own iterator.", body: """ `ipairs` walks the array part from `1` and stops at the first `nil`. `pairs` walks every key in unspecified order. The generic @@ -802,8 +796,7 @@ defmodule Website.LuaSandbox do how to write one yourself: return `(iter, state, control)` and Lua takes care of the rest. """, - exercise: - "Add a `step` parameter to `range` so `range(10, 2)` yields `1, 3, 5, 7, 9` with their squares.", + exercise: "Add a `step` parameter to `range` so `range(10, 2)` yields `1, 3, 5, 7, 9` with their squares.", source: """ local t = { 10, 20, 30, name = "trio" } for i, v in ipairs(t) do print("ipairs", i, v) end @@ -884,8 +877,7 @@ defmodule Website.LuaSandbox do slug: "closures", title: "Closures & upvalues", chapter: :idioms, - objective: - "Capture an outer-scope binding and watch the `closure` op build the function at runtime.", + objective: "Capture an outer-scope binding and watch the `closure` op build the function at runtime.", body: """ Inner functions capture outer locals *by reference*. These captured bindings are called *upvalues*. Two closures over the @@ -935,8 +927,7 @@ defmodule Website.LuaSandbox do slug: "metatables-index", title: "Metatables: `__index`", chapter: :idioms, - objective: - "Use `__index` (table or function) for fallback lookup and single-inheritance chains.", + objective: "Use `__index` (table or function) for fallback lookup and single-inheritance chains.", body: """ Every table can have a *metatable*. When a key is missing on `t`, Lua consults `t`'s metatable's `__index`. If `__index` is a @@ -969,8 +960,7 @@ defmodule Website.LuaSandbox do slug: "metatables-ops", title: "Operator overloading", chapter: :idioms, - objective: - "Implement `__add`, `__eq`, `__tostring`, and `__call` so a Vector feels like a native value.", + objective: "Implement `__add`, `__eq`, `__tostring`, and `__call` so a Vector feels like a native value.", body: """ Metamethods customise operators (`__add`, `__sub`, `__mul`, `__div`, `__unm`, `__pow`, `__concat`), equality (`__eq`), @@ -978,8 +968,7 @@ defmodule Website.LuaSandbox do (`__tostring`), and the call protocol (`__call`). Pair them with `__index = self` to make instance methods discoverable. """, - exercise: - "Add a `__sub` metamethod and a `:dot(other)` method. Use them: `print((a - b):dot(a + b))`.", + exercise: "Add a `__sub` metamethod and a `:dot(other)` method. Use them: `print((a - b):dot(a + b))`.", source: """ local Vec = {} Vec.__index = Vec @@ -1003,8 +992,7 @@ defmodule Website.LuaSandbox do slug: "errors", title: "Errors, `pcall`, `xpcall`", chapter: :idioms, - objective: - "Raise errors as strings *or* tables, catch them with `pcall`, and add a handler with `xpcall`.", + objective: "Raise errors as strings *or* tables, catch them with `pcall`, and add a handler with `xpcall`.", body: """ `error(value)` raises. The value is usually a string, but a table works and is great for structured failures. `pcall(f, …)` @@ -1039,8 +1027,7 @@ defmodule Website.LuaSandbox do title: "Coroutines (preview)", chapter: :idioms, runnable: false, - objective: - "Read the coroutine API and see why it's the engine behind stateful iterators.", + objective: "Read the coroutine API and see why it's the engine behind stateful iterators.", body: """ Coroutines are cooperative threads inside a single OS thread: `create` builds one, `resume` runs it, `yield` suspends it and @@ -1078,8 +1065,7 @@ defmodule Website.LuaSandbox do slug: "strings", title: "Strings & patterns", chapter: :stdlib, - objective: - "Format, slice, and concatenate strings, then capture matches with `gmatch` and `gsub`.", + objective: "Format, slice, and concatenate strings, then capture matches with `gmatch` and `gsub`.", body: """ `..` concatenates, `#s` is byte length (not codepoints), `string.format` is `printf`. Patterns are *not* regex: `%a` @@ -1089,7 +1075,7 @@ defmodule Website.LuaSandbox do function. """, exercise: - "Use `gsub` with a function replacement to capitalise every word: `\"hello there\"` → `\"Hello There\"`. Hint: pattern `(%a)(%a*)`.", + ~s{Use `gsub` with a function replacement to capitalise every word: `"hello there"` → `"Hello There"`. Hint: pattern `(%a)(%a*)`.}, source: """ local s = "Hello, World!" print(#s, s:upper(), s:sub(1, 5)) @@ -1113,8 +1099,7 @@ defmodule Website.LuaSandbox do slug: "tables-stdlib", title: "Working with tables", chapter: :stdlib, - objective: - "Use `table.insert`, `remove`, `sort`, `concat`, and `unpack` to manipulate sequences.", + objective: "Use `table.insert`, `remove`, `sort`, `concat`, and `unpack` to manipulate sequences.", body: """ `table.insert(t, v)` pushes; `table.insert(t, pos, v)` inserts at `pos`. `table.remove(t)` pops the tail. `table.concat(t, @@ -1147,8 +1132,7 @@ defmodule Website.LuaSandbox do slug: "math-and-numbers", title: "Numbers: int & float", chapter: :stdlib, - objective: - "Tell integers from floats, convert between them, and know which operator returns which.", + objective: "Tell integers from floats, convert between them, and know which operator returns which.", body: """ Lua 5.3 has two number subtypes: 64-bit *integer* and *float* (double). `/` always returns a float; `//` floor-divides and @@ -1239,8 +1223,7 @@ defmodule Website.LuaSandbox do slug: "set-and-get", title: "Reading & writing state", chapter: :integration, - objective: - "Define globals from Elixir with `Lua.set!` and read them back with `Lua.get!`.", + objective: "Define globals from Elixir with `Lua.set!` and read them back with `Lua.get!`.", body: """ `Lua.set!(lua, [:greeting], "hi")` writes a global. `Lua.get!( lua, [:total])` reads one. Paths nest into tables: @@ -1280,8 +1263,7 @@ defmodule Website.LuaSandbox do slug: "deflua", title: "Exposing Elixir with `deflua`", chapter: :integration, - objective: - "Define a module with `use Lua.API` + `deflua`, then load it with `Lua.load_api/2`.", + objective: "Define a module with `use Lua.API` + `deflua`, then load it with `Lua.load_api/2`.", body: """ `deflua` turns an Elixir function into a Lua-callable. The optional `scope:` puts it under a namespace, so `scope: @@ -1322,8 +1304,7 @@ defmodule Website.LuaSandbox do slug: "call-function", title: "Calling Lua from Elixir", chapter: :integration, - objective: - "Define a Lua function in a snippet, then invoke it from Elixir with `call_function!`.", + objective: "Define a Lua function in a snippet, then invoke it from Elixir with `call_function!`.", body: """ `Lua.call_function!(lua, [:name], [arg1, arg2])` calls a Lua function from Elixir. Path tuples work too: `[:string, :upper]` @@ -1362,8 +1343,7 @@ defmodule Website.LuaSandbox do slug: "put-private", title: "Private host context", chapter: :integration, - objective: - "Pass authenticated context to `deflua` handlers without exposing it to Lua scripts.", + objective: "Pass authenticated context to `deflua` handlers without exposing it to Lua scripts.", body: """ `Lua.put_private(lua, :user_id, 42)` stores host state inside the VM that *Lua scripts cannot see*. In a `deflua` body taking @@ -1448,8 +1428,7 @@ defmodule Website.LuaSandbox do title: "Errors across the boundary", chapter: :integration, expect: :runtime_error, - objective: - "Catch `Lua.RuntimeException` on the Elixir side. Line, source, and call stack come along.", + objective: "Catch `Lua.RuntimeException` on the Elixir side. Line, source, and call stack come along.", body: """ Runtime errors in Lua raise `Lua.RuntimeException` on the Elixir side. The exception carries the offending line, the @@ -1491,8 +1470,7 @@ defmodule Website.LuaSandbox do slug: "bytecode", title: "The bytecode model", chapter: :internals, - objective: - "Read a disassembled prototype: instructions, registers, upvalues, and nested protos.", + objective: "Read a disassembled prototype: instructions, registers, upvalues, and nested protos.", body: """ The compiler lowers Lua to a stream of *register-based* opcodes. No labels, no PC-relative jumps. Each function From 76f8b756ea7160c77be888fa519c2d197e95ef3b Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Fri, 29 May 2026 13:49:22 -0400 Subject: [PATCH 4/5] feat(vm): truncate deep stack traces in error output A deep recursion (now reachable via :max_call_depth) pushed hundreds of near-identical frames into the rendered Stack trace, producing an unreadable wall of text in any consumer (playground, CLI). ErrorFormatter now keeps the 7 innermost frames and 3 outermost, collapsing the middle into a '... N more frames ...' line. Only triggers when it saves space. --- lib/lua/vm/error_formatter.ex | 26 +++++++++++++++++++ test/lua/error_messages_test.exs | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/lib/lua/vm/error_formatter.ex b/lib/lua/vm/error_formatter.ex index b187db79..4d0c8557 100644 --- a/lib/lua/vm/error_formatter.ex +++ b/lib/lua/vm/error_formatter.ex @@ -176,17 +176,38 @@ defmodule Lua.VM.ErrorFormatter do |> String.pad_leading(4) end + # A deep recursion (see `:max_call_depth`) can push hundreds of frames + # onto the stack. Rendering all of them produces an unreadable wall of + # near-identical lines, so we keep the innermost frames (where the error + # fired) and the outermost frames (down to the main chunk), collapsing + # the middle into a single count. Only kicks in when the gap line + # replaces at least two frames. + @trace_head 7 + @trace_tail 3 + defp format_stack_trace([]), do: nil defp format_stack_trace(call_stack) when is_list(call_stack) do frames = call_stack |> build_call_stack() + |> truncate_frames() |> Enum.map_join("\n", &format_frame/1) "\n\n" <> IO.ANSI.cyan() <> "Stack trace:" <> IO.ANSI.reset() <> "\n" <> frames end + defp truncate_frames(frames) do + count = length(frames) + + if count > @trace_head + @trace_tail + 1 do + omitted = count - @trace_head - @trace_tail + Enum.take(frames, @trace_head) ++ [{:omitted, omitted}] ++ Enum.take(frames, -@trace_tail) + else + frames + end + end + defp build_call_stack(call_stack) when is_list(call_stack) do Enum.map(call_stack, fn frame -> %{ @@ -199,6 +220,11 @@ defmodule Lua.VM.ErrorFormatter do defp build_call_stack(_), do: [] + defp format_frame({:omitted, count}) do + IO.ANSI.faint() <> + " ... #{count} more frames ..." <> IO.ANSI.reset() + end + defp format_frame(%{source: source, line: line, name: name}) do location = " #{source || "-no-source-"}:#{line}:" diff --git a/test/lua/error_messages_test.exs b/test/lua/error_messages_test.exs index fc39afcc..ac7622c3 100644 --- a/test/lua/error_messages_test.exs +++ b/test/lua/error_messages_test.exs @@ -323,6 +323,50 @@ defmodule Lua.ErrorMessagesTest do assert formatted =~ "test.lua:5" assert formatted =~ "helper" end + + test "truncates very deep stack traces" do + alias Lua.VM.ErrorFormatter + + # 200 frames: innermost recursion down to the main chunk. + call_stack = + for n <- 1..199, do: %{source: "deep.lua", line: n, name: "f"} + + call_stack = call_stack ++ [%{source: "deep.lua", line: 1, name: nil}] + + formatted = + ErrorFormatter.format(:runtime_error, "stack overflow", + source: "deep.lua", + line: 1, + call_stack: call_stack + ) + + # Keeps the innermost and outermost frames, collapses the middle. + assert formatted =~ "deep.lua:1: in function 'f'" + assert formatted =~ "in main chunk" + assert formatted =~ "... 190 more frames ..." + + # The wall of 200 lines is gone: head (7) + tail (3) = 10 rendered + # frames, plus the single gap line. + frame_lines = + formatted + |> String.split("Stack trace:") + |> List.last() + |> String.split("\n") + |> Enum.count(&String.contains?(&1, "deep.lua:")) + + assert frame_lines == 10 + end + + test "does not truncate short stack traces" do + alias Lua.VM.ErrorFormatter + + call_stack = for n <- 1..8, do: %{source: "x.lua", line: n, name: "f"} + + formatted = + ErrorFormatter.format(:runtime_error, "boom", source: "x.lua", line: 1, call_stack: call_stack) + + refute formatted =~ "more frames" + end end describe "Lua.eval! preserves line/source on the public exception" do From 48f612938d2d9c5bf09aa212b7e624132459cc43 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Fri, 29 May 2026 17:24:23 -0400 Subject: [PATCH 5/5] fix --- lib/lua.ex | 5 ++ test/lua/vm/recursion_depth_test.exs | 11 ++++ website/lib/website/lua_sandbox.ex | 97 ++++++++++++++++++---------- 3 files changed, 79 insertions(+), 34 deletions(-) diff --git a/lib/lua.ex b/lib/lua.ex index 2af10e80..4f42afc0 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -91,6 +91,11 @@ defmodule Lua do instead of letting the recursion exhaust the host process. Accepts a positive integer or `:infinity` for no limit. + Note: this VM does not implement proper tail-call optimization, so a call in tail position + (`return f(x)`) consumes a frame like any other call. A finite `:max_call_depth` therefore + bounds tail recursion too — including loops that PUC-Lua would run indefinitely. Leave the + default `:infinity` if you rely on unbounded tail recursion. + iex> lua = Lua.new(max_call_depth: 10) iex> {[false, message], _lua} = Lua.eval!(lua, "local function f() return f() end return pcall(f)") iex> message =~ "stack overflow" diff --git a/test/lua/vm/recursion_depth_test.exs b/test/lua/vm/recursion_depth_test.exs index 61bc42ed..16099c75 100644 --- a/test/lua/vm/recursion_depth_test.exs +++ b/test/lua/vm/recursion_depth_test.exs @@ -43,6 +43,17 @@ defmodule Lua.VM.RecursionDepthTest do # call_depth was restored on the rescue, so the VM is healthy. assert {[2], _lua} = eval!(lua, "return 1 + 1") end + + test "tail recursion is bounded too (no tail-call optimization)" do + # `return f(...)` is in tail position, which PUC-Lua would run + # unbounded. This VM does not implement TCO, so every call — tail or + # not — consumes a frame and a finite cap stops the recursion. + lua = Lua.new(max_call_depth: 10) + + assert_raise RuntimeException, ~r/stack overflow/, fn -> + eval!(lua, "local function loop(n) return loop(n + 1) end loop(1)") + end + end end describe "default behavior (:infinity)" do diff --git a/website/lib/website/lua_sandbox.ex b/website/lib/website/lua_sandbox.ex index 76fc5993..e06f7877 100644 --- a/website/lib/website/lua_sandbox.ex +++ b/website/lib/website/lua_sandbox.ex @@ -18,8 +18,9 @@ defmodule Website.LuaSandbox do # Cap recursion so a runaway snippet (`local function f() return f() end`) # fails with a catchable "stack overflow" instead of growing the BEAM - # stack until the process dies. 200 mirrors PUC-Lua's LUAI_MAXCCALLS, so - # the limit lands where a Lua author expects it to. + # stack until the process dies. The VM has no tail-call optimization, so + # this bounds tail recursion too — 200 is generous for the teaching + # snippets here while still stopping an accidental infinite recursion. @max_call_depth 200 @doc """ @@ -60,10 +61,12 @@ defmodule Website.LuaSandbox do output_pid = start_output_collector() lua = - [max_call_depth: @max_call_depth] - |> Lua.new() + Lua.new(max_call_depth: @max_call_depth) |> Lua.set!([:print], fn args -> - line = Enum.map_join(args, "\t", &to_lua_string/1) + line = + args + |> Enum.map(&to_lua_string/1) + |> Enum.join("\t") send(output_pid, {:line, line}) [] @@ -213,7 +216,8 @@ defmodule Website.LuaSandbox do acc = [block | acc] next_index = next_index + 1 - Enum.reduce(Enum.with_index(proto.prototypes), {acc, next_index}, fn {child, child_local_idx}, {acc, next_idx} -> + Enum.reduce(Enum.with_index(proto.prototypes), {acc, next_index}, fn {child, child_local_idx}, + {acc, next_idx} -> name = "function ##{next_idx} (proto[#{child_local_idx}])" walk_proto(child, name, next_idx, acc) end) @@ -240,9 +244,12 @@ defmodule Website.LuaSandbox do :equal, :less_than, :less_equal - ], do: "r#{a}, r#{b}, r#{c}" + ], + do: "r#{a}, r#{b}, r#{c}" - defp format_op_args(op, [a, b]) when op in [:negate, :not, :length, :bitwise_not, :move], do: "r#{a}, r#{b}" + defp format_op_args(op, [a, b]) + when op in [:negate, :not, :length, :bitwise_not, :move], + do: "r#{a}, r#{b}" defp format_op_args(:load_constant, [d, val]), do: "r#{d}, #{format_lit(val)}" defp format_op_args(:load_nil, [d, count]), do: "r#{d}, #{count}" @@ -260,9 +267,11 @@ defmodule Website.LuaSandbox do defp format_op_args(:get_field, [d, t, name | _]), do: ~s|r#{d}, r#{t}.#{name}| defp format_op_args(:set_field, [t, name, v | _]), do: ~s|r#{t}.#{name}, r#{v}| - defp format_op_args(:set_list, [t, s, c, o]), do: "r#{t}, start=#{s}, count=#{count(c)}, off=#{o}" + defp format_op_args(:set_list, [t, s, c, o]), + do: "r#{t}, start=#{s}, count=#{count(c)}, off=#{o}" - defp format_op_args(:call, [b, ac, rc | _]), do: "r#{b}, args=#{count(ac)}, results=#{count(rc)}" + defp format_op_args(:call, [b, ac, rc | _]), + do: "r#{b}, args=#{count(ac)}, results=#{count(rc)}" defp format_op_args(:tail_call, [b, ac | _]), do: "r#{b}, args=#{count(ac)}" defp format_op_args(:return, [b, c]), do: "r#{b}, count=#{count(c)}" @@ -278,7 +287,7 @@ defmodule Website.LuaSandbox do defp format_op_args(:generic_for, [b, vc | _]), do: "r#{b}, vars=#{vc}" defp format_op_args(:scope, [n | _]), do: "registers=#{n}" defp format_op_args(:source_line, [ln]), do: "line #{ln}" - defp format_op_args(_op, args), do: Enum.map_join(args, ", ", &pretty_arg/1) + defp format_op_args(_op, args), do: args |> Enum.map(&pretty_arg/1) |> Enum.join(", ") defp pretty_arg({:constant, val}), do: format_lit(val) defp pretty_arg({:global, name}), do: ~s|<#{name}>| @@ -499,7 +508,8 @@ defmodule Website.LuaSandbox do %{ id: "sandbox", title: "Sandbox escape", - blurb: "Watch the VM refuse to run dangerous stdlib calls. This is the reason it's agent-ready.", + blurb: + "Watch the VM refuse to run dangerous stdlib calls. This is the reason it's agent-ready.", source: """ -- The host process never had to defend itself. local ok, err = pcall(function() @@ -652,7 +662,8 @@ defmodule Website.LuaSandbox do two subtypes (64-bit *integer* and *float*) and Lua tracks which is which. Strings are interned immutable byte sequences. """, - exercise: "Add a line that prints `type(3.0 == 3)` and predict the result before running.", + exercise: + "Add a line that prints `type(3.0 == 3)` and predict the result before running.", source: """ print(type(nil), type(true), type(1), type(1.5)) print(type("hi"), type(print), type({})) @@ -704,7 +715,7 @@ defmodule Website.LuaSandbox do `(cond and a) or b` is Lua's ternary expression. """, exercise: - ~s{Make `(false and "a") or "b"` return `"b"`. Now make it return `false` when the first branch is false. Why is `(c and a) or b` unsafe when `a` can be `false`?}, + "Make `(false and \"a\") or \"b\"` return `\"b\"`. Now make it return `false` when the first branch is false. Why is `(c and a) or b` unsafe when `a` can be `false`?", source: """ print(0 and "zero is truthy") print("" and "empty string is truthy") @@ -756,7 +767,8 @@ defmodule Website.LuaSandbox do slug: "tables", title: "Tables are everything", chapter: :basics, - objective: "Build arrays, records, and nested tables, and know what `#t` actually counts.", + objective: + "Build arrays, records, and nested tables, and know what `#t` actually counts.", body: """ Tables are *the* data structure: arrays, hash maps, records, modules, all tables. Indexed from `1` by convention. `#t` is @@ -765,7 +777,7 @@ defmodule Website.LuaSandbox do literal. """, exercise: - ~s(Add `user.prefs.shortcuts = { save = "⌘S" }` and print `user.prefs.shortcuts.save`. Then add `user[5] = "trailing"`. What does `#user` return now?), + "Add `user.prefs.shortcuts = { save = \"⌘S\" }` and print `user.prefs.shortcuts.save`. Then add `user[5] = \"trailing\"`. What does `#user` return now?", source: """ local user = { "first row", -- user[1] @@ -788,7 +800,8 @@ defmodule Website.LuaSandbox do slug: "iteration", title: "Iteration", chapter: :basics, - objective: "Use `pairs` for hash walks, `ipairs` for sequences, and write your own iterator.", + objective: + "Use `pairs` for hash walks, `ipairs` for sequences, and write your own iterator.", body: """ `ipairs` walks the array part from `1` and stops at the first `nil`. `pairs` walks every key in unspecified order. The generic @@ -796,7 +809,8 @@ defmodule Website.LuaSandbox do how to write one yourself: return `(iter, state, control)` and Lua takes care of the rest. """, - exercise: "Add a `step` parameter to `range` so `range(10, 2)` yields `1, 3, 5, 7, 9` with their squares.", + exercise: + "Add a `step` parameter to `range` so `range(10, 2)` yields `1, 3, 5, 7, 9` with their squares.", source: """ local t = { 10, 20, 30, name = "trio" } for i, v in ipairs(t) do print("ipairs", i, v) end @@ -877,7 +891,8 @@ defmodule Website.LuaSandbox do slug: "closures", title: "Closures & upvalues", chapter: :idioms, - objective: "Capture an outer-scope binding and watch the `closure` op build the function at runtime.", + objective: + "Capture an outer-scope binding and watch the `closure` op build the function at runtime.", body: """ Inner functions capture outer locals *by reference*. These captured bindings are called *upvalues*. Two closures over the @@ -927,7 +942,8 @@ defmodule Website.LuaSandbox do slug: "metatables-index", title: "Metatables: `__index`", chapter: :idioms, - objective: "Use `__index` (table or function) for fallback lookup and single-inheritance chains.", + objective: + "Use `__index` (table or function) for fallback lookup and single-inheritance chains.", body: """ Every table can have a *metatable*. When a key is missing on `t`, Lua consults `t`'s metatable's `__index`. If `__index` is a @@ -960,7 +976,8 @@ defmodule Website.LuaSandbox do slug: "metatables-ops", title: "Operator overloading", chapter: :idioms, - objective: "Implement `__add`, `__eq`, `__tostring`, and `__call` so a Vector feels like a native value.", + objective: + "Implement `__add`, `__eq`, `__tostring`, and `__call` so a Vector feels like a native value.", body: """ Metamethods customise operators (`__add`, `__sub`, `__mul`, `__div`, `__unm`, `__pow`, `__concat`), equality (`__eq`), @@ -968,7 +985,8 @@ defmodule Website.LuaSandbox do (`__tostring`), and the call protocol (`__call`). Pair them with `__index = self` to make instance methods discoverable. """, - exercise: "Add a `__sub` metamethod and a `:dot(other)` method. Use them: `print((a - b):dot(a + b))`.", + exercise: + "Add a `__sub` metamethod and a `:dot(other)` method. Use them: `print((a - b):dot(a + b))`.", source: """ local Vec = {} Vec.__index = Vec @@ -992,7 +1010,8 @@ defmodule Website.LuaSandbox do slug: "errors", title: "Errors, `pcall`, `xpcall`", chapter: :idioms, - objective: "Raise errors as strings *or* tables, catch them with `pcall`, and add a handler with `xpcall`.", + objective: + "Raise errors as strings *or* tables, catch them with `pcall`, and add a handler with `xpcall`.", body: """ `error(value)` raises. The value is usually a string, but a table works and is great for structured failures. `pcall(f, …)` @@ -1027,7 +1046,8 @@ defmodule Website.LuaSandbox do title: "Coroutines (preview)", chapter: :idioms, runnable: false, - objective: "Read the coroutine API and see why it's the engine behind stateful iterators.", + objective: + "Read the coroutine API and see why it's the engine behind stateful iterators.", body: """ Coroutines are cooperative threads inside a single OS thread: `create` builds one, `resume` runs it, `yield` suspends it and @@ -1065,7 +1085,8 @@ defmodule Website.LuaSandbox do slug: "strings", title: "Strings & patterns", chapter: :stdlib, - objective: "Format, slice, and concatenate strings, then capture matches with `gmatch` and `gsub`.", + objective: + "Format, slice, and concatenate strings, then capture matches with `gmatch` and `gsub`.", body: """ `..` concatenates, `#s` is byte length (not codepoints), `string.format` is `printf`. Patterns are *not* regex: `%a` @@ -1075,7 +1096,7 @@ defmodule Website.LuaSandbox do function. """, exercise: - ~s{Use `gsub` with a function replacement to capitalise every word: `"hello there"` → `"Hello There"`. Hint: pattern `(%a)(%a*)`.}, + "Use `gsub` with a function replacement to capitalise every word: `\"hello there\"` → `\"Hello There\"`. Hint: pattern `(%a)(%a*)`.", source: """ local s = "Hello, World!" print(#s, s:upper(), s:sub(1, 5)) @@ -1099,7 +1120,8 @@ defmodule Website.LuaSandbox do slug: "tables-stdlib", title: "Working with tables", chapter: :stdlib, - objective: "Use `table.insert`, `remove`, `sort`, `concat`, and `unpack` to manipulate sequences.", + objective: + "Use `table.insert`, `remove`, `sort`, `concat`, and `unpack` to manipulate sequences.", body: """ `table.insert(t, v)` pushes; `table.insert(t, pos, v)` inserts at `pos`. `table.remove(t)` pops the tail. `table.concat(t, @@ -1132,7 +1154,8 @@ defmodule Website.LuaSandbox do slug: "math-and-numbers", title: "Numbers: int & float", chapter: :stdlib, - objective: "Tell integers from floats, convert between them, and know which operator returns which.", + objective: + "Tell integers from floats, convert between them, and know which operator returns which.", body: """ Lua 5.3 has two number subtypes: 64-bit *integer* and *float* (double). `/` always returns a float; `//` floor-divides and @@ -1223,7 +1246,8 @@ defmodule Website.LuaSandbox do slug: "set-and-get", title: "Reading & writing state", chapter: :integration, - objective: "Define globals from Elixir with `Lua.set!` and read them back with `Lua.get!`.", + objective: + "Define globals from Elixir with `Lua.set!` and read them back with `Lua.get!`.", body: """ `Lua.set!(lua, [:greeting], "hi")` writes a global. `Lua.get!( lua, [:total])` reads one. Paths nest into tables: @@ -1263,7 +1287,8 @@ defmodule Website.LuaSandbox do slug: "deflua", title: "Exposing Elixir with `deflua`", chapter: :integration, - objective: "Define a module with `use Lua.API` + `deflua`, then load it with `Lua.load_api/2`.", + objective: + "Define a module with `use Lua.API` + `deflua`, then load it with `Lua.load_api/2`.", body: """ `deflua` turns an Elixir function into a Lua-callable. The optional `scope:` puts it under a namespace, so `scope: @@ -1304,7 +1329,8 @@ defmodule Website.LuaSandbox do slug: "call-function", title: "Calling Lua from Elixir", chapter: :integration, - objective: "Define a Lua function in a snippet, then invoke it from Elixir with `call_function!`.", + objective: + "Define a Lua function in a snippet, then invoke it from Elixir with `call_function!`.", body: """ `Lua.call_function!(lua, [:name], [arg1, arg2])` calls a Lua function from Elixir. Path tuples work too: `[:string, :upper]` @@ -1343,7 +1369,8 @@ defmodule Website.LuaSandbox do slug: "put-private", title: "Private host context", chapter: :integration, - objective: "Pass authenticated context to `deflua` handlers without exposing it to Lua scripts.", + objective: + "Pass authenticated context to `deflua` handlers without exposing it to Lua scripts.", body: """ `Lua.put_private(lua, :user_id, 42)` stores host state inside the VM that *Lua scripts cannot see*. In a `deflua` body taking @@ -1428,7 +1455,8 @@ defmodule Website.LuaSandbox do title: "Errors across the boundary", chapter: :integration, expect: :runtime_error, - objective: "Catch `Lua.RuntimeException` on the Elixir side. Line, source, and call stack come along.", + objective: + "Catch `Lua.RuntimeException` on the Elixir side. Line, source, and call stack come along.", body: """ Runtime errors in Lua raise `Lua.RuntimeException` on the Elixir side. The exception carries the offending line, the @@ -1470,7 +1498,8 @@ defmodule Website.LuaSandbox do slug: "bytecode", title: "The bytecode model", chapter: :internals, - objective: "Read a disassembled prototype: instructions, registers, upvalues, and nested protos.", + objective: + "Read a disassembled prototype: instructions, registers, upvalues, and nested protos.", body: """ The compiler lowers Lua to a stream of *register-based* opcodes. No labels, no PC-relative jumps. Each function