Roblox | how to wait without script stopping? - lua

I'm trying to make a Map selection gui in Roblox with vote counter for each map but if I use wait() to call results function (I mean, function that chooses map with most votes) it also delays server to client votes display, any way to fix this?

One very simple method is to spawn a new thread to do the work in.
print("I should appear first")
spawn(function()
wait(3)
print("I should appear third")
end)
print("I should appear second")

Related

Fixing my color touch script for my roblox puzzle game

So I have a roblox puzzle game that I have been working on for a while now on based on the arcade classic Q bert where the goal is to change all the colours of the bricks while avoiding enemies and getting a high score but I will be adding some features of my own so it does not get as repetitive such as additional tasks like collecting keys on platforms to unlock the door to the next level and secrets like a diamond that rarely appears once every 10 rounds and collecting one gives the player an extra dude and 10 million points.
This is how the game looks so far https://streamable.com/na46cu
The issue I am having as you can see is that the colours do in fact change but when I jump on it again it changes back to the first colour it changes to which in this case is green but I want it to stay on the first colour and make it so that it does not change until the player jumps on the brick again and later on in the game I want it to become more complex and puzzle like as the game goes on like in this example [https://www.youtube.com/watch?v=9eXJWiNXpOo][2] .
I have tried a few things like adding timers ,debounces and even separate scripts alltogether none of which have worked out for me so far and I of course went out looking for a question from somebody else that had a similar problem but so far I have been struggling to find anybody else that has the same problem.
local module = {} --module for the modulescript and for loop is created
local CollectionService = game:GetService("CollectionService")
for _, part,brick in pairs (CollectionService:GetTagged("blocks"))
do
part.Touched:Connect(function(hit) --Part connects with the touched property to the function with the parameter hit
if (hit.Parent:FindFirstChild("Humanoid"))
then
part.BrickColor = BrickColor.new ("Bright green")
wait (2)
part.BrickColor = BrickColor.new ("Eggplant")
-- local sound = workspace.Sound -- use "local sound = workspace.Sound", if there is already a sound object in the workspace
--sound.SoundId = "rbxassetid://4797903038" --replace quoted text with whatever sound id you need to use
--sound:Play()
end
end)
end
-- end)
--end
return module
I am not the best programmer but I do know the basics of programming and I have tried out various programming languages like Python and c++ all of which are not all that hard to understand once you know the basics of it all but finding out the solution to the problem is the really tricky part and so is bug fixing and troubleshooting.
I do know I could try a simple debounce system but that still does not solve the problem and it only makes it so the code only runs once and slows it down.
I have been asking all over the place for a solution to this problem but I never got an answer to it so I am trying on good old Stackoverflow for once to see if this will be the place where I get the help I need.
this should work, try it
local module = {} --module for the modulescript and for loop is created
local CollectionService = game:GetService("CollectionService")
local DidParts = {} -- Initializing another table to check if the part is already in it
for _, part,brick in pairs(CollectionService:GetTagged("blocks")) do
part.Touched:Connect(function(hit) --Part connects with the touched property to the function with the parameter hit
if hit.Parent:FindFirstChild("Humanoid") then
if table.find(DidParts,part) then
return -- checking if the part isnt in the table if it is then return
end
part.BrickColor = BrickColor.new("Bright green")
wait(2)
part.BrickColor = BrickColor.new("Eggplant")
table.insert(DidParts,part) -- when all the code has finished insert it in the table
-- local sound = workspace.Sound -- use "local sound = workspace.Sound", if there is already a sound object in the workspace
--sound.SoundId = "rbxassetid://4797903038" --replace quoted text with whatever sound id you need to use
--sound:Play()
end
end)
end
-- end)
--end
return module

Script stops after a few seconds

