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 <steve.j.donovan@gmail.com
> <mailto:steve.j.donovan@gmail.com>> 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'.
-- MyObject.new() is the factory.

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

module('MyObject')

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

local MT = { __id = ID }

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

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

-- Test run:

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


______________________________________________________________________________________
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.