diff --git a/scripts/my_func.lua b/scripts/my_func.lua new file mode 100644 index 0000000..8a186c6 --- /dev/null +++ b/scripts/my_func.lua @@ -0,0 +1,13 @@ +function run_event(name) + print("run " .. name) + if(name == "archivist") then + Business.fetch_add(10) + else + Business.fetch_add(1) + end +end + +function display_event(name) + print("display " .. name) + return Business.fetch_add(0) +end \ No newline at end of file diff --git a/shard.lock b/shard.lock index 499152c..d316120 100644 --- a/shard.lock +++ b/shard.lock @@ -16,6 +16,10 @@ shards: git: https://github.com/jeromegn/kilt.git version: 0.6.1 + lua: + git: https://github.com/veelenga/lua.cr.git + version: 0.2.0 + radix: git: https://github.com/luislavena/radix.git version: 0.4.1 diff --git a/shard.yml b/shard.yml index 1165326..326cd57 100644 --- a/shard.yml +++ b/shard.yml @@ -11,6 +11,8 @@ targets: dependencies: kemal: github: kemalcr/kemal + lua: + github: veelenga/lua.cr crystal: 1.0.0 diff --git a/src/app/business.cr b/src/app/business.cr index bfd66f2..ace1dd2 100644 --- a/src/app/business.cr +++ b/src/app/business.cr @@ -1,9 +1,15 @@ require "./model.cr" +require "lua" class Business - def self.fetch_add(v = 1) - v += Model.get; - Model.set v; - return v; + include LuaCallable + def fetch_add(v = 1) + if v.is_a?(Float64) + v += Model.get; + Model.set v.to_i!; + return v.to_i!; + else + raise "Danger: wrong return value" + end end end \ No newline at end of file diff --git a/src/app/button.ecr b/src/app/button.ecr index 887b8ff..513f862 100644 --- a/src/app/button.ecr +++ b/src/app/button.ecr @@ -2,7 +2,7 @@ -
<%= count %>
+
<%= display_event.as(Lua::Function).call(name).as(Float64).to_i32!; %>
>
diff --git a/src/app/view.cr b/src/app/view.cr index b271c80..63a8e83 100644 --- a/src/app/view.cr +++ b/src/app/view.cr @@ -3,16 +3,30 @@ require "./business.cr" get "/:name" do |env| name = env.params.url["name"] - count = Business.fetch_add(0); - render "./src/app/button.ecr"; + stack = Lua.load; + stack.set_global("Business", Business.new); + stack.run File.new("./scripts/my_func.lua"); + display_event = stack.run %q{ + return display_event; + }; + view = render "./src/app/button.ecr"; + stack.close; + view; end post "/:name" do |env| - adder = 1; name = env.params.url["name"] - if name == "archivist" - adder = 10; - end - count = Business.fetch_add(adder); - render "./src/app/button.ecr"; + stack = Lua.load; + stack.set_global("Business", Business.new); + stack.run File.new("./scripts/my_func.lua"); + run_event = stack.run %q{ + return run_event; + }; + display_event = stack.run %q{ + return display_event; + }; + run_event.as(Lua::Function).call(name); + view = render "./src/app/button.ecr"; + stack.close; + view; end