Skip to content

Commit

Permalink
Implement decode!/2 (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
davydog187 authored Mar 19, 2024
1 parent 5898625 commit 8052199
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
12 changes: 11 additions & 1 deletion lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,17 @@ defmodule Lua do
{encoded, wrap(state)}
rescue
ArgumentError ->
reraise Lua.RuntimeException, "Failed to encode value", __STACKTRACE__
reraise Lua.RuntimeException, "Failed to encode #{inspect(value)}", __STACKTRACE__
end

@doc """
Decodes a Lua value from its internal form
"""
def decode!(%__MODULE__{} = lua, value) do
:luerl_new.decode(value, lua.state)
rescue
ArgumentError ->
reraise Lua.RuntimeException, "Failed to decode #{inspect(value)}", __STACKTRACE__
end

@doc """
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ defmodule Lua.MixProject do
use Mix.Project

@url "https://github.com/tv-labs/lua"
@version "0.0.8"
@version "0.0.9"

def project do
[
Expand Down
20 changes: 16 additions & 4 deletions test/lua_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -222,24 +222,36 @@ defmodule LuaTest do
end
end

describe "encode!/1" do
describe "encode!/1 and decode!/1" do
test "it can encode values into their internal representation" do
lua = Lua.new()

assert {"hello", lua} = Lua.encode!(lua, "hello")
assert "hello" = Lua.decode!(lua, "hello")
assert {"hello", lua} = Lua.encode!(lua, :hello)
assert {5, lua} = Lua.encode!(lua, 5)
assert {{:tref, _}, lua} = Lua.encode!(lua, %{a: 1, b: 2})
assert {{:tref, _}, _lua} = Lua.encode!(lua, [1, 2, 3, 4])
assert 5 = Lua.decode!(lua, 5)
assert {{:tref, _} = ref, lua} = Lua.encode!(lua, %{a: 1, b: 2})
assert [{"a", 1}, {"b", 2}] = Lua.decode!(lua, ref)
assert {{:tref, _} = ref, lua} = Lua.encode!(lua, [1, 2])
assert [{1, 1}, {2, 2}] = Lua.decode!(lua, ref)
end

test "it raises for values that cannot be encoded" do
error = "Lua runtime error: Failed to encode value"
error = "Lua runtime error: Failed to encode {:foo, :bar}"

assert_raise Lua.RuntimeException, error, fn ->
Lua.encode!(Lua.new(), {:foo, :bar})
end
end

test "it raises for values that cannot be decoded" do
error = "Lua runtime error: Failed to decode :hello"

assert_raise Lua.RuntimeException, error, fn ->
Lua.decode!(Lua.new(), :hello)
end
end
end

describe "error messages" do
Expand Down

0 comments on commit 8052199

Please sign in to comment.