lua-users home
lua-l archive

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


The problem (if one would call it that) is that using empty tables with closures is a bit inelegant in comparison.
This is an extension providing a new way to encapsulate values, and that is simply what it does.
If anything is solved it is the absence of a userdata-like value to Lua code (such as newproxy implemented).

On Tue, Jan 28, 2020 at 2:21 AM Tim Hill <drtimhill@gmail.com> wrote:


On Jan 26, 2020, at 3:59 AM, Stefan Ginsberg <stefan.ginsberg@gmail.com> wrote:

I have an idea for Lua that I wish to share. It is called proxying, or envelopment of values, and is an extension to the Lua core adding a new type of value: proxy. The purpose of this value is to encapsulate other values, and it is implemented as such:

typedef struct Proxy {
  CommonHeader;
  TValue value;
  Table *metatable;
} Proxy;

The base library function 'envelop', using core lua_envelop, can be used to create a proxy by encapsulating a provided value through an associated metatable:

proxy = envelop(value, metatable)

This is similar to using an empty table with setmetatable, but the feature of "envelopment" means the proxied value is passed to metamethods instead of the proxy. This encapsulation works in the following way:

prx = envelop(val, meta)
val == self
prx(...) --> meta.__call(self, ...)
val = prx[idx] --> meta.__index(self, idx)
prx[idx] = val --> meta.__newindex(self, idx, val)

That is, 'val' and not 'prx' is passed to methods of 'meta'. An exception is garbage collection which will take the finalized proxy as its argument, to distinguish from the handling of the value. Another exception is '__metatable' which also applies to the proxy.

A proxy is a convenient value to use for interfacing, OOP, etc, and compared to using an empty table it is both more efficient and succinct than using closures to achieve the same goal.

Provided is a proof-of-concept implementation: https://pastebin.com/tR0L3kgw

What problem are you trying to solve here?

—Tm