Hi everyone,
I'm having quite a bit of trouble understanding how this piece of code works. I understand that there is comments to help understand what the scripter is doing but frankly i cant seem to make sense of it. The code above was created by scriptguider. The link to the original post can be found here: https://scriptinghelpers.org/questions/39391/wrapping-instances-with-robloxs-lua
In particular, i need help understanding:
Why interface and behaviour were specifically chosen as the name of the variable in the function.
How the local part interacts with the part in the WrapPart function.
What behavior.__index = part does
What function behavior:__newindex(key, value) ....... end does
How return setmetatable(interface, behavior) interacts with the rest of the code.
-- Create part first
local part = Instance.new("Part", workspace)
local function WrapPart(part)
local interface = {}
local behavior = {}
-- Object interface --
interface.BirthTime = os.time() -- Create property
-- Interface behavior --
behavior.__index = part -- Set reference to this object to part
function behavior:__newindex(key, value)
part[key] = value -- Set new index of this object to new index of part
end
-- Return new interface
return setmetatable(interface, behavior)
end
-- Pass part to wrapper
local wrappedPart = WrapPart(part)
-- As you can see, we can access both our new property, and all the part's other properties. Giving us the illusion we added something to this object.
print(wrappedPart.BirthTime) -- > Timestamp
print(wrappedPart.Name) -- > "Part"
Thanks for the help.
