Skip to content

Commit

Permalink
Support returning chunks from Lua.API.install/1 (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
davydog187 authored Sep 3, 2024
1 parent 9cc7dd3 commit ec21718
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
11 changes: 6 additions & 5 deletions lib/lua/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ defmodule Lua.API do
can run arbitrary Lua code or change the `Lua` state in any way.
An `install/1` callback takes a `t:Lua.t/0` and should either return a
Lua script to be evaluated, or return a new `t:Lua.t/0`
Lua script to be evaluated, a `t:Lua.Chunk.t/0`, or return a new `t:Lua.t/0`
defmodule WithInstall do
use Lua.API, scope: "install"
Expand All @@ -61,7 +61,8 @@ defmodule Lua.API do
If you don't need to write Elixir, but want to execute some Lua
to setup global variables, modify state, or expose some additonal
APIs, you can simply return a Lua script directly
APIs, you can simply return a Lua chunk directly using the `c` modifier
on `Lua.sigil_LUA/2`
defmodule WithLua do
use Lua.API, scope: "whoa"
Expand All @@ -70,7 +71,7 @@ defmodule Lua.API do
@impl Lua.API
def install(_lua) do
~LUA[print("Hello at install time!")]
~LUA[print("Hello at install time!")]c
end
end
"""
Expand Down Expand Up @@ -204,13 +205,13 @@ defmodule Lua.API do
%Lua{} = lua ->
lua

code when is_binary(code) ->
code when is_binary(code) or is_struct(code, Lua.Chunk) ->
{_, lua} = Lua.eval!(lua, code)
lua

other ->
raise Lua.RuntimeException,
"Lua.API.install/1 must return %Lua{} or a Lua literal, got #{inspect(other)}"
"Lua.API.install/1 must return %Lua{}, %Lua.Chunk{}, or Lua literal, got #{inspect(other)}"
end
else
lua
Expand Down
23 changes: 23 additions & 0 deletions test/lua/api_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,29 @@ defmodule Lua.APITest do
return whoa
""")
end

test "it can return lua chunks directly" do
assert [{module, _}] =
Code.compile_string("""
defmodule WithLuaChunk do
use Lua.API
import Lua
@impl Lua.API
def install(_lua) do
~LUA[whoa = "crazy"]c
end
end
""")

lua = Lua.load_api(Lua.new(), module)

assert {["crazy"], _} =
Lua.eval!(lua, """
return whoa
""")
end
end

describe "deflua" do
Expand Down

0 comments on commit ec21718

Please sign in to comment.