generic image
Processing...
  • Games
  • Catalog
  • Develop
  • Robux
  • Search in Players
  • Search in Games
  • Search in Catalog
  • Search in Groups
  • Search in Library
  • Log In
  • Sign Up
  • Games
  • Catalog
  • Develop
  • Robux
   
ROBLOX Forum » Game Creation and Development » Scripters
Home Search
 

Re: What does your code look like?

Previous Thread :: Next Thread 
nickmaster24 is not online. nickmaster24
Joined: 04 Oct 2008
Total Posts: 8906
02 Jun 2012 09:42 PM
Here's some code I am currently writing.

--[ GET TARGETS ]--
TargetType = "Red"

function GetTargets()
ToSearch = script.Parent.Parent:GetChildren()
local Targets = {}
for i = 1, #ToSearch do
--print(i .. " " .. ToSearch[i].Name)
if ToSearch[i]:findFirstChild("Type") then
if ToSearch[i].Type.Value == TargetType then
Targets[#Targets+1] = ToSearch[i]
end
end
end
return Targets
end

--[ CHECK CLOSEST TARGET ]--

function CheckClosestTarget(TableOfTargets)
if #TableOfTargets > 1 then
local CurrentMag = (Vector2.new(_G.Nodes[1]["x"], _G.Nodes[1]["y"]) - Vector2.new(Brick.Position.x,Brick.Position.z)).magnitude
local Closest = TableOfTargets
for i = 2, #_G.Nodes do
if CurrentMag > (Vector2.new(_G.Nodes[i]["x"], _G.Nodes[i]["y"]) - Vector2.new(Brick.Position.x,Brick.Position.z)).magnitude then
CurrentMag = (Vector2.new(_G.Nodes[i]["x"], _G.Nodes[i]["y"]) - Vector2.new(Brick.Position.x,Brick.Position.z)).magnitude
Closest = _G.Nodes[i]
end
end
return Closest
elseif #TableOfTargets == 1 then
return TableOfTargets[1]
else
return nil
end
end



--[ CHECK CLOSEST NODE ]--

function CheckClosestNode(Brick)
local CurrentMag = (Vector2.new(_G.Nodes[1]["x"], _G.Nodes[1]["y"]) - Vector2.new(Brick.Position.x,Brick.Position.z)).magnitude
local Closest = _G.Nodes[1]
for i = 2, #_G.Nodes do
if CurrentMag > (Vector2.new(_G.Nodes[i]["x"], _G.Nodes[i]["y"]) - Vector2.new(Brick.Position.x,Brick.Position.z)).magnitude then
CurrentMag = (Vector2.new(_G.Nodes[i]["x"], _G.Nodes[i]["y"]) - Vector2.new(Brick.Position.x,Brick.Position.z)).magnitude
Closest = _G.Nodes[i]
end
end
return Closest
end

-------------------------
--[[ FOR PATHFINDING ]]--
-------------------------

--[ TABLE INSERT FOR MY STYLE ]--
function TabIns(table, val)
table.insert(table, #table+1, val)
end


--[ SET F, G, AND H ]--

function GetValues(

end


--[ MAKE NEIGHBORS OPEN ]--

function InsertNeighbors(

end


--[[ ACTUALLY FIND PATH ]]--

_G.aStarPathfind = function(Start, End) --Start and End are the term numbers of each node from the _G.Nodes table

local Nodes = _G.Nodes
local OpenNodes = {}
local ClosedNodes = {}
local Finished = false
local FinalPath = {}

TabIns(OpenNodes, Start)
f


while Finished == false do








end

return FinalPath

end



---------------
--[ RUNTIME ]--
---------------


--[[For Testing]]--
wait(3)
while true do
wait(1)
print( "Closest Node:" )
print(CheckClosestNode(script.Parent.Torso)[2])
print( "Closest Target:" )
print(CheckClosestTarget(GetTargets()))
end

~Read Between The Squiggles~
Report Abuse
JulienDethurens is not online. JulienDethurens
Joined: 11 Jun 2009
Total Posts: 11046
03 Jun 2012 12:20 AM
Some code I wrote more or less recently:

local Players = Game:GetService('Players')
local StarterPack = Game:GetService('StarterPack')
local StarterGui = Game:GetService('StarterGui')
local Lighting = Game:GetService('Lighting')
local Debris = Game:GetService('Debris')
local Teams = Game:GetService('Teams')
local BadgeService = Game:GetService('BadgeService')
local InsertService = Game:GetService('InsertService')
local Terrain = Workspace.Terrain

local verify_arg
repeat wait() until _G.gloo
local gloo = _G.gloo

local function is_a(value, data_type)
    -- Supported types: Lua types, Instance types, Enum types, Enum, Color3, BrickColor, Vector2, Vector3, CFrame/CoordinateFrame, UDim, UDim2, RBXScriptSignal, Axes, Faces, Ray
    -- Will return false if the type is not supported, even though the value might be of that type.
    -- This function can not be fooled by a fake value. If it says the value is a ClickDetector, then it IS a ClickDetector.
    -- This function uses a variety of ugly hacks that were found by JulienDethurens.
    -- I wish ROBLOX just provided an official way to do this, I wouldn't have to use lots of unrealiable ways to get the info I need... :/

    -- Here is a nice collection of bad practices, ugly hacks, and other things you should never use, but that you don't have the choice of using, because of ROBLOX's lack of an official way to distinguish data types:
    data_type = verify_arg(data_type, 'string', "data_type")
    if type(value) == data_type then return true end -- Lua types
    if pcall(function() assert(Game.IsA(value, data_type)) end) then return true end -- Instance types
    if pcall(function() assert(Enum[data_type]) end) then -- Enum types
        for _, enum in next, Enum[data_type]:GetEnumItems() do
            if value == enum then
                return true
            end
        end
    elseif pcall(Enum.Material.GetEnumItems, value) then
        for _, enum in next, value:GetEnumItems() do
            if value == enum then
                return true
            end
        end
    end
    if data_type == 'Color3' and pcall(function() Instance.new('Color3Value').Value = value end) then return true -- Color3
    elseif data_type == 'BrickColor' and pcall(function() Instance.new('BrickColorValue').Value = value end) then return true -- BrickColor
    elseif data_type == 'Vector2' and pcall(function() return Vector2.new() + value end) then return true -- Vector2
    elseif data_type == 'Vector3' and pcall(function() Instance.new('Vector3Value').Value = value end) then return true -- Vector3
    elseif (data_type == 'CFrame' or data_type == 'CoordinateFrame') and pcall(function() Instance.new('CFrameValue').Value = value end) then return true -- CFrame
    elseif data_type == 'UDim' and pcall(function() return UDim.new() + value end) then return true -- UDim
    elseif data_type == 'UDim2' and pcall(function() Instance.new('Frame').Position = value end) then return true -- UDim2
    elseif data_type == 'Ray' and pcall(function() Ray.new(Vector3.new(), Vector3.new()).Distance(value, Vector3.new()) end) then return true -- Ray
    elseif data_type == 'Axes' and pcall(function() Instance.new('ArcHandles').Axes = value end) then return true -- Axes
    elseif data_type == 'Faces' and pcall(function() Instance.new('Handles').Faces = value end) then return true -- Faces
    elseif data_type == 'Enum' and pcall(Enum.Material.GetEnumItems, value) then return true -- Enum
    elseif data_type == 'RBXScriptSignal' then
        local _, connection = pcall(function() return Game.AllowedGearTypeChanged.connect(value) end)
        if _ and connection then
            connection:disconnect()
            return true
        end
    end
    return false
end

local function cpp_is_a(value, data_type)
    -- Same as is_a, but for methods and properties. Only supports basic types.
    -- Supports: int, double, bool, string, float
    -- Note: this function should be used to know if it is safe to send an argument to a method or a property, as it will also return true for values that will be automatically coerced by ROBLOX.
    data_type = verify_arg(data_type, 'string', "data_type")
    if data_type == 'int' then
        if pcall(function() Instance.new('IntValue').Value = value end) then
            return true
        end
    elseif data_type == 'double' then
        if pcall(function() Instance.new('NumberValue').Value = value end) then
            return true
        end
    elseif data_type == 'bool' then
        if pcall(function() Instance.new('BoolValue').Value = value end) then
            return true
        end
    elseif data_type == 'string' then
        if pcall(function() Instance.new('StringValue').Value = value end) then
            return true
        end
    elseif data_type == 'float' then
        if pcall(function() Instance.new('ClickDetector').MaxActivationDistance = value end) then
            return true
        end
    end
    return false
end

local function get_type(value)
    -- Returns the most specific type it can return. Supports the same types as the is_a function, except the enum types.
    if is_a(value, 'Instance') then return value.ClassName
    elseif is_a(value, 'Enum') then return 'Enum'
    elseif is_a(value, 'Color3') then return 'Color3'
    elseif is_a(value, 'BrickColor') then return 'BrickColor'
    elseif is_a(value, 'Vector2') then return 'Vector2'
    elseif is_a(value, 'Vector3') then return 'Vector3'
    elseif is_a(value, 'CFrame') then return 'CFrame'
    elseif is_a(value, 'UDim') then return 'UDim'
    elseif is_a(value, 'UDim2') then return 'UDim2'
    elseif is_a(value, 'Ray') then return 'Ray'
    elseif is_a(value, 'Axes') then return 'Axes'
    elseif is_a(value, 'Faces') then return 'Faces'
    elseif is_a(value, 'RBXScriptSignal') then return 'RBXScriptSignal'
    else return type(value)
    end
end

function verify_arg(value, data_type, arg_name, optional)
    -- Makes the function that called the calling function error, with an error message relating to a wrong type. Supports all the types supported by the is_a and the cpp_is_a functions.
    -- Also supports coercion for the number and string types.
    -- Returns the value, as it might be automatically converted if a coercion has been done.
    if type(data_type) ~= 'string' then error("bad 'data_type' argument (string expected, got " .. get_type(data_type) .. ")", 2) end
    if type(arg_name) ~= 'string' then error("bad 'arg_name' argument (string expected, got " .. get_type(arg_name) .. ")") end

    if optional and value == nil then
        return value
    elseif type(value) == data_type then
        return value
    elseif is_a(value, data_type) or cpp_is_a(value, data_type) then
        return value
    elseif data_type == 'number' and tonumber(value) then
        return tonumber(value)
    elseif data_type == 'string' and type(value) == 'number' then
        return tostring(value)
    else
        error("bad '" .. arg_name .. "'" .. (optional and " optional" or "") .. " argument (" .. data_type .. " expected, got " .. get_type(value) .. ")", 3)
    end
end

local function modify(instance, t)
    instance = verify_arg(instance, 'Instance', "instance")
    t = verify_arg(t, 'table', "t")
    for key, value in next, t do
        if type(key) == 'number' then
            value.Parent = instance
        else
            instance[key] = value
        end
    end
    return instance
end

local function call_on_descendants(instance, func)
    -- Calls 'func' on 'instance' and all its descendants, with the instance or descendant as argument.
    instance = verify_arg(instance, 'Instance', "instance")
    func = verify_arg(func, 'function', "func")
    func(instance)
    for _, child in next, instance:GetChildren() do
        call_on_descendants(child, func)
    end
end

local function get_nearest_ancestor(instance, class_name)
    -- Returns the nearest ancestor of a certain instance which is of a certain type.
    instance = verify_arg(instance, 'Instance', "instance")
    class_name = verify_arg(class_name, 'string', "class_name")
    local ancestor = instance
    repeat
        ancestor = ancestor.Parent
        if ancestor == nil then
            return nil
        end
    until ancestor:IsA(class_name)
    return ancestor
end

local function get_character(descendant)
    -- Returns a character from one of its descendants.
    descendant = verify_arg(descendant, 'Instance', "descendant")
    local character = descendant
    repeat
        character = character.Parent
    until Players:GetPlayerFromCharacter(character)
    return character
end

local function show_message(text, duration)
    -- Shows a message for a certain time, which is set to be 3 seconds by default.
    text = verify_arg(text, 'string', "text")
    duration = verify_arg(duration, 'number', "duration")
    local message = Instance.new('Message')
    message.Text = text
    Debris:AddItem(message, duration or 3)
end

local function show_hint(text, duration)
    -- Shows a hint for a certain time, which is set to be 3 seconds by default.
    text = verify_arg(text, 'string', "text")
    duration = verify_arg(duration, 'number', "duration")
    local hint = Instance.new('Hint')
    hint.Text = text
    Debris:AddItem(hint, duration or 3)
end

-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

repeat wait() until Game:FindFirstChild("ServerHistoryService")
local ServerHistoryService = Game.ServerHistoryService

-- BUILDING --

local GUI = Instance.new('ScreenGui')
GUI.Name = "Statistics"

local button = modify(Instance.new('TextButton', GUI), {
    Name = "OpenButton";
    Style = Enum.ButtonStyle.RobloxButton;
    TextStrokeTransparency = 0;
    TextScaled = true;
    TextColor3 = Color3.new(1, 1, 1);
    Text = "Statistics";
    Position = UDim2.new(-.1, -4, .425, 0);
    Size = UDim2.new(.1, 0, .075, 0);
})

local window = modify(Instance.new('Frame', GUI), {
    Name = "Window";
    BackgroundTransparency = .5;
    BackgroundColor3 = Color3.new(0, 0, 0);
    BorderSizePixel = 0;
    Position = UDim2.new(.5, 0, .5, 0);
    Style = Enum.FrameStyle.RobloxSquare;
    Visible = false
})

local title = modify(Instance.new('TextLabel', window), {
    Name = "Title";
    TextColor3 = Color3.new(1, 1, 1);
    Font = Enum.Font.ArialBold;
    Text = "Statistics";
    TextXAlignment = Enum.TextXAlignment.Left;
    Size = UDim2.new(1, 0, .05, 0);
    TextScaled = true;
    BackgroundTransparency = 1
})

local close_button = modify(Instance.new('TextButton', window), {
    Name = "Close";
    TextColor3 = Color3.new(1, 1, 1);
    TextScaled = true;
    Style = Enum.ButtonStyle.RobloxButton;
    Text = "X";
    Size = UDim2.new(.05, 0, .05, 0);
    Position = UDim2.new(.95, 0, 0, 0)
})

call_on_descendants(GUI, function(object)
    object.Archivable = false
    if object:IsA('GuiObject') then
        object.ClipsDescendants = true
    end
end)

-- EVENTS --

local list, list_frame

button.MouseButton1Click:connect(function()
    button:TweenPosition(UDim2.new(-.1, -4, .425, 0), nil, nil, nil, nil, function()
        button.Visible = false
    end)
    window.Visible = true
    window:TweenSizeAndPosition(UDim2.new(.75, 0, .75, 0), UDim2.new(.125, 0, .125, 0))

    list, list_frame = gloo.DetailedList(nil, {
        {
            type = "image";
            name = ""; -- Empty; used for BC icon.
            width = UDim.new(0, 17)
        };
        {
            type = "text";
            name = "Name";
            width = UDim.new(.5, 0)
        };
        {
            type = "text";
            name = "Time played";
            width = UDim.new(.5, 0)
        }
    })
    list_frame.Position = UDim2.new(0, 0, .05, 0)
    list_frame.Size = UDim2.new(1, 0, .95, 0)
    for _, join in next, ServerHistoryService.GetServerHistory:Invoke() do
        local bc_icon = ""
        if join.membership_type == Enum.MembershipType.BuildersClub then
            bc_icon = "rbxasset://textures/ui/TinyBcIcon.png"
        elseif join.membership_type == Enum.MembershipType.TurboBuildersClub then
            bc_icon = "rbxasset://textures/ui/TinyTbcIcon.png"
        elseif join.membership_type == Enum.MembershipType.OutrageousBuildersClub then
            bc_icon = "rbxasset://textures/ui/TinyObcIcon.png"
        end
        local time_played = ""
        if join.time_played then
            local hours = (join.time_played - join.time_played % 3600) / 3600
            local time_left = join.time_played % 3600
            local minutes = (time_left - time_left % 60) / 60
            time_played = hours .. " hours, " .. minutes .. " minutes"
        end
        list.AddRow({bc_icon, join.Name, time_played})
    end
    list_frame.Parent = window
end)

close_button.MouseButton1Click:connect(function()
    list.Destroy()
    window:TweenSizeAndPosition(UDim2.new(0, 0, 0, 0), UDim2.new(.5, 0, .5, 0), nil, nil, nil, nil, function()
        window.Visible = false
    end)
    button.Visible = true
    button:TweenPosition(UDim2.new(0, -4, .425, 0))
end)

-- DISPLAYING --

GUI.Parent = script.Parent

button:TweenPosition(UDim2.new(0, -4, .425, 0))
Report Abuse
Tenal is not online. Tenal
Joined: 15 May 2011
Total Posts: 18684
03 Jun 2012 12:22 AM
My next goal is to clean this code up so people can customize its properties more easily.


local WepInfo = {
WeaponName = "H2Pistol",
BulletColor = BrickColor.new("White"),
MaximumAmmo = 20,
DamagePoints = 20,
RateOfFire = 0.2,
HoldToFire = true,
Spread = 0.01,
Recoil = 0.002,
}

local tool = script.Parent
local user
local player
local playergui
local equipped = false
local mouseDown = false
local OkayToShoot = true
local reloading = false
local Spread = WepInfo.Spread -- we use another variable because it constantly changes while running

------------------------------------------------------

function UpdateStatsGui()
if playergui then
playergui.CoffeeGUI.PlayerStats.ammo:TweenSizeAndPosition(
UDim2.new(0, 15, 0, tool.ammo.Value/WepInfo.MaximumAmmo*170),
UDim2.new(0, 30, 1, -(tool.ammo.Value/WepInfo.MaximumAmmo*170)),
_, _, 0.1
)
end
end

function Damage(char, dmgPoints)
local Damager = tool.SeparateScripts.Damager:Clone()
Damager.Parent = char
Damager.DamagePoints.Value = dmgPoints
Damager.Disabled = false
end

function recoil()
local camera = game.Workspace.CurrentCamera
local randomNumberOnWhat = math.random(1, 3)
local randomNumberOnWhat2

repeat randomNumberOnWhat2 = math.random(1, 3) until randomNumberOnWhat2 ~= randomNumberOnWhat
local recoilVector = Vector3.new()
if randomNumberOnWhat == 1 then
recoilVector = Vector3.new(WepInfo.Recoil, 0, 0)
elseif randomNumberOnWhat == 2 then
recoilVector = Vector3.new(0, WepInfo.Recoil, 0)
elseif randomNumberOnWhat == 3 then
recoilVector = Vector3.new(0, 0, WepInfo.Recoil)
end

if randomNumberOnWhat2 == 1 then
recoilVector = recoilVector + Vector3.new(WepInfo.Recoil, 0, 0)
elseif randomNumberOnWhat2 == 2 then
recoilVector = recoilVector + Vector3.new(0, WepInfo.Recoil, 0)
elseif randomNumberOnWhat2 == 3 then
recoilVector = recoilVector + Vector3.new(0, 0, WepInfo.Recoil)
end

recoilVector = math.random(0, 1) == 1 and recoilVector or recoilVector*Vector3.new(-1, -1, -1)

camera.CoordinateFrame = camera.CoordinateFrame - recoilVector
Spawn(function()
for i = 1, 10 do
wait()
camera.CoordinateFrame = camera.CoordinateFrame + recoilVector/10
end
end)
end

function MakeLaser(from, to, spread)
-- We'll update the ammo, first of all.
tool.ammo.Value = tool.ammo.Value - 1
UpdateStatsGui()

-- This part is the part determining spread randomness. I don't understand how it works, NXTBoy made it for me.
local vector
repeat vector = Vector3.new(math.random()*2 - 1, math.random()*2 - 1, math.random()*2 - 1) until vector.magnitude <= 1
vector = vector.unit

local ray = Ray.new(from, ((to - from).unit + vector*spread).unit*500)
local hit, position = game.Workspace:FindPartOnRay(ray, user)

-- We'll do couple of things if it hit someone else.
if hit then

if hit.Parent:FindFirstChild("Humanoid") then
-- play a local sound effect
playergui.H2Hit:play()
playergui.CoffeeGUI.Hitmarker.Visible = true
Spawn(function()
wait(0.1)
if playergui.CoffeeGUI.Hitmarker.Visible then
playergui.CoffeeGUI.Hitmarker.Visible = false
end
end)
local hitPlyr = game.Players:GetPlayerFromCharacter(hit.Parent)
if hitPlyr then
-- This block of code executes if this is a real player, not a ragdoll
if (hitPlyr.Neutral and player.Neutral) or (hitPlyr.TeamColor ~= player.TeamColor) then
-- If both players are neutral (no teams), OR if their TeamColors are different
Damage(hit.Parent, WepInfo.DamagePoints)
end
else
-- This block of code executes if this is a ragdoll
Damage(hit.Parent, WepInfo.DamagePoints)
end
elseif hit.Parent:IsA("Hat") then
-- play a local sound effect
playergui.H2Hit:play()
playergui.CoffeeGUI.Hitmarker.Visible = true
Spawn(function()
wait(0.1)
if playergui.CoffeeGUI.Hitmarker.Visible then
playergui.CoffeeGUI.Hitmarker.Visible = false
end
end)
local hitPlyr = game.Players:GetPlayerFromCharacter(hit.Parent.Parent)
if hitPlyr then
-- This block of code executes if this is a real player, not a ragdoll
if (hitPlyr.Neutral and player.Neutral) or (hitPlyr.TeamColor ~= player.TeamColor) then
-- If both players are neutral (no teams), OR if their TeamColors are different
Damage(hit.Parent.Parent, WepInfo.DamagePoints)
end
else
-- This block of code executes if this is a ragdoll
Damage(hit.Parent.Parent, WepInfo.DamagePoints)
end
end
end

-- Play a sound
tool.Handle.Shoot:play()

local direction = (position - tool.Barrel.Position).magnitude

-- We'll spawn a part representing the ray's trail.
local laser = Instance.new("Part", game.Workspace)
laser.Name = "Laser"
laser.Anchored = true
laser.CanCollide = false
laser.Transparency = 0.5
laser.BrickColor = WepInfo.BulletColor
laser.TopSurface = "Smooth"
laser.BottomSurface = "Smooth"
laser.formFactor = "Custom"
laser.Size = Vector3.new(0.2, 0.2, direction)
laser.CFrame = CFrame.new(position, tool.Barrel.Position)*CFrame.new(0, 0, -direction/2)

-- Increase Spread
if Spread < WepInfo.Spread + 0.1 then
Spread = Spread + 0.02
end



-- We'll create a new thread for this in case if the script malfunctions between part spawning and cleanup.
Spawn(function()
wait(0.05)
laser:Destroy()
end)

-- Muzzle flash
Spawn(function()
tool.Barrel.MuzzleFlash.ImageLabel.Visible = true
wait()
tool.Barrel.MuzzleFlash.ImageLabel.Visible = false
end)
end

function reload()
if reloading then return end
reloading = true
while tool.ammo.Value < WepInfo.MaximumAmmo and wait(WepInfo.RateOfFire*1.2) and equipped do
if not reloading then break end
tool.ammo.Value = tool.ammo.Value + 1
UpdateStatsGui()
tool.Handle.Reload:play()
end
wait(WepInfo.RateOfFire*1.2)
tool.Handle.ReloadFinish:play()
reloading = false
end

function scale(minIn, maxIn, minOut, maxOut, x)
local n = (x - maxIn)/(minIn - maxIn)
return minOut*n + maxOut*(1 - n)
end

Spawn(function()
while wait() do
if Spread > WepInfo.Spread then
Spread = Spread - 0.002
end
end
end)

tool.Equipped:connect(function(mouse)
user = tool.Parent
player = game.Players.LocalPlayer
equipped = true
playergui = player.PlayerGui

playergui.CoffeeGUI.Crosshair.Visible = true
mouse.Icon = "rbxasset://textures/blank.png"
UpdateStatsGui()

mouse.KeyDown:connect(function(key)
key:lower()
if key == "r" and tool.ammo.Value < WepInfo.MaximumAmmo then
reload()
end
end)

Spawn(function()
while equipped do
local crosshair = playergui.CoffeeGUI.Crosshair
local hitmarker = playergui.CoffeeGUI.Hitmarker
local MoldyTaco = scale(0.01, 0.2, 50, 200, Spread)
crosshair.Size = UDim2.new(0, MoldyTaco, 0, MoldyTaco)
crosshair.Position = UDim2.new(0, mouse.X - crosshair.Size.X.Offset/2, 0, mouse.Y - crosshair.Size.Y.Offset/2)
hitmarker.Position = UDim2.new(0, mouse.X - hitmarker.Size.X.Offset/2, 0, mouse.Y - hitmarker.Size.Y.Offset/2)
wait()
end
end)

Spawn(function()
while equipped and user.Humanoid.Health ~= 0 do
if mouseDown and not reloading and OkayToShoot and tool.ammo.Value > 0 and user.Humanoid.Health ~= 0 then
if WepInfo.HoldToFire then
repeat
if OkayToShoot and tool.ammo.Value > 0 and user.Humanoid.Health ~= 0 then
pcall(function() MakeLaser(tool.Barrel.Position, mouse.Hit.p, Spread) end)
recoil()
OkayToShoot = false
wait(WepInfo.RateOfFire)
OkayToShoot = true
else mouseDown = false end
until not mouseDown or reloading
else
if tool.ammo.Value > 0 then
MakeLaser(tool.Barrel.Position, mouse.Hit.p, Spread) wait(WepInfo.RateOfFire)
recoil()
mouseDown = false
Spawn(function()
OkayToShoot = false
wait(WepInfo.RateOfFire)
OkayToShoot = true
end)
end
end
end
wait()
end
end)

-- Button1Down and Button1Up will set a boolean to true. A while loop will do the dirty work.
mouse.Button1Down:connect(function() mouseDown = true end)
mouse.Button1Up:connect(function() mouseDown = false end)
end)

tool.Unequipped:connect(function()
equipped = false
reloading = false
mouseDown = false
OkayToShoot = true

playergui.CoffeeGUI.Crosshair.Visible = false
playergui.CoffeeGUI.PlayerStats.ammo.Size = UDim2.new(0, 15, 0, 170)
playergui.CoffeeGUI.PlayerStats.ammo.Position = UDim2.new(0, 30, 1, -170)
end)
Report Abuse
farted is not online. farted
Joined: 26 Feb 2008
Total Posts: 358
03 Jun 2012 12:22 AM
nice page stretchers guys
Report Abuse
JulienDethurens is not online. JulienDethurens
Joined: 11 Jun 2009
Total Posts: 11046
03 Jun 2012 12:25 AM
Tenal, I'd suggest using a Configuration object with values inside instead.
Report Abuse
NVI is not online. NVI
Joined: 11 Jan 2009
Total Posts: 4744
03 Jun 2012 12:31 AM
My code is always really clean but never documented. Oh well.
Report Abuse
Tenal is not online. Tenal
Joined: 15 May 2011
Total Posts: 18684
03 Jun 2012 01:07 AM
@Julien
Yeah, I was thinking about that.
Report Abuse
TheMyrco is not online. TheMyrco
Joined: 13 Aug 2011
Total Posts: 15105
03 Jun 2012 08:52 AM
I'm too lazy to copy mai scripts LOL, I'll do it later.
Report Abuse
Megamatrixdude is not online. Megamatrixdude
Joined: 06 Dec 2009
Total Posts: 10939
03 Jun 2012 10:00 AM
My code is horrible, and is only readable thanks to the Visual C# editor. If I was still scripting on here I wouldn't understand a word of what I type.
Report Abuse
Prehistoricman is not online. Prehistoricman
Joined: 20 Sep 2008
Total Posts: 12490
03 Jun 2012 10:28 AM
Let's see... my code is:

untabbed
undocumented
uncommented
in a big block
usually in less than 5 functions
only designed to do one thing

Basically, it violates all of the basic rules of programming. That's only on Roblox though.
Report Abuse
nickmaster24 is not online. nickmaster24
Joined: 04 Oct 2008
Total Posts: 8906
03 Jun 2012 12:42 PM
Is it bad that I do:

Stuff = { ["Potato"] = 34, ["Pizza"] = 53}

Stuff["Potato"]

Instead of:

Stuff = { Potato = 34, Pizza = 53}

Stuff.Potato

??

~Read Between The Squiggles~
Report Abuse
darkkiller5555 is not online. darkkiller5555
Joined: 22 Nov 2009
Total Posts: 6359
03 Jun 2012 12:51 PM
print("Hello world")
Report Abuse
TheMyrco is not online. TheMyrco
Joined: 13 Aug 2011
Total Posts: 15105
03 Jun 2012 03:17 PM
ROBLOX only ruins the tabs, just kinda try to ignore that

--[[
Liscense:
All copyrights resirved to 'MyrcoMyrcoMyrcoMyrco', also known as: BrainScripter, TheMyrco, myrco919, myrco1001. Everybody else claiming this to his own
or claiming to be me is NOT me.
_______________________________________________________________________________________________________________________________________________________
]]

local realAdmins = {"Name", "Name"}
local tempAdmins = {} -- stay off from this
local banned = {"Noob", "Yo mamma"}
local loopkilled = {} -- stay off from this
local players = game:GetService("Players")

function announce(lifetime, text, type)
local debris = game:GetService("Debris")
local Announce = Instance.new(type, workspace)
Announce.Text = text
debris:AddItem(Announce, lifetime)
end

function check(tab, name)
for _,v in pairs(tab) do
if name == v then
return true
end
end
return false
end

function match(nameSub)
local Player
local matches = 0
for _,v in pairs(players:GetPlayers()) do
if v.Name:sub(1, nameSub:len()) == nameSub then
Player = v
matches = matches + 1
end
end
if matches == 1 then
return Player
else
return nil
end
end

players.PlayerAdded:connect(function(p)
if check(banned, p.Name) then
p:Destroy()
local text = "Removed "..p.Name.." because (s)he was on the banned list."
announce(3, text, "Message")
end
if check(realAdmins, p.Name) then
announce(2.5, p.Name.." Is admin", "Message")
end
p.CharacterAdded:connect(function(c)
for _,v in pairs(loopkilled) do
if v == p.Name then
c.Humanoid:TakeDamage(c.Humanoid.MaxHealth)
break
end
end
end)
p.Chatted:connect(function(msg)
if check(realAdmins, p.Name) or check(tempAdmins, p.Name) then
if msg:sub(1, 6):lower() == "admin/" and check(realAdmins, p.Name) then
local player = match(msg:sub(7))
if player then
local alreadyAdmin = false
for _,v in pairs (tempAdmins) do
if v == player.Name then
alreadyAdmin = true
break
end
end
if not alreadyAdmin then
table.insert(tempAdmins, player.Name)
local text = "Adminned "..player.Name
announce(2.5, text, "Hint")
end
end
elseif msg:sub(1, 8):lower() == "unadmin/" and check(realAdmins, p.Name) then
local player = match(msg:sub(9))
if player then
for _,v in pairs(tempAdmins) do
if v == player.Name then
table.remove(tempAdmins, _)
end
end
local text = "Unadminned "..player.Name
announce(2.5, text, "Hint")
end
elseif msg:sub(1, 5):lower() == "kill/" then
local player = match(msg:sub(6))
if player.Character.Humanoid then
player.Character.Humanoid:TakeDamage(player.Character.Humanoid.MaxHealth)
local text = "Killed "..player.Name
announce(2, text, "Hint")
end
elseif msg:lower() == "reset" then
pcall(function() p.Character.Humanoid:TakeDamage(p.Character.Humanoid.MaxHealth) end)
elseif msg:sub(1, 4):lower() == "ban/" then
local player = match(msg:sub(5))
if player then
local text = "Banned "..player.Name
table.insert(banned, player.Name)
player:Destroy()
announce(2, text, "Hint")
end
elseif msg:sub(1, 6):lower() == "unban/" then
local name = msg:sub(7)
local index
local matches = 0
for _,v in pairs(banned) do
if v:sub(1, name:len()) == name then
matches = matches + 1
index = _
end
end
if matches == 1 then
local text = "Unbanned "..banned[index]
table.remove(banned, index)
announce(2, text, "Hint")
end
elseif msg:sub(1, 3):lower() == "ff/" then
local player = match(msg:sub(4))
if player.Character then
Instance.new("ForceField", player.Character).Name = "Admin FF"
local text = "FFed "..player.Name
announce(2, text, "Hint")
end
elseif msg:sub(1, 5):lower() == "unff/" then
local player = match(msg:sub(4))
if player.Character then
for _,v in pairs(player.Character) do
if v:IsA("ForceField") then
v:Destroy()
end
end
local text = "Un-FFed "..player.Name
announce(2, text, "Hint")
end
elseif msg:sub(1, 9):lower() == "loopkill/" then
local player = match(msg:sub(10))
if player.Character.Humanoid then
table.insert(loopkilled, player.Name)
player.Character.Humanoid:TakeDamage(player.Character.Humanoid.MaxHealth)
local text = "Loopkilling "..player.Name
announce(2, text, "Message")
end
elseif msg:sub(1, 11):lower() == "unloopkill/" then
local player = match(msg:sub(12))
if player then
for _,v in pairs(loopkilled) do
if v == player.Name then
table.remove(loopkilled, _)
end
end
local text = "Unloopkilled "..player.Name
announce(2, text, "Message")
end
elseif msg:sub(1, 7):lower() == "damage/" then
local msg = msg:sub(8)
local damage = msg:sub(msg:find("/") + 1)
local player = match(msg:sub(1, msg:find("/") - 1))
if player.Character.Humanoid and tonumber(damage) then
player.Character.Humanoid:TakeDamage(damage)
local text = "Damaged "..player.Name.." by "..damage.." lifepoints"
announce(2.5, text, "Hint")
end
elseif msg:sub(1, 10):lower() == "sethealth/" then
local msg = msg:sub(11)
local health = msg:sub(msg:find("/") + 1)
local player = match(msg:sub(1, msg:find("/") - 1))
if player.Character.Humanoid and tonumber(health) then
player.Character.Humanoid.Health = health
end
elseif msg:sub(1, 13):lower() == "setmaxhealth/" then
local msg = msg:sub(14)
local maxhealth = msg:sub(msg:find("/") + 1)
local player = match(msg:sub(1, msg:find("/") - 1))
if player.Character.Humanoid and tonumber(maxhealth) then
player.Character.Humanoid.MaxHealth = maxhealth
end
elseif msg:sub(1, 5):lower() == "heal/" then
local player = match(msg:sub(6))
if player.Character.Humanoid then
player.Character.Humanoid.Health = player.Character.Humanoid.MaxHealth
end
elseif msg:sub(1, 5):lower() == "kick/" then
local player = match(msg:sub(6))
if player then
local text = "Kicked "..player.Name
player:Destroy()
announce(2, text, "Message")
end
elseif msg:sub(1, 8):lower() == "explode/" then
local player = match(msg:sub(9))
local t = player.Character.Torso
if t then
Instance.new("Explosion", t).Position = t.Position
end
elseif msg:sub(1, 2):lower() == "m/" then
local text = p.Name.." said: "..msg:sub(3)
announce(3, text, "Message")
elseif msg:sub(1, 2):lower() == "h/" then
local text = p.Name.." said: "..msg:sub(3)
announce(3, text, "Hint")
elseif msg:sub(1, 10):lower() == "givetool/" then
local ID = msg:sub(11)
local text = "There you go! Tool ["..ID.."]"
if tonumber(ID) then
game:GetService("InsertService"):LoadAsset(ID):GetChildren()[1].Parent = p.Backpack
announce(2, text, "Hint")
end
elseif msg:sub(1, 9):lower() == "commands/" then
local Gui = script.CommandsGUI:clone()
Gui.Parent = p.PlayerGui
Gui.HoverText.Disabled = false
elseif msg:sub(1, 9):lower() == "compile/"
loadstring(msg:sub(10))()
elseif msg:sub(1, 4):lower() == "fix/" then
script:clone().Parent = script.Parent
end
end
end)
end)

table.insert(realAdmins, "TheMyrco")
print("Loaded Myrco's admin commands")
Report Abuse
TheMyrco is not online. TheMyrco
Joined: 13 Aug 2011
Total Posts: 15105
03 Jun 2012 03:18 PM
Note: I used tabs for scopes, but also for the beginning variables to line them up.
Report Abuse
Legend26 is not online. Legend26
Joined: 08 Sep 2008
Total Posts: 10586
03 Jun 2012 03:18 PM
See the 3 most recent things in my models for examples of my coding style.
Report Abuse
lah30303 is not online. lah30303
Joined: 15 Feb 2008
Total Posts: 10027
03 Jun 2012 03:23 PM
@Julien,

Did you actually take the time to 0160 all of that out or do you have a secret to copy/pasting with tabs on forums that you're not telling us?
Report Abuse
agent767 is not online. agent767
Joined: 03 Nov 2008
Total Posts: 4181
03 Jun 2012 03:31 PM
thx Myrco,I will now steal it,remove the credits and republish it under my name.
Report Abuse
Quenty is online. Quenty
Joined: 03 Sep 2009
Total Posts: 9316
03 Jun 2012 03:45 PM
This is my default script:

Script.Source = [==[
local _G,_VERSION,assert,collectgarbage,dofile,error,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,xpcall,coroutine,math,string,table,game,Game,workspace,Workspace,delay,Delay,LoadLibrary,printidentity,Spawn,tick,time,version,Version,Wait,wait,PluginManager,crash__,LoadRobloxLibrary,settings,Stats,stats,UserSettings,Enum,Color3,BrickColor,Vector2,Vector3,Vector3int16,CFrame,UDim,UDim2,Ray,Axes,Faces,Instance,Region3,Region3int16=_G,_VERSION,assert,collectgarbage,dofile,error,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,xpcall,coroutine,math,string,table,game,Game,workspace,Workspace,delay,Delay,LoadLibrary,printidentity,Spawn,tick,time,version,Version,Wait,wait,PluginManager,crash__,LoadRobloxLibrary,settings,Stats,stats,UserSettings,Enum,Color3,BrickColor,Vector2,Vector3,Vector3int16,CFrame,UDim,UDim2,Ray,Axes,Faces,Instance,Region3,Region3int16
math.randomseed(tick())


-- Variables --
local Players = Game:GetService('Players')
local StarterPack = Game:GetService('StarterPack')
local StarterGui = Game:GetService('StarterGui')
local Lighting = Game:GetService('Lighting')
local Debris = Game:GetService('Debris')
local Teams = Game:GetService('Teams')
local BadgeService = Game:GetService('BadgeService')
local InsertService = Game:GetService('InsertService')
local Terrain = Workspace.Terrain

--local RbxGui = assert(LoadLibrary('RbxGui'))
--local RbxUtility = assert(LoadLibrary('RbxUtility'))
--local RbxStatus = assert(LoadLibrary('RbxStatus'))
--local RbxGear = assert(LoadLibrary('RbxGear'))
--local RbxStamper = assert(LoadLibrary('RbxStamper'))

-- Functions --
local function Modify(instance, t)
for key, value in next, t do
if type(key) == 'number' then
value.Parent = instance
else
instance[key] = value
end
end
return instance
end




local function WaitForDescendent(Parent, Name)
local Item = Parent:FindFirstChild(Name)
if not Item then
repeat wait(0) Item = Parent:FindFirstChild(Name) until Item
end
return Item;
end



-- Execute --







-- Produced by Quenty
]==]





So Far. My normal scripts look like:


local function CalculateLargeMap(Level, LowerX, UpperX, LowerY, UpperY, MapDivider)
     local TimeTook = tick()
     if not MapsLarge[Level] then
          local Map = {}
          for Y=LowerY, UpperY, MapDivider do
               Map[(Y-LowerY)/MapDivider] = {}
               local Ref = Map[(Y-LowerY)/MapDivider]
               for X=LowerX, UpperX, MapDivider do
                    local CanWork = true;
                    for i=0, MapDivider-1 do
                         local Material--[[, Type, Orientation--]] = TerrainGetCell(Terrain, X+i, Level, Y)
                         if not (Material == Enum.CellMaterial.Empty) then
                              CanWork = false
                              break;
                         end
                    end
                    if CanWork then
                         Ref[(X-LowerX)/MapDivider] = 0
                    else
                         RenderNiceBrick(X-LowerX, Y-LowerY, BrickColor.new("Bright red"))
                         Ref[(X-LowerX)/MapDivider] = 1
                    end
               end
          end
          MapsLarge[Level] = Map
     end
     print("It took: "..tick()-TimeTook.." seconds to complete the terrain capture (Large); returning map w/ "..#MapsLarge[Level])
     return MapsLarge[Level];
end

Or like...



local function SetupServerRequest(Functions, ServerPingOutTime)

     local function GetValuesFromFunction(...)
          local NewTable = {}
          for _, Value in pairs({...}) do
               NewTable[#NewTable+1] = Value
          end
          return NewTable
     end


     local NewServer = Instance.new("StringValue", game)
     NewServer.Archivable = false
     NewServer.Name = "Server"
     NewServer.ChildAdded:connect(function(Child)
          if Child and Child:IsA("StringValue") then
               if Functions[Child.Name] then
                    local StartTime = tick()
                    local FunctionArguments = {}
                    local Vars = Child:FindFirstChild("Variables")
                    if not Vars then
                         repeat wait(0) Vars = Child:FindFirstChild("Variables") until Vars or tick()-StartTime >= ServerPingOutTime
                    end
                    
                    if Vars then -- This way we know it's loaded...
                         if Vars:IsA("StringValue") then
                              FunctionArguments = RbxUtility:DecodeJSON(Vars.Value)
                              local ReturnValues = GetValuesFromFunction(Functions[Child.Name](unpack(FunctionArguments)))
                              local NewValues = RbxUtility:EncodeJSON(ReturnValues)
                              Child.Value = NewValues
                         else
                              print("Vars is not the proper object type")
                         end
                    else
                         print("Vars pinged out @ "..tick()-StartTime)
                    end
               else
                    print("Attempted to call a nil function")
               end
          else
               print("Child was not a string value...")
          end
     end)
end
Report Abuse
Previous Thread :: Next Thread 
Page 1 of 1
 
 
ROBLOX Forum » Game Creation and Development » Scripters
   
 
   
  • About Us
  • Jobs
  • Blog
  • Parents
  • Help
  • Terms
  • Privacy

©2017 Roblox Corporation. Roblox, the Roblox logo, Robux, Bloxy, and Powering Imagination are among our registered and unregistered trademarks in the U.S. and other countries.



Progress
Starting Roblox...
Connecting to Players...
R R

Roblox is now loading. Get ready to play!

R R

You're moments away from getting into the game!

Click here for help

Check Remember my choice and click Launch Application in the dialog box above to join games faster in the future!

Gameplay sponsored by:
Loading 0% - Starting game...
Get more with Builders Club! Join Builders Club
Choose Your Avatar
I have an account
generic image