lua-users home
lua-l archive

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

Ryan Pusztai wrote:
> On Mon, Feb 8, 2010 at 8:38 AM, steve donovan <
> <>> wrote:
>     But, yes, there's a better way; ask the modules to export an object
>     factory (if that fails then it's definitely bad) and insist that these
>     objects all have a metatable which contains some distinct field/value.
>      This field can then identify the interface; the value can be made as
>     distinct as you like.
> Do you have a simple example of this. This is an intriguing idea and
> just want more details. Thanks. 

Below is a Lua-only version. In C you would typically declare a static
variable and use a pointer to it as the ID.

-- Put this in MyObject.lua, then require'MyObject'.
-- is the factory.

local getmetatable = getmetatable
local setmetatable = setmetatable
local type = type


local ID = {}  -- In C, use a pointer &ID for static int ID;

local MT = { __id = ID }

function new()
   return setmetatable({}, MT)

function isValid(self)
   local mt = getmetatable(self or {})
   return (mt ~= nil) and (mt.__id == ID)

-- Test run:

Lua 5.1.4  Copyright (C) 1994-2008, PUC-Rio
> require'MyObject'
> print(MyObject.isValid(obj))
> print(MyObject.isValid({}))

The information contained in this email transmission may contain proprietary and business 
sensitive information.  If you are not the intended recipient, you are hereby notified that 
any review, dissemination, distribution or duplication of this communication is strictly 
prohibited.  Unauthorized interception of this e-mail is a violation of law.  If you are not 
the intended recipient, please contact the sender by reply email and immediately destroy all 
copies of the original message.

Any technical data and/or information provided with or in this email may be subject to U.S. 
export controls law.  Export, diversion or disclosure contrary to U.S. law is prohibited.  
Such technical data or information is not to be exported from the U.S. or given to any foreign
person in the U.S. without prior written authorization of Elbit Systems of America and the 
appropriate U.S. Government agency.