User:NXTBoy/Scripts/"new" operator: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>NXTBoy
New page: <pre> _G.new = function(typeName) return function(properties) pcall(function local i = Instance.new(typeName) if type(properties) == "table" then for property, value in pairs(pro...
 
>NXTBoy
No edit summary
Line 1: Line 1:
<pre>
<pre>
_G.new = function(typeName)
_G.new = function(typeName)
return function(properties)
local instance
pcall(function
local i = Instance.new(typeName)
-- Instances
if type(properties) == "table" then
if pcall(function() instance = Instance.new(typeName) end) then
for property, value in pairs(properties) do
print("Instance")
if type(property) == "number" then
return function(properties)
value.Parent = i
if type(properties) == "table" then
else
for property, value in pairs(properties) do
i[property] = value
if type(property) == "number" then
value.Parent = instance
else
instance[property] = value
end
end
end
end
end
return instance
end
end
return i
 
-- Built in classes
elseif getfenv()[typeName] and type(getfenv()[typeName].new) == "function" then
return getfenv()[typeName].new
 
-- User classes defined in _G
elseif _G[typeName] and type(_G[typeName].new) == "function" then
return getfenv()[typeName].new
 
-- What is this I don't even
else
error("Unknown type \""..typeName..."\"", 2)
end
end
end
end
</pre>
</pre>


Line 22: Line 38:
<pre>
<pre>
local new = _G.new
local new = _G.new


local m = new "Model" {
local m = new "Model" {
Line 30: Line 45:
new "Part" {
new "Part" {
Name = "My Part",
Name = "My Part",
BrickColor = BrickColor.Red(),
BrickColor = new "BrickColor"("Bright red"),
Size = Vector3.new(2, 2, 2)
Size = new "Vector3"(2, 2, 2)
}
}
}
}

Revision as of 09:38, 15 September 2011

_G.new = function(typeName)
	local instance
	
	-- Instances
	if pcall(function() instance = Instance.new(typeName) end) then
		print("Instance")
		return function(properties)
			if type(properties) == "table" then
				for property, value in pairs(properties) do
					if type(property) == "number" then
						value.Parent = instance
					else
						instance[property] = value
					end
				end
			end
			return instance
		end

	-- Built in classes
	elseif getfenv()[typeName] and type(getfenv()[typeName].new) == "function" then
		return getfenv()[typeName].new

	-- User classes defined in _G
	elseif _G[typeName] and type(_G[typeName].new) == "function" then
		return getfenv()[typeName].new

	-- What is this I don't even
	else
		error("Unknown type \""..typeName..."\"", 2)
	end
end	

Usage as follows:

local new = _G.new

local m = new "Model" {
	Name = "Test",
	Parent = workspace,

	new "Part" {
		Name = "My Part",
		BrickColor = new "BrickColor"("Bright red"),
		Size = new "Vector3"(2, 2, 2)
	}
}

local p = new "Part"()
p.Parent = m