[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: How to export associative arrays to an embedded lua script?
- From: Nagaev Boris <bnagaev@...>
- Date: Mon, 12 Oct 2015 01:18:12 +0300
On Sun, Oct 11, 2015 at 1:20 AM, Rena <firstname.lastname@example.org> wrote:
> On Oct 10, 2015 2:23 AM, "email@example.com" <firstname.lastname@example.org> wrote:
>> Hi list,
>> I'm embedding Lua in a pascal program which uses several
>> tables filled with key/values pairs,
>> for example
>> xGuiPrefs['lang'] :
>> = 'en';
>> xEnviron['screenwidth'] := 480;
>> ...and so on. Now I
>> want to expose those tables (about 8 or 9) to Lua, so a script can read
>> and write values to them. I started with:
>> lua_pushstring(L, '__index');
>> (L, xl_getxtable); // my routine to read values
>> lua_rawset(L, -3);
>> // (__newindex is left out, for the moment)
>> to create a metatable
>> which will be associated to the various tables I will export.
>> Then for
>> every table to export I do this:
>> (L, 'xplcmetatable');
>> lua_setglobal(L, 'env');
>> This creates a Lua
>> table named "env". If a script tries to read a value from table env:
>> print (env.screenwidth)
>> lua nicely calls my routine xl_getxtable()
>> with two arguments - the table and the key.
>> My problem is that I don't
>> know how to get the table name lua refers to; while the key is passed
>> as a string, the table is passed as a lua internal variable which means
>> nothing to me. I tried to search around in examples, docs, and so on,
>> but with no success. I only discovered the Registry where, may be, I
>> can store the table as key and its name as value, so I can later fetch
>> the name of the table. Probably I will end up using different
>> xl_getxtable() functions, each one with its hard-coded table name
>> inside; it would be faster and the tables to export are not so many.
>> But while am at it, I want to understand.
> I think the simplest solution here is one of these:
> 1) Store the table name in the metatable (different metatable for each
> table, all specifying the same __index and __newindex methods)
> 2) Keep a table in the registry (with weak keys) mapping table to name (ie
> the key is the table you're interested in, the value is its name)
> 3) Keep the name in an upvalue for the __index and __newindex methods
> (different closure for each table)
> 4) Don't give Lua a table; give it a userdata containing a unique ID. (I'd
> use a numeric ID rather than a string since switch() is O(1) while a series
> of strncmp() is O(N).
Complexity of switch() in C is compiler dependent. It is at worst
O(n). Anyway for both strings and numbers hash map can be used to
resolve name in O(1).
Why not to store table address in userdata?