lua-users home
lua-l archive

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


--- John Passaniti <jpass@rochester.rr.com> wrote:
> For the more mentally sluggish (like me), when you implement what Luiz
> suggested, could you post the code?

Sure, though it's somewhat specific to my app. For one thing, I don't worry about 'gettable' on a
proxy, because that situation never occurs in the mechanically translated FOO scripts.


local is_proxy, 
  proxy_tonum, 
  proxy_tostr, 
  proxy

function is_proxy(p)
  return type(p) == "table" and metatable(p) == proxy_metatable
end

function proxy_tonum(p)
  if is_proxy(p) then
    setglobal(p.name, 0)
    return 0
  else
    return p
  end
end

function proxy_tostr(p)
  if is_proxy(p) then
    setglobal(p.name, "")
    return "" 
  else
    return p
  end
end

proxy_metatable = {
  add = function(l,r) return proxy_tonum(l) + proxy_tonum(r) end,
  sub = function(l,r) return proxy_tonum(l) - proxy_tonum(r) end,
  mul = function(l,r) return proxy_tonum(l) * proxy_tonum(r) end,
  div = function(l,r) return proxy_tonum(l) / proxy_tonum(r) end,
  pow = function(l,r) return proxy_tonum(l) ^ proxy_tonum(r) end,
  unm = function(o) setglobal(o.name, 0) return 0  end, 
  concat = function(l,r) return proxy_tostr(l) ..proxy_tostr(r) end,
  settable = function(t,k,v) 
    local nt = {}
    rawset (nt, k, v)
    setglobal (t.name, nt)
  end,
}

metatable (
  globals(), {
  index = function(t,k) 
    local proxy = { name = k }
    metatable (proxy, proxy_metatable)
    rawset (t, k, proxy) 
    return proxy 
  end,
  })


-- Try it out...

a = b + 1 + -c * d
e = f / 1 ^ g
h = i .. "str"
j[1] = "one"

print (a, b, c, d, e, f, g, h, i, j[1])


__________________________________________________
Do You Yahoo!?
Yahoo! Greetings - Send FREE e-cards for every occasion!
http://greetings.yahoo.com