Skip to content

Instantly share code, notes, and snippets.

@lastcanal
Last active December 14, 2015 11:09
Show Gist options
  • Save lastcanal/5077610 to your computer and use it in GitHub Desktop.
Save lastcanal/5077610 to your computer and use it in GitHub Desktop.
%% File : hello_table.erl
%% Purpose : Demonstration of luerl:table.
%% Use $ erlc hello_table.erl && erl -pa ../../ebin -s hello_table run -s init stop -noshell
-module(hello_table).
-export([run/0]).
run() ->
LuaScript = <<"hello_table = { hello=\"world\" }; return table;">>,
{_Val, Lua0} = luerl:do(LuaScript),
{<<"world">>,Lua1} = luerl:table([hello_table, hello], Lua0),
{<<"there">>,Lua2} = luerl:table([hello_table, hello], there, Lua1),
{<<"there">>,Lua3} = luerl:table([hello_table, hello], Lua2),
{[{<<"hello">>,<<"there">>}],_Lua4} = luerl:table([hello_table], Lua3),
done.
diff --git a/src/luerl.erl b/src/luerl.erl
index c594c43..584838e 100644
--- a/src/luerl.erl
+++ b/src/luerl.erl
@@ -24,6 +24,7 @@
do/1,do/2,dofile/1,dofile/2,
load/1,loadfile/1,call/2,call/3,call_chunk/2,call_chunk/3,
call_function/2,call_function/3,call_function1/3,function_list/2,
+ table/2,table/3,
call_method/2,call_method/3,call_method1/3,method_list/2,
init/0,stop/1,gc/1,
encode/2,encode_list/2,decode/2,decode_list/2]).
@@ -129,6 +130,26 @@ function_list([G|Kl], St0) ->
lists:foldl(Fun, {First,St1}, Kl);
function_list(_, _) -> error(badarg).
+%% table(Fp, State) -> {Value, State}.
+%% Go down a list of keys and return decoded final value.
+table(Fp, St0) when is_list(Fp) ->
+ {Lfp,St1} = encode_list(Fp, St0),
+ {V,St1} = function_list(Lfp, St0),
+ Vd = decode(V, St1),
+ {Vd, St1};
+table(_,_) -> error(badarg).
+
+%% table(Fp, Value, State) -> {Value, State}.
+%% Go down a list of keys and set final key to Value
+table(Fp, V, St0) when is_list(Fp) ->
+ {Lfp0,St1} = encode_list(Fp, St0),
+ {Lfp1, [K]} = lists:split(length(Lfp0) - 1, Lfp0),
+ {Tab, St2} = function_list(Lfp1, St1),
+ {Lv, St3} = encode(V, St2),
+ St4 = luerl_emul:set_table_key(Tab, K, Lv, St3),
+ {Lv, St4};
+table(_,_,_) -> error(badarg).
+
%% call_method(FuncPath, Args) -> {Result,State}.
%% call_method(FuncPath, Args, State) -> {Result,State}.
%% call_method1(FuncPath | FuncPath, Args, State) -> {Result,State}.
diff --git a/src/luerl_emul.erl b/src/luerl_emul.erl
index 7dc958a..15ae8f0 100644
--- a/src/luerl_emul.erl
+++ b/src/luerl_emul.erl
@@ -41,7 +41,7 @@
%% Internal functions which can be useful "outside".
-export([alloc_table/1,alloc_table/2,free_table/2,
- functioncall/3,get_table_key/3,
+ functioncall/3,get_table_key/3,set_table_key/4,
getmetamethod/3,getmetamethod/4]).
%% Currently unused internal functions, to suppress warnings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment