Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to simplify this code, so if add more blocks I don't have to write it?

Asked by 4 years ago

Blocks are in tables and I was wondering how to simplify this code so that I don't have to write it over and over again:

rs = game.ReplicatedStorage
local block = {
    rs:WaitForChild("StoneBlock"),
    rs:WaitForChild("DimondBlock")
}

local dimondChance = 0.1

local rand = math.random()
if rand < dimondChance then
    local clonedblock = block[2]:Clone()
    clonedblock.Parent = folder --destination folder
    clonedblock:SetPrimaryPartCFrame(CFrame.new(x, y, z))
else 
    local clonedblock = block[1]:Clone()
    clonedblock.Parent = folder --destination folder
    clonedblock:SetPrimaryPartCFrame(CFrame.new(x, y, z))
end

Thanks for the Help!

1 answer

Log in to vote
1
Answered by 4 years ago

When code is repeated like this you can pull the repeated code out into a function and just pass in the parts that change as variables. Something like this:

rs = game.ReplicatedStorage
local block = {
    rs:WaitForChild("StoneBlock"),
    rs:WaitForChild("DimondBlock")
}

local dimondChance = 0.1

local function CreateBlock(blockType)
    local clonedblock = blockType:Clone()
    clonedblock.Parent = folder --destination folder
    clonedblock:SetPrimaryPartCFrame(CFrame.new(x, y, z))
end

local rand = math.random()
if rand < dimondChance then
    CreateBlock(block[2])
else 
    CreateBlock(block[1])
end
0
just an FYI math.random((1/10), (10/10)) Mr_Pure 129 — 4y
0
whats that gonna do? if you put no arguments it generates a pseudo number from 0 to 1 Luka_Gaming07 534 — 4y
Ad

Answer this question