I've recently discovered the usefulness of metatables and I was wondering if it's possible to make new objects available to instance.new with them. Here's an example of what I'm wanting because I'm horrible at explaining things with kitties for an example:
01 | Cat = { } --New cat base table |
02 |
03 | Cat.metatable = { __index = { --Setting the default values |
04 | alive = true , |
05 | legs = 4 , |
06 | name = "Artemis" |
07 | } } |
08 |
09 | Cat.new = function (specialsetvalues) --When you call this you can supply a table to change the default values |
10 | if specialsetvalues then --If you want to do what the comment above said then |
11 | setmetatable (specialsetvalues, Cat.metatable) --Sets the metatable of the optional table |
12 | return specialsetvalues --Returns it |
13 | end |
14 | specialsetvalues = { } --Makes a new table if you don't supply an optional table |
15 | setmetatable (specialsetvalues, Cat.metatable) --Sets that table's metatable |
This would output James
However, what I want is for this (Assuming all of the above code is referenced when using Instance.new("Cat")
):
1 | jeff = Instance.new( "Cat" ) |
2 | jeff.name = "Jeff" |
3 | print (jeff.name) |
to output Jeff
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?
You cannot directly modify the Instance.new
function but you may replace it with your own. First I save a copy of the Instance
table in the variable OldInstance
. This gives us the ability to be able to create instances after the table has been reassigned.
In this script all the custom functions that you want it to work withit must be placed inside the table.
01 | local CustomObjects = { Cat = Cat } |
02 |
03 | local OldInstance = Instance |
04 | Instance = { [ "new" ] = function (class,tab) |
05 | for o,n in pairs (CustomObjects) do |
06 | if class = = o then |
07 | return n.new(tab) |
08 | end |
09 | end |
10 | OldInstance.new(class,tab) |
11 | end } |
12 |
13 | james = Instance.new( "Cat" , { name = "james" } ) |
14 | print (james.name) --Prints james' name |
15 | print (james.legs) --Prints 4 |
16 | print (james.alive) --Prints true |
17 | Instance.new( "Part" ,Workspace) --Proving that using the function normally still works. |
This is a variant of the script above that searches all the variables in the environment to see if a table has the key new
. If it does it treats it as a custom object. If you wish you may use a different key to authenticate a table as a custom object so there are no mix ups.
This script will be less efficient than the one above.
01 | local OldInstance = Instance |
02 | Instance = { [ "new" ] = function (class,tab) |
03 | for o,n in pairs ( getfenv ()) do |
04 | if type (n) = = "table" then |
05 | if n [ "new" ] and class = = o then |
06 | return n.new(tab) |
07 | end |
08 | end |
09 | end |
10 | OldInstance.new(class,tab) |
11 | end } |