lua-users home
lua-l archive

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


On Thu, Mar 01, 2007 at 12:11:05PM +0100, Timm Felden wrote:
> Is there a way of writing a function "lua_link( name, set, get );", that 
> would do this:
> lua:  name = <any value(s)>
> -> invokes the parameter passed as set, this is like the normal C-functions
> 
> lua: x = name
> -> invokes set, which is also a normal C-function, but by default gets 
> no parameters and returns only one.
> 
> I ask, because I have to take care of values between lua and C and atm 
> I'm using functions, what is pretty ugly:P

Doing

  name = 4

is the same as

  getfenv()['name'] = 4

Lua 5.1.1  Copyright (C) 1994-2006 Lua.org, PUC-Rio
> = getfenv()['hi']
nil
> getfenv()['hi'] = 3
> = getfenv()['hi']
3
> = hi
3

so you can make a metatable for your function environment (the table
returned by getfenv()), and define __index and __newindex in that
metatable to do your linking.

Is something like this what you are thinking of? Its written in lua, but
you can do the same thing in C, or just call attr_link() from C:

function attr_setup()
    -- handlers: name => { fn get, fn set }
    local handlers = {}
    local mt = {
        __index = function(t, k)
            local h = handlers[k]
            return h and h.get()
        end,
        __newindex = function(t, k, v)
            local h = handlers[k]
            if h then
                return h.set(v)
            else
                rawset(t, k, v)
            end
        end,
    }

    setmetatable(getfenv(), mt)

    function attr_link(name, set, get)
        handlers[name] = { set = set, get = get }
    end
end

attr_setup()

do
    local v_ = 3
    attr_link('fu', function(v) v_ = v end, function() return v_ end)
end

fu = fu + 1
bar = fu

print(bar)