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.
Related
script.Parent.MouseButton1Click:Connect(function()
if script.Parent.Parent.Frame.Visible == true then
script.Parent.Parent.Frame.Visible = false
end
if script.Parent.Parent.Frame.Visible == false then
script.Parent.Parent.Frame.Visible = true
end
end)
I am very new to coding (have started practically yesterday ) and ive decided to start with lua in roblox studio. The program here is working i can assure you (some things in code may not be in proper place since im having a bit trouble writing code on this site) but the code works. I have tried to make it seperatly for 2 buttons then I tried this and nothing seems to work. I am starting to think it is caused by the program itself and not the code since I can make other things invisible with that code. I've placed those 2 codes for visibility and invisibility in 1 thing since I've been told that events caused by the code happen at same time so some of them may not work.
Assume Visible is true. The first condition will be true and Visible will be set to false. Then, in the next condition Visible is false and the condition is therefore true, again. And it sets Visible back to true.
Now, in order to fix it you want to execute the second condition only if the first failed. Take a look at elseif https://www.lua.org/pil/4.3.1.html.
script.Parent.MouseButton1Click:Connect(function()
if script.Parent.Parent.Frame.Visible == true then
script.Parent.Parent.Frame.Visible = false
elseif script.Parent.Parent.Frame.Visible == false then
script.Parent.Parent.Frame.Visible = true
end
end)
This code is still quite bulky and can be improved:
script.Parent.MouseButton1Click:Connect(function()
script.Parent.Parent.Frame.Visible = not script.Parent.Parent.Frame.Visible
end)
Now you assign true to Visible if Visible does not evaluate to true. It basically toggles the boolean.
I am having problems with the functionality of a script and I don't know how to solve it.
In the images below attach photos of the in-game problem, this means that the whole script works and in-game the property of the visible "bframe" is false but in-game this is not shown and I want to know how I can solve it ..
in-game mode the visibility of the "Bframe" it becomes false in the property (that's fine) but in-game this is not seen..
Does anyone know how to solve it?
Button script
-- Events
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Evento = ReplicatedStorage.RemoteEvent
-- end of Events
local button = script.Parent
local frame = script.Parent.Parent.Parent.Frame
Evento.OnClientEvent:Connect(function(argumento1)
button.MouseButton1Click:Connect(function()
if frame.Visible == false then
frame.Visible = true
button.Visible = false
else
frame.Visible = false
end
end)
end)
Server script
-- Events
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Evento = ReplicatedStorage.RemoteEvent
-- end of Events
game.Players.PlayerAdded:Connect(function(player)
Evento:FireClient(player,"argumento1")
print("testing probado")
end)
Redteam / touch part script called script
local wll = script.Parent.Part
local fr = game.StarterGui.TeamChangerGui.BFrame
local function Toch()
fr.Visible = false
fr.button.Visible = false
print("visible desactivado")
end
wll.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
Toch()
end
end)
**images**
enter image description here
enter image description here
enter image description here
Is the button script a localscript? if it is then it may be to do with the fireclient although I am not good at it and I usually use fireallclients passing through the player name then checking if its the correct name on the clients side script.
Otherwise I am not sure as it is an interesting issue i have never encountered. Hope it works!
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()
can someone help me with that? I already got the code for resetting but when i open chat and say rrrrrrr, i keep dying.
here it is:
local player = game:GetService("Players").LocalPlayer
local character = player.Character
local enabled = true
local userinputservice = game:GetService("UserInputService")
userinputservice.InputBegan:connect(function(input)
if input.KeyCode == Enum.KeyCode.R and enabled then
character.Head:Remove()
enabled = false
wait(6)
enabled = true
end
end)
UserInputService#inputBegan gives you gameProcessedEvent as the second parameter of the function.
It indicates whether the game engine internally observed this input and acted on it. Generally, this refers to UI processing, so if a button was touched or clicked from this input, gameProcessedEvent would be true. This applies to TextBoxes, such as the chat.
All you need to check if if gameProcessedEvent is true.
local UserInputService = game:GetService("UserInputService");
local PlayersService = game:GetService("Players");
UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
if gameProcessedEvent then return false end
if (input.KeyCode == Enum.KeyCode.R) then
PlayersService.LocalPlayer.Character.Head:Destroy()
end
end)
This is for my game. I have all the code right with no errors.
script.Parent.MouseButton1Click:Connect(function()
game.StarterGui.ScreenGui.Enabled = true
script.Parent.Visible = false
end)
But when I start the game the code wont work properly, only the shop button disappears which is: "script.Parent.Visible = false" and the show me the shop: "game.StarterGui.ScreenGui.Enabled = true" is not working,and wont show up the shop, yes I have the ScreenGui disabled, and there are no output errors.
you need to make sure that you are useing the local StarterGui
when you do game.StarterGui.ScreenGui.Enabled = true you are changing the global instance and not the local. To fix this you need to use script.Parent and not game.StarterGui.
Below is some example code:
script.Parent.MouseButton1Click:Connect(function()
script.Parent.%how ever many parents it takes go get back to StarterGui%.ScreenGui.Enabled = true
script.Parent.Visible = false
end)
In the second line, You are enabling a GUI that's located in the StarterGui not the PlayerGui, To fix the problem, Change your code to this:
script.Parent.MouseButton1Click:Connect(function()
game.Players.LocalPlayer.PlayerGui.ScreenGui.Enabled = true
script.Parent.Visible = false
end)
Also, when posting code next time, use {} button instead