New user question re: settagmethod

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

New user question re: settagmethod

Pete Gardner
Hi everyone,

I'm researching Lua to determine it's potential use in a product I am
working on.  I'm interested in using the object inheritance concepts made
available through the use of settagmethod().  Unfortunately, the only
examples I've seen of it are from back when it was called setfallback(),
which did not take tags into account.

Here's how I've got it to work:

-- Create a dummy table
   BaseTable = {}

-- Define the inherit function
function inherit (object, field)
  if field == "parent" then     -- avoid loops
    return nil
  end
  local p = object.parent       -- access parent object
  if type(p) == "table" then    -- check if parent is a table
    return p[field]             -- (this may call Inherit again)
  else
    return nil
  end
end

-- Set the tag method.
settagmethod(tag(BaseTable),"index",inherit)		 


Note that I've created a dummy table to provide the tag for settagmethod().
It seems to work for all tables from this point on.

My question is, is this the proper way to do this, or is there a more
elegant method?

Pete Gardner
President, CEO
Helikon Technologies Inc.
http://www.helikon.com






Pete Gardner
President, CEO
Helikon Technologies Inc.
http://www.helikon.com





Reply | Threaded
Open this post in threaded view
|

Re: New user question re: settagmethod

Tomas-14
> function inherit (object, field)
>   if field == "parent" then     -- avoid loops
>     return nil
>   end
>   local p = object.parent       -- access parent object
	I think you should use rawgettable instead:
	rawgettable (object, "parent")

>   if type(p) == "table" then    -- check if parent is a table
>     return p[field]             -- (this may call Inherit again)
>   else
>     return nil
>   end
> end
> 
> -- Set the tag method.
> settagmethod(tag(BaseTable),"index",inherit)		 
	Here you can use just an empty table, but I think it'll be the same:
settagmethod (tag({}), "index", inherit)

	Tomas