how do i make it so that when a button is pressed, this variable decreases by one? (Roblox studio, .Lua) - lua

what i want to do is when a button is pressed (in Startergui.ExitGUI.ExitBtn) it decreases a variable value (for me it is "seatsOccupied") by 1. I want to also make it so that if seatsOccupied = 0 then it changes the playercount.text and countdown.text to: playercount.text = "0 / 10" and countdown.text = "Waiting for players.." but i know how to do that.
main script:
seatsOccupied = 0
textLabel = game.Workspace.TruckLanes.InvisibleSurfaceGui.BillboardGui.Frame.TextLabel
playercount = game.Workspace.TruckLanes.InvisibleSurfaceGui.BillboardGui.Frame.Countdown
countdown = 15
signtext = game.Workspace.TruckLanes.Lane2.Sign.Top.SurfaceGui.TextLabel
local TeleportService = game:GetService("TeleportService")
truckSeats = script.Parent.Parent.Truck.Seats:GetChildren() -- define truckSeats here
playercount.Text = "Players: 0 / 10"
script.Parent.Touched:Connect(function(hit)
local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
for i, seat in pairs(truckSeats) do -- use the truckSeats variable here
if not seat.Occupant then
seat:Sit(player.Character.Humanoid)
seatsOccupied = seatsOccupied + 1
playercount.Text = "Players: " .. seatsOccupied .. "/" .. #truckSeats
player.Character.Humanoid.JumpPower = 0
game.ReplicatedStorage.ShowExitGUI:FireClient(player)
for i = 15,0 -1 do
game.Workspace.TruckLanes.InvisibleSurfaceGui.BillboardGui.TextLabel.Text = "Leaving in " ..i.." seconds"
end
for i = 15, 0, -1 do
textLabel.Text = "Leaving in " .. i .. " seconds"
signtext.Text = "Leaving in " .. i .. " seconds"
wait(1)
end
-- Move truck
-- Reserve server
local players = {}
for i, v in pairs(game.Workspace.TruckLanes.Lane2.Truck.Seats:GetChildren()) do
if v.Occupant then
print("Occupant found. " .. v.Parent.Name)
table.insert(players, game.Players:GetPlayerFromCharacter(v.Occupant.Parent))
end
end
if #players > 0 then
for i = 0, 150, 1 do -- Change 30 to number of studs
script.Parent.Parent.Truck:TranslateBy(script.Parent.Parent.Truck.Hitbox.CFrame.lookVector)
wait(0.01)
end
for i = 0, 150, 1 do -- Change 30 to number of studs
script.Parent.Parent.Truck:TranslateBy(-script.Parent.Parent.Truck.Hitbox.CFrame.lookVector)
wait(0.01)
end
local serverData = TeleportService:ReserveServer(12433394609)
TeleportService:TeleportToPrivateServer(12433394609, serverData, players)
for i = 0, 150, 1 do -- Change 30 to number of studs
script.Parent.Parent.Truck:TranslateBy(-script.Parent.Parent.Truck.Hitbox.CFrame.lookVector)
wait(0.01)
end
textLabel.Text = "Waiting For Players.."
playercount.Text = "0 / 10"
end
end
end
end
end)
-- WHERE I DO NOT KNOW WHAT TO DO/WHY ITS NOT WORKING
button = game.StarterGui.ExitGUI.ExitBtn.MouseButton1Click
local function onExitButtonClicked()
if seatsOccupied > 0 then
seatsOccupied = seatsOccupied - 1
playercount.Text = "Players: " .. seatsOccupied .. "/" .. #truckSeats
if seatsOccupied == 0 then
textLabel.Text = "Waiting For Players.."
playercount.Text = "0 / " .. #truckSeats
end
end
end
button:Connect(onExitButtonClicked)
Second script (localscript) that tells the button to do stuff
local clicked = game.ReplicatedStorage.LeaveTruck:FireServer()
-- Connect the function to the ShowExitGUI event
game.ReplicatedStorage.ShowExitGUI.OnClientEvent:Connect(function()
script.Parent.ExitBtn.Visible = true
end)
ExitButtonClicked = function()
print("Exit button clicked")
game.ReplicatedStorage.LeaveTruck:FireServer()
script.Parent.ExitBtn.Visible = false
print("its trueeeeeee")
end
-- Connect the function to the ExitBtn's MouseButton1Click event
script.Parent.ExitBtn.MouseButton1Click:Connect(ExitButtonClicked)
Hierarchy: First script: game -> workspace -> trucklanes -> lane2 -> lane2detector -> detectorscript Second script: game -> starterGui -> exitgui -> ClientExit (Aka the script) the button: game -> startergui -> exitgui -> ExitBtn (aka the button)
I tried the above scripts, but they don't work. I was expecting to: contact with the border seat the player countdown from 15 seconds and a player count -- where it doesn't work when the player presses the leave/exitbtn, it decreases the seatsoccupied value by 1, and when the value is 0, it changes the playercount.text and countdown.text to: "0/10" and "Waiting for players.."

Related

My timer script for minecraft is not working

I have a problem with my Minecraft timer script I tried to add a function that saves the time values from worlds in a document. The timer worked completely fine before i added this function...
Code:
name = "Timer"
description = "Just a normal Timer."
positionX = 0
positionY = 0
sizeX = 24
sizeY = 10
scale = 1
START_STOP_KEY = 0x55 --or 'U'
RESET_KEY = 0x4A --or 'J'
--
--[[
if you wish to change the key you can take the key code from here
https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
]] -------------script-code-------------
previoustime = 0
state = 0
startTime = 0
stopTime = 0
ImportedLib = importLib("readfile.lua")
function keyboard(key, isDown)
if (isDown == true) then
if (key == RESET_KEY) then
state = 0
elseif (key == START_STOP_KEY) then
if (state == 0) then
state = 1
startTime = os.time()
elseif (state == 1) then
state = 2
previoustime = os.time()
stopTime = os.time()
elseif (state == 2) then
state = 1
startTime = startTime + os.time() - stopTime
end
end
end
end
TimerText = "00:00"
TextColor = {r = 30, g = 255, b = 30, a = 255}
function doubleDigit(number)
if (number < 10) then
return "0" .. math.floor(number)
else
return math.floor(number)
end
end
function timeText(time)
local result = ""
local days = 0
while (time > 86399) do
days = days + 1
time = time - 86400
end
local hours = 0
while (time > 3599) do
hours = hours + 1
time = time - 86400
end
local minutes = 0
while (time > 59) do
minutes = minutes + 1
time = time - 60
end
if (days == 0) then
if (hours == 0) then
return doubleDigit(minutes) .. ":" .. doubleDigit(time)
else
return math.floor(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
else
return math.floor(days) ..
" : " .. doubleDigit(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time)
end
end
function update()
if (state == 0) then
TextColor = {r = 255, g = 0, b = 0, a = 255}
TimerText = "00:00"
elseif (state == 1) then
TimerText = timeText(os.time() - startTime)
TextColor = {r = 0, g = 255, b = 255, a = 255}
elseif (state == 2) then
TimerText = timeText(stopTime - startTime)
TextColor = {r = 255, g = 255, b = 0, a = 255}
end
end
function render()
local font = gui.font()
local tw = font.width(TimerText)
gfx.color(0, 0, 0, 0)
gfx.rect(0, 0, tw + 4, 10)
gfx.color(TextColor.r, TextColor.g, TextColor.b, TextColor.a)
gfx.text(2, 1, TimerText)
end
This is the function i want to add
if (state == 1) then
local worldName = server.worldName()
io.open(local worldName".txt", "w")
io.output(file)
io.write(time)
io.close(file)
end
if (state == 0) then
local worldName = server.worldName()
io.open(local worldName".txt", "r")
io.output(file)
time = (file:read())
io.close(file)
end
It appears that you want to concatenate (join) two strings io.open(local worldName".txt", "r"). You should use the concat operator (double dot) for that:
local s1 = "Hello "
local s2 = "World!!!"
local s3 = s1..s2
print(s3)
This program will print the string "Hello world!!" (without the quotes).
Also, the you are only supposed to use the local keyword when declaring a variable.
So:
if (state == 1) then
local worldName = server.worldName()
io.open(worldName..".txt", "w")
io.output(file)
io.write(time)
io.close(file)
end
if (state == 0) then
local worldName = server.worldName()
io.open(worldName..".txt", "r")
io.output(file)
time = (file:read())
io.close(file)
end
This code is the correct version of what you wanted to write. I removed the incorrect uses of the local keyword and added the concat operator.

How to get over the 32 bits for storing numbers like - 2,147,483,647 to 2,147,483,647

I try to fix some old Basewars script for Gmod amd there is something i tried to fix but i dont know what i am missing there. Basicly its about a Bank script. This Bank could original store a amount of 2 Billion $. I would like to expand that storage amount to 1 Quadtrillion.
So Basicly the Basewars Gamemode allows players to have an high amount of money up to 10^18 $
= 1 Quintillion. I looked up into https://wiki.garrysmod.com/page/Category:number
so basicly lua uses double-precision floating-point format. So lua uses 32 bits for storing numbers and that means the number can be from a range of
-2,147,483,647 to 2,147,483,647.
The Basewars Gamemode uses a Function to make out of 10^18
= 1 Quintillion
function BaseWars.NumberFormat(num)
local t = BaseWars.LANG.Numbers
for i = 1, #t do
local Div = t[i][1]
local Str = t[i][2]
if num >= Div or num <= -Div then
return string.Comma(math.Round(num / Div, 1)) .. " " .. Str
end
end
return string.Comma(math.Round(num, 1))
end
The Gamemode is using that faction to convert the amount of money.
and here is the BaseWars.LANG.Numbers:
BaseWars.LANG = {}
BaseWars.LANG.__LANGUAGELOOK = {}
BaseWars.LANG.__LANGUAGELOOK.ENGLISH = {
Numbers = {
[5] = {10^6, "Million"},
[4] = {10^9, "Billion"},
[3] = {10^12, "Trillion"},
[2] = {10^15, "Quadtillion"},
[1] = {10^18, "Quintillion"},
},
CURFORMER = CURRENCY .. "%s",
CURRENCY = CURRENCY,
}
So i know that this function does work but i dont get it, how the variable num can be that high!
Why do i know what it does work ?
Here is what i tried and it manipulated the Capacity up to 1 Quadtrillion but at the point i manipluated a other Problem came up and i do not know what i do wrong!
Here how it was Original:
ENT.Capacity = 2000000000 --Max money in the bank. Can be bugs if it is more than 2000000000 (2 bil)
ENT.Money = 0
ENT.MaxPaper = 0
local Clamp = math.Clamp
function ENT:GSAT(slot, name, min, max)
self:NetworkVar("Int", slot, name)
local getVar = function(minMax)
if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end
if self[minMax] and isnumber(self[minMax]) then return self[minMax] end
return minMax or 0
end
self["Add" .. name] = function(_, var)
local Val = self["Get" .. name](self) + var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
self["Take" .. name] = function(_, var)
local Val = self["Get" .. name](self) - var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
end
function ENT:StableNetwork()
self:GSAT(2, "Capacity")
self:GSAT(3, "Money", 0, "GetCapacity")
self:GSAT(4, "Paper", 0, "MaxPaper")
self:GSAT(5, "Level", 0, "MaxLevel")
end
function ENT:ThinkFunc() --This Funtion is to auto collect all the Money of Printers
for k, v in pairs( ents.FindByClass( "bw_printer_*" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < self.Capacity then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
for k, v in pairs( ents.FindByClass( "bw_base_moneyprinter" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < self.Capacity then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
end
if CLIENT then
local Cp = self:GetCapacity()
local money = tonumber(self:GetMoney()) or 0
local cap = tonumber(Cp) or 0
local moneyPercentage = math.Round( money / cap * 100 ,1)
draw.DrawText( moneyPercentage .."%" , fontName .. ".Huge", w - 4-430, 71+610, self.FontColor, TEXT_ALIGN_CENTER)
local currentMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(money)
local maxMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap)
local font = fontName .. ".Big"
if #currentMoney > 16 then
font = fontName .. ".MedBig"
end
if #currentMoney > 20 then
font = fontName .. ".Med"
end
local fh = draw.GetFontHeight(font)
local StrW,StrH = surface.GetTextSize("")
local moneyW,moneyH = surface.GetTextSize(currentMoney)
draw.DrawText(currentMoney.. " / " .. BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap) , font,
w/2 - StrW/2-225 , (font == fontName .. ".Big" and 106 or 105 + fh / 4)+675, self.FontColor, TEXT_ALIGN_CENTER)
end
Here the changes i did:
removed line:
local cap = tonumber(Cp) or 0
added
local cap = 10^15
if self:GetMoney() < cap then
ENT.Capacity = 2000000000 --Max money in the bank. Can be bugs if it is more than 2000000000 (2 bil)
local cap = 10^15
ENT.Money = 0
ENT.MaxPaper = 0
local Clamp = math.Clamp
function ENT:GSAT(slot, name, min, max)
self:NetworkVar("Int", slot, name)
local getVar = function(minMax)
if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end
if self[minMax] and isnumber(self[minMax]) then return self[minMax] end
return minMax or 0
end
self["Add" .. name] = function(_, var)
local Val = self["Get" .. name](self) + var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
self["Take" .. name] = function(_, var)
local Val = self["Get" .. name](self) - var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
end
function ENT:StableNetwork()
self:GSAT(2, "Capacity")
self:GSAT(3, "Money", 0, "GetCapacity")
self:GSAT(4, "Paper", 0, "MaxPaper")
self:GSAT(5, "Level", 0, "MaxLevel")
end
function ENT:ThinkFunc() --This Funtion is to auto collect all the Money of Printers
for k, v in pairs( ents.FindByClass( "bw_printer_*" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < cap then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
for k, v in pairs( ents.FindByClass( "bw_base_moneyprinter" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < cap then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
end
if CLIENT then
local Cp = self:GetCapacity()
local money = tonumber(self:GetMoney()) or 0
local moneyPercentage = math.Round( money / cap * 100 ,1)
draw.DrawText( moneyPercentage .."%" , fontName .. ".Huge", w - 4-430, 71+610, self.FontColor, TEXT_ALIGN_CENTER)
local currentMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(money)
local maxMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap)
local font = fontName .. ".Big"
if #currentMoney > 16 then
font = fontName .. ".MedBig"
end
if #currentMoney > 20 then
font = fontName .. ".Med"
end
local fh = draw.GetFontHeight(font)
local StrW,StrH = surface.GetTextSize("")
local moneyW,moneyH = surface.GetTextSize(currentMoney)
draw.DrawText(currentMoney.. " / " .. BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap) , font,
w/2 - StrW/2-225 , (font == fontName .. ".Big" and 106 or 105 + fh / 4)+675, self.FontColor, TEXT_ALIGN_CENTER)
end
So now if you i look into the game it looks like this:
and now i have the problem that when it collects money it does it up to 2 billion and if i try to change
local money = tonumber(self:GetMoney()) or 0
to
local money =self:GetMoney()
i get straight -2.1 Bil
or i tried to change the min max values:
function ENT:GSAT(slot, name, min, max)
self:NetworkVar("Int", slot, name)
local getVar = function(minMax)
if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end
if self[minMax] and isnumber(self[minMax]) then return self[minMax] end
return minMax or 0
end
self["Add" .. name] = function(_, var)
local Val = self["Get" .. name](self) + var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), 10^15)
end
self["Set" .. name](self, Val)
end
self["Take" .. name] = function(_, var)
local Val = self["Get" .. name](self) - var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), 10^15)
end
self["Set" .. name](self, Val)
end
end
Basicly these lines:
Val = Clamp(tonumber(Val) or 0, getVar(min), 10^15)
if i run the game the Bank will just collect the money up to 2 Bill and then it goes to -2.1Bil. And at that point i dont know why and when a value does go buggy like it self sets to -2.1 Bil. does math.Round create this bug or do funktion return only return full integer ?
thx for any help
Because the network variable that the bank uses is an integer, it will only be able to store $(2^31-1) through $-(2^31-1). Try changing it to a networked float:
-- ...
function ENT:GSAT(slot, name, min, max)
-- self:NetworkVar("Int", slot, name), changes into:
self:NetworkVar("Float", slot, name)
-- ...
But, beware as the more money players accumulate the less precision will be put into those numbers.

Check Winner Naughts and Crosses game - Lua/Corona

I am quite new to the Lua language and am trying to create a simple Tic Tac Toe game. I am having difficulties figuring out how to check the winner. I have tried if-then statements but I think I am using them wrong. Not sure what the best way to check the winner is so any suggestions or assistance is greatly appreciated.
The code is -
local composer = require( "composer" )
local scene = composer.newScene()
d = display
w20 = d.contentWidth * .2
h20 = d.contentHeight * .2
w40 = d.contentWidth * .4
h40 = d.contentHeight * .4
w60 = d.contentWidth * .6
h60 = d.contentHeight * .6
w80 = d.contentWidth * .8
h80 = d.contentHeight * .8
----DRAW LINES FOR BOARD
local lline = d.newLine(w40,h20,w40,h80 )
lline.strokeWidth = 5
local rline = d.newLine(w60,h20,w60,h80 )
rline.strokeWidth = 5
local bline = d.newLine(w20,h40,w80,h40 )
bline.strokeWidth = 5
local tline = d.newLine(w20,h60,w80,h60 )
tline.strokeWidth = 5
--PLACE BOARD COMPARTMENT DIMENSIONS IN TABLE
board ={
{"tl",1,w20,h40,w40,h20,0},
{"tm",2,w40,h40,w60,h20,0},
{"tr",3,w60,h40,w80,h20,0},
{"ml",4,w20,h60,w40,h40,0},
{"mm",5,w40,h60,w60,h40,0},
{"mr",6,w60,h60,w80,h40,0},
{"bl",7,w20,h80,w40,h60,0},
{"bm",8,w40,h80,w60,h60,0},
{"br",9,w60,h80,w80,h60,0}
}
--
local EMPTY, X, O = 0, 1, 2
local whichTurn = 0
--FILL COMPARTMENT W/ COLOUR WHEN TOUCHED
local function fill(event)
if (event.phase == "ended") then
for t = 1,9 do
if event.x > board[t][3] and event.x < board[t][5] then
if event.y < board[t][4] and event.y > board[t][6] then
if board[t][7] == EMPTY then
if whichTurn == 1 then
whichTurn = 2
else
whichTurn = 1
end
board[t][7] = whichTurn
if board[t][7] == 1 then
local xText = display.newText("X", board[t][3], board[t][4], "Arial", 80)
xText.anchorX = 0
xText.anchorY = 100
elseif board[t][7] == 2 then
local oText = display.newText("O", board[t][3], board[t][4], "Arial", 80)
oText.anchorX = 0
oText.anchorY = 100
end
end
end
end
end
end
local function checkWinner()
for i = 1,9 do
if board[i][2] == 1 and board[i][7] == 1 then
boxOne = "x"
end
if board[i][2] == 2 and board[i][7] == 1 then
boxTwo = "x"
end
if board[i][2] == 3 and board[i][7] == 1 then
boxThree = "x"
end
if boxOne == "x" and boxTwo == "x" and boxThree == "x" then
display.newText("Winner", 10, 100, "Arial", 200)
end
end
end
end
Runtime:addEventListener ("touch", fill)
return scene
local All_Lines = {{1,5,9}, {3,5,7}, {1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8}, {3,6,9}}
local function checkWinner()
for _, Line in ipairs(All_Lines) do
local values = 0
for _, idx in ipairs(Line) do
values = values * 10 + board[idx][7]
end
if values == 111 then
display.newText("Winner", 10, 100, "Arial", 200)
return
elseif values == 222 then
display.newText("Loser", 10, 100, "Arial", 200)
return
end
end
end

If Statement Not Working in RobloxLua

Hello Everyone I am wondering why this code gives me an error
It's supposed to take some cash of all the players and then add 1 to an int value (stage) update its cost and change the speed value (SpawnDelay) so when he clicks on it again it knows what stage he is on but for some reason this does not work as the if statement shows up as incorrect please help:
local stage = script.Parent.stage.Value
local text = script.Parent.Text
script.Parent.MouseButton1Click:connect(function()
if stage == 0 then
for i, v in pairs(game.Players:GetPlayers()) do
v.leaderstats.Cash.Value = v.leaderstats.Cash.Value - 100
workspace.RedTycoon.Factory.SpawnDelay.Value = 15
text = "Upgrade Speed (Cost = 200)"
stage = stage + 1
elseif stage == 1 then
for i, v in pairs(game.Players:GetPlayers()) do
v.leaderstats.Cash.Value = v.leaderstats.Cash.Value - 200
workspace.RedTycoon.Factory.SpawnDelay.Value = 10
text = "Upgrade Speed (Cost = 500)"
stage = stage + 1
end
elseif stage == 2 then
for i, v in pairs(game.Players:GetPlayers()) do
v.leaderstats.Cash.Value = v.leaderstats.Cash.Value - 500
workspace.RedTycoon.Factory.SpawnDelay.Value = 8
text = "Upgrade Speed (Cost = 1000)"
stage = stage + 1
end)
I just tried this
local stage = script.Parent.stage.Value
local text = script.Parent.Text
local delaytime = workspace.RedTycoon.Factory.SpawnDelay.Value
text = "Upgrade Speed (Cost = 100)"
script.Parent.MouseButton1Click:connect(function()
if stage == 0 then
delaytime = 15
text = "Upgrade Speed (Cost = 500)"
stage = stage + 1
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 100
end
end
elseif stage == 1 then
delaytime = 10
text = "Upgrade Speed (Cost = 1000)"
stage = stage + 1
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 500
end
end
elseif stage == 2 then
delaytime = 10
text = "Upgrade Speed (Cost = 1500)"
stage = stage + 1
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 1000
end
end
elseif stage == 3 then
text = "Upgrade Speed (Cost = 2000)"
delaytime = 8
stage = stage + 1
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 1500
end
end
elseif stage == 4 then
delaytime = 4
text = "Upgrade Speed (Cost = 20000)"
stage = stage + 1
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 2000
end
end
elseif stage == 5 then
delaytime = 2
text = "No More Upgrades Avalible"
stage = stage + 1
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 20000
end
end
else
text = "Just for being annoying here you have 1 less cash:"
for _, player in ipairs(game.Players:GetPlayers()) do
if player:FindFirstChild("leaderstats") then
player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 1
end
end
wait(4)
text = "No More Upgrades Avalible"
end
end)
Didn't work
After removing all the excess code statements, we can see that the code structure is, at the very least, missing three end keywords.
script.Parent.MouseButton1Click:connect(function ()
if stage == 0 then
for i, v in pairs(game.Players:GetPlayers()) do
-- missing end
elseif stage == 1 then
for i, v in pairs(game.Players:GetPlayers()) do
end
elseif stage == 2 then
for i, v in pairs(game.Players:GetPlayers()) do
-- missing end
-- missing
end)

while loop wont work inside of the other while loop

I'm scripting in roblox lua and when I try to put a while loop in the first it messes up the first sequence of code can someone give me hand in fixing this?
The problem is that when the humanoid makes it to tar2 he stops there and wont move I want him to continue running to the points but while also having it so where if a actual person comes by then he runs after him instead.
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local plr = game.Players:GetChildren()
local tar1 = game.Workspace.tar1
local tar2 = game.Workspace.tar2
local tar3 = game.Workspace.tar3
local tar4 = game.Workspace.tar4
local pos = {tar1, tar2, tar3, tar4}
local char = script.Parent
local Hum = char.Humanoid
torso = char.Torso
GoTo = 0
while true do
wait(1)
if GoTo == 0 then
Hum:MoveTo(pos[1].Position)
end
if (torso.Position - pos[1].Position).magnitude < 5 then
GoTo = 1
end
if GoTo == 1 then
Hum:MoveTo(pos[2].Position)
end
if (torso.Position - pos[2].Position).magnitude < 5 then
GoTo = 2
end
if GoTo == 2 then
Hum:MoveTo(pos[3].Position)
Goto = 3
end
if (torso.Position - pos[3].Position).magnitude < 5 then
GoTo = 4
end
if GoTo == 5 then
Hum:MoveTo(pos[4].Position)
end
while true do
wait(0.1)
plrs = game.Players:GetChildren()
for i,plr in ipairs(plrs) do
if plr.Character ~= nil then
tor = plr.Character.Torso
if (torso.Position-tor.Position).magnitude <= 5 then
GoTo = 0
Hum:MoveTo(tor.Position)
end
end
end
end
end
Coroutines! Coroutines are the bombdiggety. They let you do multiple while loops at once in a single script.
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local plr = game.Players:GetChildren()
local tar1 = game.Workspace.tar1
local tar2 = game.Workspace.tar2
local tar3 = game.Workspace.tar3
local tar4 = game.Workspace.tar4
local pos = {tar1, tar2, tar3, tar4}
local char = script.Parent
local Hum = char.Humanoid
torso = char.Torso
GoTo = 1
function normalCor() -- run around
while true do
wait(1)
for i=1, 4 do
if GoTo == i then
Hum:MoveTo(pos[i].Position)
end
if (torso.Position - pos[i].Position).magnitude < 5 then
GoTo = GoTo + 1
if GoTo == 5 then
GoTo = 1
end
--[[
The above _can_ be done in a single statement:
"GoTo = (GoTo+1)%4+1"
"a % 4" gets the remainder of a / 4 ]]
end
end
end
end
cr = coroutine.create(normalCor)
coroutine.resume(cr) -- this lets you do two while loops at the same time.
function aggroCor() -- when a player is nearby
while true do
wait(0.1)
plrs = game.Players:GetChildren()
for i,plr in ipairs(plrs) do
if plr.Character ~= nil then
tor = plr.Character.Torso
if (torso.Position-tor.Position).magnitude <= 5 then
GoTo = 0
Hum:MoveTo(tor.Position)
end
end
end
end
end
cr = coroutine.create(aggroCor)
coroutine.resume(cr)
Roblox has the syntax spawn(aggroCor) that you can play around with too,
if coroutine.whatever seems like too much work.

Resources