I have this exploit for Murder Mystery 2.
It is a tpcoins and esp exploit. When I enable the tpcoins it will turn off after a few seconds. Is there any way of making it so it stays on?
Here's the code:
function enableTpCoin()
if nameMap ~= "" and wp[nameMap] ~= nil then
if lplr.PlayerGui.MainGUI.Game.CashBag:FindFirstChild("Elite") then
tpCoin(10)
elseif lplr.PlayerGui.MainGUI.Game.CashBag:FindFirstChild("Coins") then
tpCoin(15)
end
end
Trigger to start the script is q.
Short answer, you can't. Since this is script related I'll answer your question.
So each round, the player can only earn 10 coins, and 15 if they have purchased the "Elite" gamepass.
This meaning that the game physically doesn't allow you to add anymore per round. You'll have to execute the code at the launch of every round.
The game has FE, so it's most likely that the original developer of the game has specified the remote events to only accept 10 or 15 coins depending on the boolean value whether the user is "Elite" or not.
Even if Universal Link says the truth, here's the solution.
Create a new function. In that function, do a while loop with a interval (use wait(.1)), and in that while loop, call enableTpCoin().
Now, call spawn() and pass the function you created as an argument.
The code should look like this:
function _loop()
while wait(.1) do
enableTpCoin()
end
end
spawn(_loop)

Roblox Anti-Exploit WalkSpeed Script

I am making a game that has different walkspeeds in different sections, but I don't want people to change their own walkspeed with hacks. My solution was to make a part and stretch it to fit the entire area and make it invisible + CanCollide disabled, and then use the child script to kill you if your walkspeed isn't what it should be:
script.Parent.Touched:connect(function(WSChecker)
if not WSChecker.Parent then return end
local humanoid = WSChecker.Parent:FindFirstChild("Humanoid")
if not humanoid then return end
if (humanoid.WalkSpeed ~= 25) then
humanoid.Health = 0
end
end)
Problem is that it does not work with multiple players in the part at one time, and I want to make it so it will kick the player instead of killing them. Is there a way to go about these problems? It has to check their ws only within the part, and I don't know how to make it kick whoever changed their ws instead of killing them.
I would suggest hooking up your function to each player's Humanoid instead, and use the Humanoid.Running event.
Humanoid.Running provides you the speed they're currently running at, which means you can check if that speed is ever above a certain threshold, and punish them if it is.
Code example:
player.Character.Humanoid.Running:Connect(function(Speed)
print(Player, "is running at speed", Speed)
end)
As for kicking, you want to use player:Kick().
if (humanoid.WalkSpeed ~= 25) then
game.Players.LocalPlayer:Kick()
end
that should do the trick...
I think I can help. The solution that worked for me is:
local player = game.Players.LocalPlayer --Make sure it's a local script.
local char = player.Character
local hum = char:WaitForChild("Humanoid")
local hum2 = char.Humanoid
script.Parent = game.StarterPlayer.StarterPlayerScripts
if hum.WalkSpeed >16 then
player:Kick('You have been kicked for possible speed hacks.')
end
if hum2.WalkSpeed >16 then
player:Kick('You have been kicked for possible speed hacks.')
end
if (humanoid.WalkSpeed ~= 25) then
game.localplayer.remove:fire
end
end)
Hopefully, this is a better solution.
You can ofcourse do the above but as an addition to what everyone above said, checking if the walkspeed value is at the desired value is easily bypassable.
Exploiters will get the raw metatable of the game and hook __index to return a normal value for WalkSpeed. Metatables cant be detected either as most modern exploits use C closures instead of Lua. Your best chance is to see how fast the character is moving and teleport them back if player is moving too fast (like a passive anticheat).

Lua Coroutine Error

I'm currently working on a simple 'guess the number' game using Lua. I'm programming through an app on my iPad called TouchLua+. One of the game modes is you have a certain amount of time to guess the number. I thought that to do this, I would create a coroutine that counts down from the given time. For some reason, I can't input a number while the coroutine is running. Can anyone help? Here is what I have so far.
target = math.random(1, 100)
coroutine.resume(coroutine.create(function()
for i = 1, roundTime do
sleep(1000)
sys.alert("tock")
end
lose = true
coroutine.yield()
end))
repeat
local n = tonumber(io.read())
if (n > target) then
print("Try a lower number.\n")
elseif (n < target) then
print("Try a higher number.\n")
else
win = true
end
until (lose or win)
return true
Coroutines are not a form of multiprocessing, they are a form of cooperative multithreading. As such, while the coroutine is running, nothing else is running. A coroutine is meant to yield control back to the caller often, and the caller is meant to resume the coroutine so the coroutine can continue where it yielded. You can see how this will appear to be parallel processing.
So in your case you would want to yield from inside the loop, after a small sleep time:
co = coroutine.create(function()
for i = 1, roundTime do
sleep(1)
sys.alert("tock")
coroutine.yield()
end
lose = true
end)
Unfortunately, you can't interrupt io.read(), which means the above is of no use. Ideally you would want a "io.peek" function so you could do the following:
while coroutine.status(co) ~= "dead" do
coroutine.resume(co)
if io.peek() then -- non-blocking, just checks if a key has been pressed
... get the answer and process ...
end
end
I am not aware of a non-blocking keyboard IO in Lua. You could create a C extension that exposes some of C non-blocking keyboard input to Lua, assuming that TouchLua+ supports C extensions. I doubt it, given that it is an iOS app.
It doesn't appear that there is a time loop or callbacks or such, and couldn't find docs. If you have option of creating a text box where user can enter answer and they have to click accept then you can measure how long it took. If there is a time loop you could check time there and show message if run out of time. All this is very easy to do in Corona, maybe not possible in TouchLua+.

