lua-users home
lua-l archive

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


Wesley Smith skrev:
Let's say I have

Obj = {}
Obj_mt = { __index = function(t, k) -- do something
                    end
        }

function Obj.new(o)
   setmetatable(o, Obj_mt)
   return o
end

obj1 = Obj.new{}
obj1:draw_circle(0, 0, 0.5)


When draw_circle is called, it looks up __index and falls the function
defined in the metatable above where t = obj1 and k = "draw_circle".

My question is, how do I get at the arguments?  What happens to 0, 0,
0.5 and how can I access them?

thanks,
wes


What you could do is to return a anonymous (lambda) function that calls
the requested function. That might not be what you need in this case, but was usefull for me when implementing XML-RPC.

function Obj_mt.__index(t, k)
	return function(...)
		-- the function name to call is in `k'
		-- `...' is the arguments passed to this function

		-- dummy example
		if k == "draw_circle" then
			return my_draw_circle_impl(...)
		else
			return nil, "unknown function"
		end

		-- or, another dummy example
		return my_func_impl[k](...)
		-- where my_func_impl probably should have a metatable
		-- returning a default function for undefined k's giving
		-- a descriptive error message
	end
end

Another meta method to look at is __call, which can be quite nice :)

Cheers,
Andreas