lua-users home
lua-l archive

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


jimmyp@hal.csd.auth.gr:
> I see now that __index also only works on uninitialized globals.Why is
> that?Wouldn't it be possible to provide read,write,newread,newwrite
> metamethods?

It would be possible but the authors have chosen not to, probably for the
minor efficiency gain it grants on access of an already defined value(?).

But it's still not a problem for you... just don't actually *store* the
value under the index name you have chosen... store it somewhere else!
Either in the globals under another name (eg, "_secret_c_data"), or in
another table, or store it directly to the C variable that you want to hold
the value.

For example, consider the following code:

  -- Let's assume that you access you C version of your C-synced
  -- variable using the functions cget() & cset(). Here I'll simulate that
  -- by instead using a local variable to store the value.

  do
    local c
    function cget() return c end
    function cset(x) c=x end
  end

  -- Now we create "index" and "newindex" functions to intercept our synced
  -- variable "xyzzy". Note that we never actually update the global table
  -- to store the value, rather we rely on the C-stored version of the data.

  function ci(t,k)
    if (k=="xyzzy") then return cget() else return nil end
  end

  function cn(t,k,v)
    if (k=="xyzzy") then cset(v) else rawset(t,k,v) end
  end

  m = {__index=ci, __newindex=cn}

  setmetatable(_G,m)

The result of this is that if we say:
     abc = 123

then the global table's key "abc" will be store the 123 value, whereas:
    xyzzy = 456

will not affect the global table, but will instead call "cput(456)". Not too
inefficient (despite affecting the whole global table _G) as you only trap
accesses to globals that are undefined.

Is that the sort of thing you're after?

*cheers*
Peter Hill.