Answered by
8 years ago Edited 8 years ago
What is wrapping?
All objects have an interface (a way of interacting with it, invoking behavior, changing properties, etc...). However, sometimes the interface doesn't include something(s) that the programmer may find particularly useful. Unless you're the one designing the object, you can't just add or change it's preset behavior. You can, however, create your own interface for this object, which does the new interaction for you. This is called wrapping.
Creating a wrapper
In Lua, you can emulate the wrapping of an object by using tables (for the object) and metatables (for the wrapper). Say for example, you wanted to wrap a property to a Part
instance, which represents when the part was created (or when it was wrapped). We'll call this property BirthTime
. First, let's create a function that will handle this for us (you should know what tables and metatables are before reading):
02 | local part = Instance.new( "Part" , workspace) |
04 | local function WrapPart(part) |
09 | interface.BirthTime = os.time() |
12 | behavior.__index = part |
14 | function behavior:__newindex(key, value) |
19 | return setmetatable (interface, behavior) |
23 | local wrappedPart = WrapPart(part) |
26 | print (wrappedPart.BirthTime) |
27 | print (wrappedPart.Name) |
Now, this is a very weak example compared to a wrapper's full potential, but this is only meant to give you the idea. After all, we're just returning the table we created with only two metamethods to redirect reference. There's nothing that handles calling a function as a method on the object once wrapped, parenting something to it, etc. Creating more complex examples would probably just lead to more confusion at this stage. Hope this gave you a better idea of what wrapping is, if you have any questions, just let me know.