lua-users home
lua-l archive

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


On Wed, Dec 17, 2008 at 4:33 PM, Mark Hamburg wrote:
> So, now we can write:
>        label _angle, _radius
>        function Point( x, y )
>                return {
>                        _angle = math.atan2( y, x ),
>                        _radius = math.sqrt( y * y + x * x ),
>                        coordinates = function( self )
>                                return self._radius * math.cos( self._angle
> ), self._radius * math.sin( self._angle )
>                        end
>                }
>        end

You can achieve a similar effect with "inside-out objects"[1-2] via
Lua's support for weak keys.  Example:

local radius = setmetatable({}, {__mode = 'k'})
local angle  = setmetatable({}, {__mode = 'k'})

local function Point(x,y)
  local self = {}
  angle [self] = math.atan2(y,x)
  radius[self] = math.sqrt(y*y + x*x)
  function self:coordinates()
    return radius[self] * math.cos( angle[self] ),
             radius[self] * math.sin( angle[self] )
  end
  return self
end

This is at a cost of one table per attribute per class rather than one
table per object.

Also, since radius and angle are lexical variables, means of
compile-time detection of undefined variables[3] can detect
mispellings[2].  For example, "radus[self]" shows up as an access to
the global "radus" in a "luac -p -l example.lua | grep ETGLOBAL".

> #2: Non-iterable keys

The proposed __pairs and __ipairs metamethods in Lua 5.2 [4] may be
more general.

[1] http://www.stonehenge.com/merlyn/UnixReview/col63.html
[2] http://search.cpan.org/dist/Class-Std/lib/Class/Std.pm
[3] http://lua-users.org/wiki/DetectingUndefinedVariables
[4] http://lua-users.org/wiki/LuaFiveTwo