Last active
September 12, 2016 23:06
-
-
Save lastcanal/5326991 to your computer and use it in GitHub Desktop.
Setting Erlang functions as values on a Luerl tables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% Initialize the luerl state | |
Lua0 = luerl:init(), | |
%% Create a new empty table | |
{HttpTable, Lua1} = luerl_emul:alloc_table(Lua0), | |
%% Set the empty table to the global key `http` | |
Lua2 = luerl_emul:set_global_key(<<"http">>, HttpTable, Lua1), | |
%% You can also set up the global table from Lua | |
% {[HttpTable], Lua2} = luerl:do("http = { request = nil }; return http"), | |
%% Currying function for encapsulating pool name. | |
%% Returns a function that is callable from Lua | |
PoolWrapper = fun(Pool) -> | |
fun([_Url] = Arguments, LuaState) -> | |
% check out process from Pool | |
% call ihttpc request | |
% recieve response | |
{[<<"my response">>], LuaState} | |
end | |
end, | |
%% Path to http request. Translates to 'http.request' in Lua | |
FunctionPath = [<<"http">>, <<"request">>], | |
%% Generate a function for Lua with curried Erlang arguments | |
Value = {function, PoolWrapper(my_private_pool)}, | |
%% Set the table in the lua state | |
{HttpTable, Lua3} = luerl:set_table1(FunctionPath, Value, Lua2), | |
%% Call the function from Erlang | |
{[<<"my response">>], _Lua5} = luerl:call_function1(FunctionPath, ["http://google.com"], Lua3), | |
%% Or call the function from Lua | |
{[<<"my response">>], _Lua6} = luerl:do("return http.request('http://google.com')", Lua3). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment