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

How would I make a loop for a i,v statement?

Asked by 3 years ago

I'm trying to loop a i,v statement to check workspace if a certain item is there. I have a while true do loop activating when I press a button, but it doesn't work on the new instances being added to the workspace. Here's what I currently have.

        local character = game.Players.LocalPlayer.Character
        local hum = character.HumanoidRootPart
        local work = game.Workspace:GetChildren()
        while valuee == true do -- this code is in a function
            wait(1)
            for i,v in pairs(work) do
                if v.Name == "Test" then
                    v.CFrame = work.Part.CFrame
                end 
            if valuee == false then
                break 
            end  
              end 
        end
0
its because you are checking the same table every loop, you need to create the table inside the loop. Benbebop 1049 — 3y
0
Would the table have to specify the item? Zeta_Dev 34 — 3y
0
"work.Part.CFrame" but work is a table. replace that part with workspace.Part.CFrame greatneil80 2647 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago

Hello,

It appears that you're i, v statement is fine, but you are incorrectly referencing objects from your "work" table.

Instead of writing:

v.CFrame = work.Part.CFrame

write:

v.CFrame = workspace.Part.CFrame

this is because the :GetChildren() function returns a table value, which means that to access its objects, we must use a different method OR simply reference "Part" through the workspace.

To add, your code could be refined in many areas, as annotated below:

local player = game:GetService("Players").LocalPlayer -- more common way to get the local player
workspace:WaitForChild(player.Name) -- wait for character object to be created, often the player's client connects to the server before the server can create their respective character
local character = game.Players.LocalPlayer.Character
local hum = character.HumanoidRootPart
while valuee == true do -- this code is in a function
    wait(1)
    for i,v in pairs(workspace:GetChildren()) do -- this way each loop, the table stays true to the current amount of objects in the workspace. if we define the list before the while true loop, other objects could be added to the workspace without getting searched. This also helps clean the code by removing excess variables
        if v.Name == "Test" then
            v.CFrame = workspace.Part.CFrame --search workspace for part
        end 
    if valuee == false then
        break 
    end  
      end 
end

I hope this answer helped you!

Cheers, Ninjamanchase

Ad

Answer this question