Hello I am making a roblox LUA script and I cant figure out how to make the script stop after a if sentence. Here my code.
if not newPlayer:GetRankInGroup(workspace.CoreValues.GroupID.Value) then
teamName = "Civilian"
(STOP)
end
Depending on how you structure your code, you could simply return.
local shouldEscape = true
if shouldEscape then
return
end
print("This line won't get hit")
But if you have set up event listeners, this won't stop those from firing. You'll need to clean those up, disable the Script, or delete the Script.
-- connect to a signal as an example
local connection = game.Players.PlayerAdded:Connect(function(player)
-- if the Script is still enabled, this line will print
print("Player Added : " .. player.Name)
end
local shouldEscape = true
if shouldEscape then
-- disable the script
script.Disabled = true
-- OR : disconnect the signals
--connection:Disconnect()
-- OR : delete the script entirely
--script:Destroy()
-- escape so that no other lines execute
return
end
print("This line won't get hit")
Related
It's me again
I'm trying to make a Terminal program in Lua since it's my best language I know, I'm making the calculator program in it and I'm trying to make it so if the user types "exit" the program will restart and will go back to the terminal, but I don't know how to reset the program through the code. if anyone can help that be deeply appreciated.
This is the code:
io.write("Terminal is starting up --- done!")
io.write("Making sure everything works --- Done!")
cmd = io.read()
io.write(">")
if cmd == "" then
io.write(">\n")
end
if cmd == "cal"then
io.write("Calculator Terminal Program v1.0")
io.write("what operation?/n")
op = io.read()
if op == "exit"then
io.write("Exiting")
end
end
To answer your question directly, I don't think it's possible to "restart the program". However, by taking advantage of loops, you can achieve the same result.
For instance, this code probably does what you want:
print('Terminal is starting up --- done!')
print('Making sure everything works --- Done!')
repeat
io.write('>')
cmd = io.read()
if cmd == 'cal' then
print('Calculator Terminal Program v1.0')
repeat
io.write('Operation: ')
op = io.read()
until op == 'exit'
print('Exiting')
elseif cmd == 'command' then
--another command
else
print('Unknown command.')
end
until cmd == 'exit'
Other tips:
You should take advantage of elseif instead of writing multiple separate if statements to improve readability.
Consider using the print function when you want a new line after writing some text for a better Terminal experience. You could also use io.write('\n').
You probably want os.exit(), which terminates the entire program.
i think this might work through creative use of load() and coroutines
this gonna stop restarting itself when 3 total error has occured
if innerProgram == nil then --innerProgram will set to true when it load itself
local filename = nil
local errorLimit = 3 --Change this to any value to enable this code to restart itself when error occur until this amount of time set zero or below to exit instantly when error occur
local errors = 0
local filename = function()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("^.*/(.*)") or str
end
filename = filename()
local src_h = io.open(filename, "r") --open in read mode
local src = src_h:read("*a")
src_h:close()
local G = _G
local quit = false --set true when you want to exit instead restart
local code = nil
local request = false
local restart = false --set true when you want restart
local program
local yield = coroutine.yield --Incase when coroutine get removed in your calculator code for no reason
local running = coroutine.running
local exit = os.exit
function G.restart()
restart = true --Always refer to restart variable above
request = true
yield() --Always refer to yield above
end
function G.os.exit(exitcode) --Replace os.exit with this
quit = true --Always refer to quit variable above
reuqest = true
code = exitcode or nil
yield() --Always refer to yield above
end
function G.coroutine.yield()
if running() == program and request == false then --Emulating coroutine.yield when it not run inside coroutine
error("attempt to yield from outside a coroutine")
end
end
G.innerProgram = true --So the inner program not keep loading itself forever
function copy(obj, seen)
if type(obj) ~= 'table' then return obj end --got from https://stackoverflow.com/questions/640642/how-do-you-copy-a-lua-table-by-value for us to clone _G variable without reference to original _G thus we can do total restart without using same _G
if seen and seen[obj] then return seen[obj] end
local s = seen or {}
local res = setmetatable({}, getmetatable(obj))
s[obj] = res
for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end
return res
end
print("Loading "..filename)
program = coroutine.create(load(src, filename, "bt", copy(G)))
while errors < errorLimit do
restart = false
local status, err = coroutine.resume(program)
if restart == true then
print("Restarting...")
program = coroutine.create(load(src, filename, "bt", copy(G)))
--Put errors = errors + 1 if you want errors counter to reset every time the program request restart
end
if status == false and restart ~= true then
print(filename.." errored with "..err.."\nRestarting...")
program = coroutine.create(load(src, filename, "bt", copy(G)))
errors = errors + 1
elseif restart ~= true then
print(filename.." done executing.")
exit()
end
end
return
else
innerProgram = nil --Nil-ing the variable
end
Features
Auto exit when 3 total errors has occur (configure errorLimit variable)
_G is not shared (same _G as start of the program but not linked with the actual _G)
Emulating yielding outside of coroutine
Replaced os.exit so it yield then the self-loader run the os.exit
How to use
put the code i give above to very first line of your code
Feature Number 1 and 3 test
it error with the a content the value will be different in each error restart
if a == nil then --Only set a when a equal nil so if _G was shared the error value will be same
a = math.random() --Set global a to a random value
end
error(a) --Error with number a
os.exit()
I made a cash for kill script in Roblox, but wanted to go further than that and implement a script where when a player has a gamepass, then that player would recieve more cash than another normal player would.
This is for a battle royale styled game in Roblox, and when I playtested it, there were no errors, but the script didn't work.
game.Players.PlayerAdded:connect(function(player)
local folder = Instance.new("Folder",player)
folder.Name = "leaderstats"
local currency1 = Instance.new("IntValue",folder)
currency1.Name = "Cash"
local increment = 50
if game:GetService("MarketplaceService"):PlayerOwnsAsset(player,7382818)then
increment = increment + 50
end
player:WaitForChild("Humanoid").Died:connect(function()
local tag = player.Humanoid:FindFirstChild("creator")
if tag ~= nil then
local killer = tag.Value
if killer ~= nil then
-- Find the killer's leaderstats folder
local killerStats = killer:FindFirstChild("leaderstats")
if killerStats ~= nil then
-- Find the killer's Cash IntValue
local killerCash = killerStats:FindFirstChild("Cash")
-- Increase cash as before
killerCash.Value = killerCash.Value + increment
end
end
end
end)
I expected a VIP player, who has the gamepass, to receive more cash, but when I tested it, no player received any cash for killing another player at all.
How to fix an end expected error near eof
If the Lua interpreter complains about a missing end you`re missing it somewhere.
Read through your code and make sure everything that is supposed to be closed with an end has one. Read through the Lua Reference Manual to find out which keywords need an end.
In your code it's if statements and function definitions. Checking each pair from inside out you'll end up one end) short to close this game.Players.PlayerAdded:connect(function(player) as mentioned in the comments.
I want the script to print "Printed" when I press P but only if the tool is equipped. If the tool is unequipped I want it to be toggled off.
When I tested my code however the print was not toggled off after I unequipped my tool, it still prints "Printed". What am I doing wrong here?
tool = script.Parent
handle = tool.Handle
a = false
tool.Equipped:Connect(function()
if a == false then
a = true
game:GetService("UserInputService").InputBegan:Connect(function(P)
if P.KeyCode ==Enum.KeyCode.P then
print ("Pressed")
end
end)
end
tool.Unequipped:Connect(function()
if a == true then
a = false
end
end)
end)
In Lua once you make a :Connect statement that statement will run every time the trigger it's attached to triggers.
This means that once your code has run once and executed that game:GetService("UserInputService").InputBegan:Connect( call it will run no matter if a equals true or false. What you want is the check to be inside the :Connect call.
This is probably what you are looking for here:
Tool = script.Parent
Handle = tool.Handle
Run = false
Tool.Equipped:Connect(function()
Run = true
end)
Tool.Unequipped:Connect(function()
Run = false
end)
Game:GetService("UserInputService").InputBegan:Connect(function(P)
if P.KeyCode == Enum.KeyCode.P and Run = true then
print ("Pressed")
end
end)
The Run = true check means that the print will only run if P is pressed AND the tool is equipped. If you want this to run the other way around you can swap the true and false assignments around.
I want to make a command that would kill a player you specify..
Let's say I type: kill/Paul. Now I want to kill the player with the name Paul.
This is my command Script:
local player = ...
game.Players.PlayerAdded:connect(function(player) --this gets the player that connected
player.Chatted:connect(function(message) --this function executes when the player type into chat
--commands are here
if player.Name == "TominoCZ" or player.Name == "nathancain" or player.Name == "block100000" then
if message == "kill/me" then
player.Character.Head:remove()
end
if message == "ff/me" then
if player.Character:findFirstChild("ForceField") then
player.Character.ForceField:Destroy()
end
Instance.new("ForceField").Parent = player.Character
end
if message == "unff/me" then
if player.Character:findFirstChild("ForceField") then
player.Character.ForceField:Destroy()
end
end
end
end)
end)
Now you can see that I already have a command that will kill the play that executed it.
But how can I kill a different player by specifying the player's name after the "kill/"?
This command script might look too long or not too pro, but atleast I know and understand what it does.
So any ideas?
You can do something like this:
local player = ...
game.Players.PlayerAdded:connect(function(player) --this gets the player that connected
player.Chatted:connect(function(message) --this function executes when the player type into chat
--commands are here
if string.sub(message,1,string.len("kill/"))=="kill/" then --check the message if it starts with command "kill/"
if string.sub(message,string.len("kill/"))==player.Name then --kill the player with the name
player.Character.Head:remove()
end
end)
end)
I don't know Lua so there might be syntax errors, but the overall idea is that you use string.sub method to divide your message into 2 parts: the command part and the info part. If the command part equals to "kill/", then find the player with the name specified in the info part, and kill him! (Or behead him... I don't play ROBLOX :D)
The following script breaks between print("2") and print("3") because it cannot find the variable "tag". How would I fix this?
local Humanoid = script.Parent.Zombie -- Or Zombie Or Whatever
function PwntX_X()
print("1")
local tag = Humanoid:findFirstChild("creator")
print("2")
if tag ~= nil then
print("3")
if tag.Value ~= nil then
print("4")
local Leaderstats = tag.Value:findFirstChild("leaderstats")
print("5")
if Leaderstats ~= nil then
print("6")
Leaderstats.Cash.Value = Leaderstats.Cash.Value + 5
print("7")
wait(0.1)`enter code here`
script:remove()
end
end
end
end
Humanoid.Died:connect(PwntX_X)
I already have a script for the leaderboard that works 100%. This script is being used for a game called "ROBLOX". Thanks!
Alright, first off, scriptinghelpers.org was created as a service similar to stackoverflow specifically for Roblox, I suggest next time, you ask there, now on to stuff;
-- If you have further problems, My Roblox username is 'ZeroBits' (REMOVE THIS LINE)
DEBUG = true -- Debug Print, so you can disable it when you're done.
local function print_D(t)
if DEBUG == true then warn(t) end end
print_D("DEBUG MODE, Switch Debug Value to False when finished")
local Humanoid = script.Parent:FindFirstChild("Zombie") -- We'll use FindFirstChild() here
--if not Humanoid then -- Uncomment this statement if you want it to affect objects named Humanoid as well
-- Humanoid = script.Parent:FindFirstChild("Humanoid")
--end
function HumanoidKilled() -- Renamed the function to be a little less cringeworthy
print_D("1") -- switched these print statements with the Print_D() function
local tag = Humanoid:FindFirstChild("creator") -- Capitalized the first letter in FindFirstChild()
print_D("2")
if not tag then
warn("No Tag Found check Humanoid and weapon script") --if this prints, there's either no tag, or a serious problem, and you should check the humanoid object for a tag, or make sure the weapons you use actually generate tags.
else -- changed 'if tag ~= nil then' to 'if not tag then 'do stuff' else' to simplify the code, and add an else statement early on.
print_D("3")
if tag.Value then -- removed '~= nil' because it's just useless clutter
print_D("4")
local Leaderstats = tag.Value:findFirstChild("leaderstats")
print_D("5")
if Leaderstats ~= nil then
print_D("6")
Leaderstats.Cash.Value = Leaderstats.Cash.Value + 5
print_D("7")
wait(0.1)
script:Destroy() -- switched remove() to Destroy(), remove() is deprecated
end
end
end
end
Humanoid.Died:connect(HumanoidKilled)
This fixes all the problems in the script, and makes it more efficient. if there are still problems, it's either in the tag creation script, the tags aren't stored in the humanoid, or the tags aren't named 'creator'
also, I switched over the print statements to a print_D function, which uses warn() rather than print() there's almost no difference, except that the debug text will appear yellow in the console, rather than white.
script is being used for a game called "ROBLOX". Thanks!
It's for a game On Roblox, not a game called Roblox, what you said is akin to saying; I made this mod for Source Engine, when you actually made the mod for Half-Life 2