lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Julien Hamaide wrote:
Lythoner LY wrote:
Hi All,

>> (snip)

if you have a limited number of type, you can define them as global variable :

INT = "INT"
FLOAT = "FLOAT"

function DEF_PARAM(v)
   -- do something here to set NAME property from v
   -- v["NAME"] = ???? How do I get string equivalent of variable v
   return v
end

Just load this script before your definition file, and TYPE will
automatically contain the text.





I think he meant the name of the variable:


>> In shell, >> >>> print(DeviceParam3.NAME) >> DeviceParam3 >> >>> print (type(DeviceParam3.NAME) >> string


Unfortunately, it is not possible to know what is the name of the variable you are assigning to (inside the DEF_PARAM function, of course). What I suggest, is to __newindex the chunk's environment and post-assign the name. Something like:



myconfiguration.lua: DeviceParam1 = DEF_PARAM{ TYPE = INT } DeviceParam2 = DEF_PARAM{ TYPE = INT } DeviceParam3 = DEF_PARAM{ TYPE = INT }

~~ end of myconfiguration.lua:


configloader.lua function load( filename ) local f = assert( loadfile( filename ) ) local e = setmetatable( {}, { __index = _G; __newindex = function( t, k, v ) if type( k ) == 'string' and type( v ) == 'table' then v.NAME = k end end; } ) setfenv( f, e ) f() end

~~ end of configloader.lua

Of course, this will cause all assignments of tables to global variables be changed. You can make some tricks to only assign the NAME fields to a particular subset. First, you can check for the presence of a TYPE attribute as a pre-condition (trivial). Second, you can store the newly created table in another table while creating it with DEF_PARAM and then check if the table being assigned belongs to it:

configloader2.lua
function load( filename )
    local f = assert( loadfile( filename ) )

    local t = {}
    local old_DEF_PARAM = DEF_PARAM

    local e = setmetatable(
        {
            DEF_PARAM = function( info )
                -- In case DEF_PARAM creates another table...
                info = old_DEF_PARAM( info )
                t[ info ] = true
                return info
            end;
        }, {
            __index = _G;
            __newindex = function( t, k, v )
                if t[ v ] then
                    v.NAME = k
                end
            end;
        }
    )
    setfenv( f, e )
    f()
end

~~ end of configloader2.lua

Hope that helps,

--rb