luerl icon indicating copy to clipboard operation
luerl copied to clipboard

gettig table data from a table ref

Open Licenser opened this issue 9 years ago • 3 comments

When writing the data structures wiki page I stumbled about the situation where a function defined using the 1 interface receives a table reference as an argument but didn't found a luerl_emul function related that would be the reverse of alloc_table. So I was wondering how would one go about reading data that is stored behind the reference?

Licenser avatar Nov 23 '16 17:11 Licenser

You can read values from a table reference using luerl_emul:get_table_keys/3, but only if you know the key you want to access.

Lua0 = luerl:init(),
{TableRef, Lua1} =  luerl:get_table1([<<"math">>], Lua0),
{Value, Lua2} = luerl_emul:get_table_keys(TableRef, [<<"pi">>], Lua1).

Getting the entire table is more difficult because tables are split into the 'array part' and the 'dictionary part'.

Getting only the keys from the 'dictionary part' could look something like this if defined in luerl_emul:

get_table_key_list(#tref{i=N}, #luerl{ttab=Ts}=St) ->
    #table{d=Dict} = ?GET_TABLE(N, Ts),	
    Keys = ttdict:fetch_keys(Dict),
    {Keys, St}.

lastcanal avatar Nov 23 '16 20:11 lastcanal

Awesome thanks. Updated the wiki page. I thought get_table_keys would give me a list of table keys :).

Licenser avatar Nov 23 '16 21:11 Licenser

The functions luerl:get_table/2 and luerl:get_table1/2 are just wrappers around luerl_emul:get_table_keys/2/3 where the first one encodes the list of keys into internal format. You don't have to explicitly find the first table.

The reason tables are split into 2 parts is make the array use of them with integer keys faster. A simple test I did gave about 20%. I will check out whether using maps is faster than the array module. Unfortunately I can't use maps for the whole table as their is no support for doing next efficiently.

rvirding avatar Nov 23 '16 21:11 rvirding