Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

javascript wins yet again

Name: Anonymous 2012-10-19 17:48

Name: Anonymous 2012-10-20 2:25


function Proxy(object, handler)
  local p = {}

  local get
  if handler.get ~= nil then
    get = function(target,key)
      return handler.get(object, key)
    end
  else
    get = object
  end

  local set
  if handler.set ~= nil then
    set = function(target,key)
      return handler.set(object, key)
    end
  else
    set = object
  end

  setmetatable(p, {
    __index = get,
    __newindex = set
  })

  return p
end

function contains(object, key)
  return rawget(object,key) ~= nil
end



Examples
Very simple example

An object with 37 as its default value when the property name is not in the object


handler = {
  get = function(target, name)
    local key = rawget(target, name)
    if key ~= nil then return key
    else return 37
    end
  end
}

p = Proxy({}, handler)
p.a = 1
p.b = "fuck you undefined isn't necessary!"

print(p.a, p.b) -- 1, "fuck you undefined isn't necessary!"
print(contains(p, 'c'), p.c) -- false, 37



No-op forwarding proxy

In this example, we are using a native Lua object to which our proxy will forward all operations that are applied to it.


target = {}
p = Proxy(target, {})

p.a = 37 -- operation forwarded to the proxy

print(target.a) -- 37. The operation has been properly forwarded



See also

    * "Lua is awesome" Brendan Eich presentation at LuaConf (slides)
    * Lua Already Implemented This proposal page and Lua builtin features page
    * Tutorial on Lua builtin feautures that were there since day one
    * Old Javascript Proxy Attempt API page

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List