How to end a looping coroutine in Lua?

I'm currently working on a game using Roblox (which uses Lua). It is a basically made up of several minigames. At the beginning of each round, all the players in game are put in a table and teleported to an area. That is where the coroutine comes into play. As the round is in progress, I want a coroutine to start. Every second that coroutine checks if the player's health is below zero, and removes them from the currentPlayer table if it is.
Sorry if I am not describing the problem correctly, but the coroutine will not yield. I haven't used coroutines before, so I am probably trying to yield it the wrong way. I know most of you will not be familiar with Roblox, but the Lua syntax is the same.
Can someone please give me an example of how I would end a looping coroutine?
currentPlayers = {}
roundTime = 60
local lookForWinners = coroutine.create(function()
while coroutine.running do
wait(1)
for i, v in pairs(currentPlayers) do
if v.Character.Humanoid.Health <= 0 then
table.remove(currentPlayers, v)
end
end
end
end)
while wait() do
repeat display("Two or more players need to be in the game.", 1) until #_G.plrs > 1 --Ignore, just checks if two+ players are in game.
display("Picking a map...", 3) pickMap()
teleport(0, 500, 0)
coroutine.resume(lookForWinners)
wait(roundTime)
print("Round over")
coroutine.yield(lookForWinners)
end
Lua is a single-threaded language. Coroutines do not cause functions to execute in parallel.
Coroutines are effectively just a way to make a function that can pause its own execution (using coroutine.yield), that can be resumed from outside (using coroutine.resume). There is no "coroutine.running": there's only one line "running" at any given time.
If Roblox were meant for you to use wait() to jump out of the Lua thread, you would write this as a series of loops that check their condition and then call wait():
local currentPlayers={}
local roundTime = 60
while #_G.plrs > 1 do
display("Two or more players need to be in the game.", 1)
wait()
end
display("Picking a map...", 3) pickMap()
teleport(0, 500, 0)
for i=0, roundTime do
for i, v in pairs(currentPlayers) do
if v.Character.Humanoid.Health <= 0 then
table.remove(currentPlayers, v)
end
end
wait(1)
end
print("Round over")
However, this is bad code. (Whenever you write code, let loops with a "wait" function in them serve to indicate that something is being done incorrectly.) You should be using Roblox's Events to handle your game's logic.
Check to see if the game should start only when the number of players changes.
"Look For Winners" only when a Humanoid's health changes (the HealthChanged event).
Run the timer on some kind of timer or interval (don't forget that you'll probably want to end your game early once somebody has won).
Events have many, many advantages over a busy loop; the most visible one will be that your checks occur when the thing they're checking for happens, and not later.
I suggest you follow Stuart's advice to use events; this is mostly to provide additional information on what coroutines are to help you use them correctly.
Think of coroutines as functions that may return values, but with a twist: while a "normal" function completes when it executes return, when you yield from a coroutine, it saves its state, so that resume can then continue from the point where you yielded as if nothing happened. Note that you only yield from a coroutine and only to the point where the resume of that coroutine was done (this is no different from calling a function and returning from it; the control returns to the point where you called the function).
In addition to that, resume and yield calls allow you to pass values to the coroutine and return (intermediate) values from the coroutine. See this SO answer for an example of how this can be used.
One can still return from a coroutine and it's no different from returning from a function, which completes its execution. If you check the status of the coroutine at that time (coroutine.status), it should be "dead".
So, to answer your question how you can end a looping coroutine: you can return from it, you can yield() from it (and never resume it again), or you can call error(), which you can then catch and check for in the result of the resume call. Having said that, I agree with Stuart that it may be the wrong way to solve your problem.

Resources