lua-users home
lua-l archive

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

Just a little note, this:

>   local env = setmetatable({}, {__index = function(_, k) return _G[k] end})

Is equivalent to this:

>   local env = setmetatable({}, {__index = _G})

The second approach is a bit faster (warning: a very simplistic
micro-benchmark follows):

local N = 10000000
function runBench(name, env)
    local start = os.clock()
    for i=1,N do local x = env.print end
    local time = os.clock() - start
    print(name, time)
runBench('__index function', setmetatable({}, {__index = function(_,k)
return _G[k] end}))
runBench('__index table', setmetatable({}, {__index = _G}))

This is on a 2.3GHz Core i5 with Lua 5.1.4:

__index function	1.062802
__index table	0.372607

> Is this old? Is this new? Has this been done before?

The idea of not needing a colon for method call is not new - objects
via closures are discussed in PiL [1], and can be seen in various
projects like Lunatic Python [2].