Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,14 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.
past the ceiling in a single allocation. Each raises the same catchable
`"resulting string too large"` error as `string.rep` and `..`, before the
result is built (#425).
- `pcall` and `xpcall` return `"error in host function"` instead of the
message of an exception raised by host code, which can quote host data.
Errors raised for the script pass through unchanged.
- `rawget`, `rawset`, `rawequal`, `next`, `getmetatable`, `setmetatable`,
`tostring`, `tonumber` and `select` raise Lua's `"bad argument"` errors
instead of an Elixir exception or a silent default.
- `os.date` raises a Lua error for an out-of-range time instead of an Elixir
`ArgumentError`.

## [1.0.2] - 2026-07-28

Expand Down
33 changes: 13 additions & 20 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1253,26 +1253,12 @@ defmodule Lua do

{data, %Lua{} = returned_lua} ->
data = List.wrap(data)

if not Util.list_encoded?(data) do
raise Lua.RuntimeException,
function: function_name,
scope: module.scope(),
message: "deflua functions must return encoded data, got #{inspect(data)}"
end

validate_encoded!(data, function_name, module.scope())
{data, returned_lua}

data ->
data = List.wrap(data)

if not Util.list_encoded?(data) do
raise Lua.RuntimeException,
function: function_name,
scope: module.scope(),
message: "deflua functions must return encoded data, got #{inspect(data)}"
end

validate_encoded!(data, function_name, module.scope())
{data, lua}
end
catch
Expand Down Expand Up @@ -1328,15 +1314,22 @@ defmodule Lua do
end}
end

# Raised as a host exception: the message quotes host data.
defp validate_encoded!(value, function_name, scope) do
if not Util.list_encoded?(value) do
raise Lua.RuntimeException,
function: function_name,
scope: scope,
message: "deflua functions must return encoded data, got #{inspect(value)}"
unencoded_return =
ArgumentError.exception(
"#{callback_label(scope, function_name)} failed, " <>
"deflua functions must return encoded data, got #{inspect(value)}"
)

raise Lua.RuntimeException, unencoded_return
end
end

defp callback_label([], function_name), do: "#{function_name}()"
defp callback_label(scope, function_name), do: "#{Enum.join(scope, ".")}.#{function_name}()"

defp to_lua_key(key) when is_atom(key), do: Atom.to_string(key)
defp to_lua_key(key) when is_binary(key), do: key
defp to_lua_key(key), do: key
Expand Down
5 changes: 5 additions & 0 deletions lib/lua/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ defmodule Lua.API do

Keep in mind that if you want to work with values passed to `deflua` functions,
they still need to be decoded first.

## Errors

