lua-users home
lua-l archive

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


On Mon, Feb 8, 2010 at 9:17 PM, Doug Rogers <doug.rogers@elbitsystems-us.com> wrote:

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
>

Thanks for the example, but I don't understand how it relates to my original question. I would like to define the plugin interface similar to a C++ abstract base class. If an object is derived from the base class you know the methods which are available for the host to call. 
In this example, how I understand it, you do an id check in order to know if an object is really the object you expect it to be, but I don't understand where you would define its interface. 
 
Thijs