|
On Oct 10, 2015 2:23 AM, "linuxfan@tin.it" <linuxfan@tin.it> 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';
>
> or
>
> 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:
>
> luaL_newmetatable(L,
> 'xplcmetatable');
> lua_pushstring(L, '__index');
> lua_pushcfunction
> (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:
>
> lua_newtable(L);
> luaL_setmetatable
> (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.
>
> Regards,
> Linuxfan
>
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).