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
22 changes: 22 additions & 0 deletions spec/lua/stack_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,28 @@ module Lua
stack.size.should eq 1
end
end

describe "#register_function" do
it "creates a new Lua function" do
stack = Stack.new
Stack.register_function stack, "crystal_debug", ->(value : String) do
value
end

result = stack.run %(return crystal_debug("hello"))
result.should eq("hello")
end

it "creates a new Lua function with two args" do
stack = Stack.new
Stack.register_function stack, "crystal_add", ->(x : Float64, y : Float64) do
x + y
end

result = stack.run "return crystal_add(1, 2)"
result.should eq(3)
end
end
end

private class LuaReporter
Expand Down
1 change: 1 addition & 0 deletions src/lua/stack.cr
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ module Lua
include StackMixin::CoroutineSupport
include StackMixin::StandardLibraries
include StackMixin::ClassSupport
include StackMixin::RegisterFunction

getter state
getter libs = Set(Symbol).new
Expand Down
26 changes: 26 additions & 0 deletions src/lua/stack/register_function.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module Lua
module StackMixin::RegisterFunction
macro included
macro register_function(stack, name, proc)
{% verbatim do %}
proc = ->(state : LibLua::State) {
{% for arg, index in proc.args %}
{{ arg.name }} = LibLua.tonumberx(state, {{ index + 1 }}, nil)
{% end %}

# push result to stack
LibLua.pushnumber(state, {{ proc.body }})
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming if one of the proc.args is a String, then we would call LibLua.pushstring here? But that expected a Pointer(UInt8) to be passed in... But also, what happens if the first arg is a String, and the second is a number? Does the value of each arg need to be pushed separately?


1 # number of results
}

# push crystal proc onto the stack
LibLua.pushcclosure({{ stack.id }}.state, proc, 0)

# give it a name
LibLua.setglobal({{ stack.id }}.state, {{ name }})
{% end %}
end
end
end
end