lua-users home
lua-l archive

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


Wesley Smith wrote:
> I've been looking at the UserDataRefinement wiki example
> (http://lua-users.org/wiki/UserDataRefinement) to try and understand
> how environments work with userdata.  What I don't understand from
> this example is the process by which a method gets overridden in a
> script and how the environment tables gets manipulated in this
> process.  I'm looking mostly at Udr Code Snippet Three
> (http://lua-users.org/wiki/UdrCodeSnippetThree).  Where would I place
> these functions in my userdata C code?  I don't want to modify liblua
> as is suggested later in the page.  Any hints?       
> 
> If I have userdata U with function do_it() defined in C consider the
> following code: 
> 
> U:do_it = function() print("new function") end
> U:do_it()  --how does the environment table for the userdata
>                  --come in to play here based on the Udr example?

When you write U.do_it (U:do_it() is equivalent to U.do_it(U)), you are
not using the userdata environment table but its metatable. More
specifically you are calling the userdata __index metamethod. In itself
it has nothing to do with environments.

To provide such behaviour to your userdata, you must have defined the
__index metamethod. To allow for method overrides you must implement the
__newindex metamethod.