lua-users home
lua-l archive

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



Håkon Evensen wrote:

Is it possible to register a c function call to overload a assignment to a special variable?

so if i in lua write:

yo = 4

i would get that 4 in a registered c function? What i need is lua tables with spesific names which really just calls one c function on read, and another on write.

Starting with this example: http://lua-users.org/lists/lua-l/2003-06/msg00498.html

You can alter it to check for your 'special' variables like so:

$ cat x.lua

do
  local read_actions = {
    yo  = function(t, name) print'yo read function' end,
    foo = function(t, name) print'foo read function' end,
  }

  local write_actions = {
    yo  = function(t, name, value) print'yo write function' end,
    foo = function(t, name, value) print'foo write function' end,
  }

  local function set(t, name, value)
    print("set", name, value)
    local wa = write_actions[name]
    if wa then wa(t, name, value) end
  end

  local function get(t, name)
    print("get", name)
    local ra = read_actions[name]
    if ra then return ra(t, name) end
    return nil -- or some default value
  end

  setmetatable(getfenv(), {__index=get, __newindex=set})
end

$ lua -lx -i
>
> yo = 4
set     yo      4
yo write function
>
> local x = yo
get     yo
yo read function
>
> yo = foo
get     foo
foo read function
set     yo      nil
yo write function
>

You just need to put your C funtions in the lookup tables.

- Peter Shook