Skip to content

Commit

Permalink
Implemented Lua.load() and Lua.load!().
Browse files Browse the repository at this point in the history
  • Loading branch information
artob committed Aug 4, 2016
1 parent 3dd4f18 commit 7bc9777
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,27 @@ defmodule Lua do
end
end

@doc "Compiles a Lua code snippet."
@spec load(Lua.State.t, binary) :: {:ok, Lua.State.t, Lua.Chunk.t} | {:error, any, any}
def load(%State{luerl: state}, code) do
case :luerl.load(code, state) do
{:ok, function, state} ->
{:ok, %State{luerl: state}, %Chunk{luerl: function}}
error -> error
end
end

@doc "Compiles a Lua code snippet."
@spec load!(Lua.State.t, binary) :: {Lua.State.t, Lua.Chunk.t}
def load!(%State{luerl: state}, code) do
case :luerl.load(code, state) do
{:ok, function, state} ->
{%State{luerl: state}, %Chunk{luerl: function}}
{:error, reason, _} ->
raise Error, reason: reason, message: inspect(reason)
end
end

@doc "Compiles a Lua source file."
@spec load_file(Lua.State.t, binary) :: {:ok, Lua.State.t, Lua.Chunk.t} | {:error, any, any}
def load_file(%State{luerl: state}, filepath) do
Expand Down
10 changes: 10 additions & 0 deletions test/lua_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ defmodule LuaTest do
assert_raise Lua.Error, fn -> Lua.eval_file!(Lua.State.new, "test/scripts/_enoent.lua") end
end

test "Lua.load/2" do
assert {:ok, %Lua.State{}, %Lua.Chunk{}} = Lua.load(Lua.State.new, "return 6 * 7")
assert {:error, _, _} = Lua.load(Lua.State.new, "foobar")
end

test "Lua.load!/2" do
assert {%Lua.State{}, %Lua.Chunk{}} = Lua.load!(Lua.State.new, "return 6 * 7")
assert_raise Lua.Error, fn -> Lua.load!(Lua.State.new, "foobar") end
end

test "Lua.load_file/2" do
assert {:ok, %Lua.State{}, %Lua.Chunk{}} = Lua.load_file(Lua.State.new, "test/scripts/hello.lua")
assert {:error, _, _} = Lua.load_file(Lua.State.new, "test/scripts/_enoent.lua")
Expand Down

0 comments on commit 7bc9777

Please sign in to comment.