Call `runtime_exception!/1` or return `{:error, reason}` to give `pcall` a
readable error. Other exceptions reach `pcall` as `"error in host function"`.
"""

defmacro __using__(opts) do
Expand Down
28 changes: 25 additions & 3 deletions lib/lua/vm/protected_call.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ defmodule Lua.VM.ProtectedCall do
# (`pcall`/`xpcall`, and `Lua.call_function/3`), per §6.1: the raised value
# passes through verbatim.
#
# Clause ordering is load-bearing:
# `caught_value/1` replaces host exception messages, which can quote host
# data, with `"error in host function"`.
#
# `error_value/1` clause ordering is load-bearing:
# 1. `error()`'s §6.1-prefixed string view (`RuntimeError.lua_value`).
# 2. Raw passthrough on KEY PRESENCE — `value: nil` (from `error()`) and
# `value: false` must match here so the boundary returns nil/false like
Expand All @@ -14,11 +17,30 @@ defmodule Lua.VM.ProtectedCall do
# `:value` slot, so it gets its own clause that returns the raw
# `"bad argument #N to 'F' ..."` string — never the terminal-rendered
# `Exception.message/1` (ANSI + location header).
# 4. Plain Elixir exceptions keep their message string as a last resort.
alias Lua.VM.ArgumentError
alias Lua.VM.AssertionError
alias Lua.VM.RuntimeError
alias Lua.VM.TypeError

@vm_errors [RuntimeError, AssertionError, TypeError, ArgumentError]

@host_error_message "error in host function"

def caught_value(exception), do: caught_value(exception, raised_for_script?(exception))

defp caught_value(%module{} = vm_error, true) when module in @vm_errors, do: error_value(vm_error)
defp caught_value(runtime_exception, true), do: Exception.message(runtime_exception)
defp caught_value(_host_exception, false), do: @host_error_message

defp raised_for_script?(%module{}) when module in @vm_errors, do: true

defp raised_for_script?(%Lua.RuntimeException{original: original}) when is_exception(original),
do: raised_for_script?(original)

defp raised_for_script?(%Lua.RuntimeException{}), do: true
defp raised_for_script?(_host_exception), do: false

def error_value(%{lua_value: lv}) when not is_nil(lv), do: lv
def error_value(%{value: value}), do: value
def error_value(%ArgumentError{} = e), do: ArgumentError.raw_message(e)
def error_value(e), do: Exception.message(e)
end
121 changes: 71 additions & 50 deletions lib/lua/vm/stdlib.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ defmodule Lua.VM.Stdlib do
alias Lua.VM.RuntimeError
alias Lua.VM.State
alias Lua.VM.Table
alias Lua.VM.TypeError
alias Lua.VM.Value

# Installed in this order: it is the order `pairs(_G)` and
Expand Down Expand Up @@ -121,31 +120,28 @@ defmodule Lua.VM.Stdlib do
{[str], state}
end

defp lua_tostring([], state), do: {["nil"], state}
defp lua_tostring([], _state), do: raise(ArgumentError.value_expected("tostring", 1))

# tonumber(v [, base]) — converts a string to a number
defp lua_tonumber([value | rest], state) do
base = List.first(rest)
defp lua_tonumber([], _state), do: raise(ArgumentError.value_expected("tonumber", 1))

result =
case {value, base} do
{v, nil} when is_number(v) ->
v
defp lua_tonumber([value | base], state), do: {[tonumber(value, base)], state}

{v, nil} when is_binary(v) ->
Value.parse_number(v)
defp tonumber(value, []), do: to_number_or_nil(value)
defp tonumber(value, [nil | _]), do: to_number_or_nil(value)
defp tonumber(value, [base | _]), do: tonumber_in_base(value, integer_argument!(base, "tonumber", 2))

{v, b} when is_binary(v) and is_integer(b) and b >= 2 and b <= 36 ->
parse_in_base(v, b)
defp to_number_or_nil(value) when is_number(value), do: value
defp to_number_or_nil(value) when is_binary(value), do: Value.parse_number(value)
defp to_number_or_nil(_value), do: nil

_ ->
nil
end
defp tonumber_in_base(value, _base) when not is_binary(value),
do: raise(ArgumentError.type_error("tonumber", 1, "string", Value.type_name(value)))

{[result], state}
end
defp tonumber_in_base(_value, base) when base not in 2..36,
do: raise(ArgumentError, function_name: "tonumber", arg_num: 2, details: "base out of range")

defp lua_tonumber([], state), do: {[nil], state}
defp tonumber_in_base(value, base), do: parse_in_base(value, base)

# tonumber(s, base) per Lua 5.3 §6.1: surrounding whitespace is ignored, an
# optional sign is allowed, digits a-z/A-Z map to 10-35 (case-insensitive),
Expand Down Expand Up @@ -253,12 +249,7 @@ defmodule Lua.VM.Stdlib do
{results, state} = Executor.call_function(func, args, state)
{[true | results], state}
rescue
e in [RuntimeError, AssertionError, TypeError, ArgumentError] ->
{[false, ProtectedCall.error_value(e)], State.unwind_to(state, e.state)}

e ->
# Catch any other error
{[false, Exception.message(e)], State.unwind_to(state, raised_state(e))}
exception -> {[false, ProtectedCall.caught_value(exception)], State.unwind_to(state, raised_state(exception))}
end

defp lua_pcall([], state), do: {[false, "bad argument #1 to 'pcall' (value expected)"], state}
Expand All @@ -273,12 +264,8 @@ defmodule Lua.VM.Stdlib do
{results, state} = Executor.call_function(func, args, state)
{[true | results], state}
rescue
e in [RuntimeError, AssertionError, TypeError, ArgumentError] ->
run_xpcall_handler(handler, ProtectedCall.error_value(e), State.unwind_to(state, e.state))

e ->
# Catch any other error
run_xpcall_handler(handler, Exception.message(e), State.unwind_to(state, raised_state(e)))
exception ->
run_xpcall_handler(handler, ProtectedCall.caught_value(exception), State.unwind_to(state, raised_state(exception)))
end

defp lua_xpcall(_, state), do: {[false, "bad argument to 'xpcall'"], state}
Expand All @@ -304,12 +291,27 @@ defmodule Lua.VM.Stdlib do
{[Table.get(table, key)], state}
end

defp lua_rawget(args, _state), do: raise(table_argument_error("rawget", args))

# rawset(table, key, value) — set without metamethods
defp lua_rawset([{:tref, _} = tref, key, value | _], state) do
state = State.update_table(state, tref, fn table -> Table.put(table, key, value) end)
{[tref], state}
end

defp lua_rawset(args, _state), do: raise(table_argument_error("rawset", args))

defp table_argument_error(function_name, []), do: ArgumentError.value_expected(function_name, 1)

defp table_argument_error(function_name, [{:tref, _} | _] = too_few_args),
do: missing_argument_error(function_name, too_few_args)

defp table_argument_error(function_name, [non_table | _]),
do: ArgumentError.type_error(function_name, 1, "table", Value.type_name(non_table))

defp missing_argument_error(function_name, given_args),
do: ArgumentError.value_expected(function_name, length(given_args) + 1)

# rawlen(v) — length without metamethods.
#
# Lua 5.3 reference: rawlen requires a table or string argument and
Expand Down Expand Up @@ -342,7 +344,7 @@ defmodule Lua.VM.Stdlib do
{[a === b], state}
end

defp lua_rawequal(_, state), do: {[false], state}
defp lua_rawequal(args, _state), do: raise(missing_argument_error("rawequal", args))

# next(table [, key]) — returns next key-value pair after key.
# Per Lua 5.3 §6.1, when `key` is non-nil and was never a key in the
Expand Down Expand Up @@ -381,7 +383,7 @@ defmodule Lua.VM.Stdlib do
end
end

defp lua_next(_, state), do: {[nil, nil], state}
defp lua_next(args, _state), do: raise(table_argument_error("next", args))

# pairs(table) — returns next, table, nil
defp lua_pairs([{:tref, _} = tref | _], state) do
Expand Down Expand Up @@ -421,24 +423,20 @@ defmodule Lua.VM.Stdlib do
{[length(args)], state}
end

defp lua_select([index | args], state) when is_integer(index) do
cond do
# Positive index: return from that position onward
index > 0 ->
selected = Enum.drop(args, index - 1)
{selected, state}

# Negative index: count from end (take last n elements)
index < 0 ->
selected = Enum.take(args, index)
{selected, state}
defp lua_select([index | args], state) when is_integer(index) and index > 0 do
{Enum.drop(args, index - 1), state}
end

# Index 0 is invalid
true ->
raise RuntimeError, value: "bad argument #1 to 'select' (index out of range)"
end
defp lua_select([index | args], state) when is_integer(index) and index < 0 and -index <= length(args) do
{Enum.take(args, index), state}
end

defp lua_select([index | _], _state) when is_integer(index),
do: raise(ArgumentError, function_name: "select", arg_num: 1, details: "index out of range")

defp lua_select([index | args], state) when is_float(index),
do: lua_select([integer_argument!(index, "select", 1) | args], state)

defp lua_select([non_valid | _], _state) do
raise ArgumentError,
function_name: "select",
Expand All @@ -451,6 +449,25 @@ defmodule Lua.VM.Stdlib do
raise ArgumentError.value_expected("select", 1)
end

# `luaL_checkinteger`: accepts a float with an exact integer value.
defp integer_argument!(value, _function_name, _arg_num) when is_integer(value), do: value

defp integer_argument!(value, function_name, arg_num) when is_float(value) do
truncated = trunc(value)

if value == truncated and Numeric.signed?(truncated) do
truncated
else
raise ArgumentError,
function_name: function_name,
arg_num: arg_num,
details: "number has no integer representation"
end
end

defp integer_argument!(value, function_name, arg_num),
do: raise(ArgumentError.type_error(function_name, arg_num, "number", Value.type_name(value)))

# load(chunk, chunkname, mode, env) — loads a Lua chunk
# `chunk` may be either a string or a reader function. A reader function
# is called repeatedly; each call must return a string piece, and the
Expand Down Expand Up @@ -565,7 +582,7 @@ defmodule Lua.VM.Stdlib do
defp format_parse_error(error) when is_binary(error), do: error

# setmetatable(table, metatable) — sets the metatable for a table
defp lua_setmetatable([{:tref, _} = tref, metatable], state) do
defp lua_setmetatable([{:tref, _} = tref, metatable | _], state) do
# Check for __metatable protection on existing metatable
table = State.get_table(state, tref)

Expand Down Expand Up @@ -599,6 +616,10 @@ defmodule Lua.VM.Stdlib do
end
end

defp lua_setmetatable([{:tref, _}], _state) do
raise ArgumentError, function_name: "setmetatable", arg_num: 2, expected: "nil or table"
end

defp lua_setmetatable([non_table | _], _state) do
raise ArgumentError,
function_name: "setmetatable",
Expand Down Expand Up @@ -642,8 +663,8 @@ defmodule Lua.VM.Stdlib do
{[nil], state}
end

defp lua_getmetatable([], state) do
{[nil], state}
defp lua_getmetatable([], _state) do
raise ArgumentError.value_expected("getmetatable", 1)
end

# Install package table with loaded and path fields
Expand Down
5 changes: 4 additions & 1 deletion lib/lua/vm/stdlib/os.ex
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,10 @@ defmodule Lua.VM.Stdlib.Os do
# treated as identical. The utc? flag is parsed for compatibility with
# the leading '!' but does not change the result.
defp to_datetime(time, _utc?) do
DateTime.from_unix!(time, :second)
case DateTime.from_unix(time, :second) do
{:ok, datetime} -> datetime
{:error, _reason} -> raise RuntimeError, value: "time result cannot be represented in this installation"
end
end

defp date_table(%DateTime{} = dt, state) do
Expand Down
Loading