Roblox script does not run - roblox

I need help with my code. I'm trying to make a button give you a sword but the script will detect clicks but will not run. It keeps saying that the script detected a click but it does nothing and ends.
function Click(mouse)
for tool in ipairs(player.Backpack:GetChildren()) do
tool:Destroy()
print("Tool destroyed.")
end
for tool in ipairs(player.StarterPack:GetChildren()) do
tool:Destroy()
print("Tool destroyed.")
end
local cloneb = game.ServerStorage.Darkheart:Clone()
cloneb.Parent = player.backpack
print("Tool moved.")
local clones = game.ServerStorage.Darkheart:Clone()
clones.Parent = player.StarterPack
print("Tool moved.")
end
script.Parent.MouseButton1Down:Connect(Click)
wait ()

First and largest problem, you have an extra end after the print("tool moved") message. Here is the corrected script.
Mouse.Button1Down:Connect(function()
for tool in ipairs(player.Backpack:GetChildren()) do
tool:Destroy()
print("Tool destroyed.")
end
for tool in ipairs(player.StarterPack:GetChildren()) do
tool:Destroy()
print("Tool destroyed.")
end
local cloneb = game.ServerStorage.Darkheart:Clone()
cloneb.Parent = player.backpack
print("Tool moved.")
local clones = game.ServerStorage.Darkheart:Clone()
clones.Parent = player.StarterPack
print("Tool moved.")
wait ()
end
edit:
Mouse.Button1Down:Connect(function()
for tool in ipairs(player.Backpack:GetChildren()) do
tool:Destroy()
print("Tool destroyed.")
end
for tool in ipairs(player.StarterPack:GetChildren()) do
tool:Destroy()
print("Tool destroyed.")
end
local cloneb = game.ServerStorage.Darkheart:Clone()
cloneb.Parent = player.backpack
print("Tool moved.")
local clones = game.ServerStorage.Darkheart:Clone()
clones.Parent = player.StarterPack
print("Tool moved.")
wait ()
end) -- added a parenthesis / )
Try this one. I'm not entirely sure if it will work because I cannot test it with your file, and if it doesn't here is a resource to look at: https://developer.roblox.com/en-us/api-reference/event/Mouse/Button1Down

Related

How to break a MATLAB system call after a specified number of seconds

I am using Windows MATLAB to run SSH commands, but every once in a while the SSH command hangs indefinitely, and then so does my MATLAB script (sometimes when running overnight). How can I have a command time-out after a certain amount of waiting time? For example, suppose I don't want to wait more than 3 seconds for a SSH command to finish execution before breaking it and moving on:
% placeholder for a command that sometimes hangs
[status,result] = system('ssh some-user#0.1.2.3 sleep 10')
% placeholder for something I still want to run if the above command hangs
[status,result] = system('ssh some-user#0.1.2.3 ls')
I'd like to make a function sys_with_timeout that can be used like this:
timeoutDuration = 3;
[status,result] = sys_with_timeout('ssh some-user#0.1.2.3 sleep 10', timeoutDuration)
[status,result] = sys_with_timeout('ssh some-user#0.1.2.3 ls', timeoutDuration)
I've tried the timeout function from FEX but it doesn't seem to work for a system/SSH command.
I don't think the system command is very flexible, and I don't see a way to do what you want using it.
But we can use the Java functionality built into MATLAB for this, according to this answer by André Caron.
This is how you'd wait for the process to finish with a timeout:
runtime = java.lang.Runtime.getRuntime();
process = runtime.exec('sleep 20');
process.waitFor(10, java.util.concurrent.TimeUnit.SECONDS);
if process.isAlive()
disp("Done waiting for this...")
process.destroyForcibly();
end
process.exitValue()
In the example, we run the sleep 20 shell command, then waitFor() waits until the program finishes, but for a maximum of 10 seconds. We poll to see if the process is still running, and kill it if it is. exitValue() returns the status, if you need it.
Running sleep 5 I see:
ans =
0
Running sleep 20 I see:
Done waiting for this...
ans =
137
Building on #Cris Luengo's answer, here is the sys_with_timeout() function. I didn't use the process.waitFor() function because I'd rather wait in a while loop and display output as it comes in. The while loop breaks once the command finishes or it times out, whichever comes first.
function [status,cmdout] = sys_with_timeout(command,timeoutSeconds,streamOutput,errorOnTimeout)
arguments
command char
timeoutSeconds {mustBeNonnegative} = Inf
streamOutput logical = true % display output as it comes in
errorOnTimeout logical = false % if false, display warning only
end
% launch command as java process (does not wait for output)
process = java.lang.Runtime.getRuntime().exec(command);
% start the timeout timer!
timeoutTimer = tic();
% Output reader (from https://www.mathworks.com/matlabcentral/answers/257278)
outputReader = java.io.BufferedReader(java.io.InputStreamReader(process.getInputStream()));
errorReader = java.io.BufferedReader(java.io.InputStreamReader(process.getErrorStream()));
% initialize output char array
cmdout = '';
while true
% If any lines are ready to read, append them to output
% and display them if streamOutput is true
if outputReader.ready() || errorReader.ready()
if outputReader.ready()
nextLine = char(outputReader.readLine());
elseif errorReader.ready()
nextLine = char(errorReader.readLine());
end
cmdout = [cmdout,nextLine,newline()];
if streamOutput == true
disp(nextLine);
end
continue
else
% if there are no lines ready in the reader, and the
% process is no longer running, then we are done
if ~process.isAlive()
break
end
% Check for timeout. If timeout is reached, destroy
% the process and break
if toc(timeoutTimer) > timeoutSeconds
timeoutMessage = ['sys_with_timeout(''',command, ''',', num2str(timeoutSeconds), ')',...
' failed after timeout of ',num2str(toc(timeoutTimer)),' seconds'];
if errorOnTimeout == true
error(timeoutMessage)
else
warning(timeoutMessage)
end
process.destroyForcibly();
break
end
end
end
if ~isempty(cmdout)
cmdout(end) = []; % remove trailing newline of command output
end
status = process.exitValue(); % return
end
Replacing ssh some-user#0.1.2.3 with wsl (requires WSL of course) for simplicity, here is an example of a function that times out:
>> [status,cmdout] = sys_with_timeout('wsl echo start! && sleep 2 && echo finished!',1)
start!
Warning: sys_with_timeout('wsl echo start! && sleep 2 && echo finished!',1) failed after timeout of 1.0002 seconds
> In sys_with_timeout (line 41)
status =
1
cmdout =
'start!'
and here is an example of a function that doesn't time out:
>> [status,cmdout] = sys_with_timeout('wsl echo start! && sleep 2 && echo finished!',3)
start!
finished!
status =
0
cmdout =
'start!
finished!'

Roblox-How to fix tool manager

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local remotes = ReplicatedStorage:FindFirstChild("Remotes")
local tools = ServerStorage:FindFirstChild("Tools")
local scripts = ServerStorage:FindFirstChild("Scripts")
local toolConfig = require(ReplicatedStorage:FindFirstChild("Config"):FindFirstChild("ToolConfig"))
remotes.ToolActivated.OnServerEvent:Connect(function(player: Player)
local playerTool = player.inventory.EquippedTool.Value
for tool, toolTable in pairs(toolConfig) do
if tool == playerTool then
player.leaderstats.Decibel.Value += toolTable.Decibel
end
end
print(player.Name)
end)
for _, tool in ipairs(tools:GetChildren()) do
local script = scripts.Click:Clone()
script.Parent = tool
end
This is my code to make the Decibel Value from leaderstats go up
Then It doesn't show any error up but it isn't working.
It doesn't print the player name and also it doesn't make the Decibel Value go up
help
On the client, you need to fire the signal.
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remotes = ReplicatedStorage:FindFirstChild("Remotes")
local tool = script.Parent
tool.Activated:Connect(function()
remotes.ToolActivated:Fire()
end

How to exit a REPL from the command line

I'm currently learning Lua and also learning how to work with CMD.
I know how to change a directory path and run my codes and files from that path
but what I don't know and I'm here to ask for is how to get out of a programming language REPL when you start it in CMD
For example to jump into the Lua REPL you should type:
lua53 (--like python3 for the Python language)
then you changed the CMD environment to a Lua compiler and can't access CMD commands such as
dir, cd, cls etc. and everytime when I need to access these commands I have to close the CMD window and open a new one.
Now can you guys tell me am I able to access CMD commands while in the Lua REPL? Or do I have to exit Lua first, and is there any command to exit a REPL?
I'd recommend EOF (Ctrl + D on Unix) rather than SIGKILL (Ctrl + C) because some REPLs (node and python) choose to ignore the latter (perhaps because it's often used for copying text?); python will just print KeyboardInterrupt whereas node will only exit if you press Ctrl + C twice (it will send a message telling you this the first time).
EOF (Ctrl + D) on the other hand immediately exists all REPLs I have used so far.
The Lua REPL stops immediately when it receives either EOF or SIGKILL, so you can use both here.
Edit: As Sowban points out, EOF apparently is entered as Ctrl + Z then Enter in powershell.
You could type ctrl c to exit the process that's running generally.
I suggest to write a REPL by yourself.
But be warned :-)
The main loop with a prompt and the interpreting and executing function/method is mostly the easiest part.
99.99999% is the errorhandling thing.
One of my earliest interpreter language is (A)REXX.
A REPL without any errorhandling is done with...
/* REXX have to start with a comment */
do forever
parse pull input
interpret input
end
Now Lua sandboxed to an _ENV with io and os library and a little bit of errorhandling...
#!/usr/bin/env -S readline-editor /usr/local/bin/lua
-- ^--SHEBANG for Linux --------------------------------------------------------------------------------------
-- interpreter.lua
-- Sandboxed to io and os
-- Lua 5.4 >>-because-> goto label <const> load()
--------------------------------------------------------------------------------------------------------------
local Lua = function(...)
-- Info about OS
io.write(("%s\n"):format(io.popen('uname -a'):read())):flush()
-- Global Setting
debug.setmetatable((1), {__index = math}) -- Add math library to number as methods (like string for strings)
os.setlocale('de_DE.UTF8')
os.setlocale('en_US.UTF8', 'time')
io.write(os.date("[%c]\n" .. ("%s\n"):format(os.setlocale():gsub("%;", "\n")))):flush()
-- io.write(("%s\n"):format(_VERSION)):flush()
-- Label for goto
::lua::
-- Local Setting
local args <const> = args or {...}
local Lua = Lua or true
local cmd = cmd or ""
--------------------------------------------------------------------------------------------------------------
local env <const> = env or setmetatable({os = os, io = io}, -- The _ENV for load()
{__call = function(self, ...)
local self, t = ({...})[1] or self, "" -- First argument becomes self if one
if ({...})[1] == "help" then self = getmetatable(({...})[2]).__index end -- Showing metamethod __index (table)
for k, v in pairs(self) do
t = t .. ("%s => %s\n"):format(k, v)
end
return t
end,
__index = {cg = collectgarbage,
gt = getmetatable,
pairs = pairs,
tn = tonumber,
ts = tostring,
_V = ("%s \27[1;" .. (31):random(36) .. "m(sandboxed)\27[0m"):format(_VERSION)},
__tostring = function(self) return self._V end}) -- end env
--------------------------------------------------------------------------------------------------------------
local prompt = prompt or setmetatable({}, {__tostring = function() return getmetatable(env).__index._V .. "> " end})
local name <const> = name or _VERSION
local result = result or true
--------------------------------------------------------------------------------------------------------------
while Lua do
io.write(tostring(prompt))
cmd = io.read() or 'quit'
if cmd == "quit" then Lua, result = true, true break end
Lua, result = pcall(load("return " .. cmd or false, name, "t", env))
if Lua and result then
io.write(("%s"):format(tostring(result)))
else
goto exception
end
end
--------------------------------------------------------------------------------------------------------------
-- Errorhandler
::exception::
io.write(("%s\n"):format("Exception"))
if not Lua or not result then
io.output(io.stderr)
io.write(("[%s][%s][%s]\n\27[1;31m>>-Exception->\27[0m %s\n"):format(os.date(), _VERSION, cmd, result)):flush()
io.output(io.stdout)
collectgarbage()
goto lua
end
goto lua
end
--------------------------------------------------------------------------------------------------------------
-- EXAMPLE ---------------------------------------------------------------------------------------------------
-- Lua = require("interpreter")
Lua() -- UNCOMMENT-> For direct execution like: /bin/lua interpreter.lua
return Lua -- UNCOMMENT-> For: Lua = require("interpreter")
Ctrl&C quits hardly
Ctrl&D is only an exception
...and os.exit(0) do an clean exit with returncode 0.
Impression

Attempt to call global function is nil, but function is not shown in debugger?

I am using Eclipse LDT for development, using the packaged Lua EE and Interpreter for Lua 5.2. I need to call the commandDatabase() method from my main method, though when I try, I receive the error:
"attempt to call global 'commandDatabase' (a nil value)".
I have looked up this error, and I am, as far as I can tell, defining methods in the right order.
Lua - attempt to call global 'contains' (a nil value)
When I view it in the debugger, the interpreter does not seem to find any methods I define between commandSystem and commandHelp. It shows each other function in the Variables area as e.g. ["commandSystem"] = function() but commandDatabase() does not appear
I have tried calling a wrapper method like so:
function commandDatabaseStep()
return commandDatabase()
end
... but this did not work either (same error)
The relevant code:
-- System command
function commandSystem()
...
end
-- Database command
function commandDatabase()
if arguments[2] == "no_arg1" then
print("The 'database' command must have at least one argument: [generate, wipe, dump, delete, get <system_name>]", true)
return 2
elseif arguments[2] == "generate" then
local file = io.open(database, "w+")
file:write("#ssmhub database")
file:close(file)
return 1
elseif arguments[2] == "dump" then
print("= DUMP START =")
for line in io.lines(database) do
print(line)
end
print("= DUMP END =")
return 1
-- 1+
elseif arguments[2] == "get" then
-- 2+
if isEmpty(arguments[3]) then
print("The 'database get' command must have a <name> parameter")
return 0
-- 2-
else -- 3+
local file = io.open(database, "r")
for line in io.lines(file) do -- 4+
local state = ""
local id = ""
local dividersFound = 0
line:gsub(".", function(c) -- 5+
if c == "|" then -- 6+
if dividersFound == 0 then -- 7+
state = state .. c
end -- 7-
if dividersFound == 1 then -- 8+
id = id .. c
end -- 8-
dividersFound = dividersFound + 1
end -- 6-
end) -- 5-
io.close(file)
end -- 4-
end -- 3-
else -- 9+
print("Illegal argument for command. Use 'help' for a list of commands and arguments.")
return 0
end -- 9-
end -- 2-
end -- 1-
function commandHelp()
...
end
-- Main
function main()
arguments = readProgramArguments()
commandArgument = arguments[1]
commandCompleteCode = 0
-- Process help and system commands
if commandArgument == "database" then
commandCompleteCode = commandDatabase()
end
end main()
As #luther pointed out, I had one-too-many end-s in commandDatabase.
This wasn't flagged in my IDE because I had not end-ed commandSystem, so commandSystem was nested inside of it.
To fix: add an end to commandSystem, and remove the end which I tagged '-- 1-'.

interrupt a TCP-IP callback function in matlab

Recently wrote code that establishes a connection between two instances of matlab. I can send messages through the TCP-IP connection which will execute code. Now I'm trying to setup the code to be interruptible as I would like to start/stop a function through TCP-IP. Problem though is that sending a second command does nothing until the function is completed. Is there a way to interrupt a TCP-IP callback function?
code:
classdef connectcompstogether<handle
properties
serverIP
clientIP
tcpipServer
tcpipClient
Port = 4000;
bsize = 8;
earlystop
end
methods
function gh = connectcompstogether(~)
% gh.serverIP = '127.0.0.1';
gh.serverIP = 'localhost';
gh.clientIP = '0.0.0.0';
end
function SetupServer(gh)
gh.tcpipServer = tcpip(gh.clientIP,gh.Port,'NetworkRole','Server');
set(gh.tcpipServer,'OutputBufferSize',gh.bsize);
fopen(gh.tcpipServer);
display('Established Connection')
end
function SetupClient(gh)
gh.tcpipClient = tcpip(gh.serverIP,gh.Port,'NetworkRole','Client');
set(gh.tcpipClient, 'InputBufferSize',gh.bsize);
set(gh.tcpipClient, 'BytesAvailableFcnCount',8);
set(gh.tcpipClient, 'BytesAvailableFcnMode','byte');
set(gh.tcpipClient, 'BytesAvailableFcn', #(h,e)gh.recmessage(h,e));
fopen(gh.tcpipClient);
display('Established Connection')
end
function CloseClient(gh)
fclose(gh.tcpipClient);
gh.tcpipClient = [];
end
end
methods
function sendmessage(gh,message)
fwrite(gh.tcpipServer,message,'double');
end
function recmessage(gh,h,e)
Message = fread(gh.tcpipClient,gh.bsize/8,'double');
if Message == 444
gh.Funwithnumbers();
elseif Message == 777
gh.earlystop = 1;
end
end
function Funwithnumbers(gh)
x=1;
while true
if x > 5000, break;end
if gh.earlystop == 1,break;end
x = x+1;
display(x)
end
end
end
end
for ease to understand code.
server
Ser = connectcompstogether;
ser.SetupServer();
ser.sendmessage(333);
Client
cli = connectcompstogether;
cli.SetupClient();
Update:
So after going through the web, I have found out based on this post that the tcpip callback cannot be interrupt. The post was in 2017 which means my 2016a version definitely cannot interrupt a callback.
So An update to my question, Is it possible to start a subprocess in matlab to run the function. I just want to use the callback to start code. If I can start a subprocess from the callback. Than I should be able to free up the main process and use tcpip to start/stop a function on a different computer.
Update 2:
So I tried to utilize parallel processing using the 'spmd' command but the problem still persisted.
function recmessage(gh,h,e)
Message = fread(gh.tcpipClient,gh.bsize/8,'double');
spmd
switch labindex
case 1
if Message == 444
gh.Funwithnumbers();
elseif Message == 777
gh.earlystop = 1;
end
end
end
end
You may use a timer object, which is convenient to delay the execution of some function.
t=timer('ExecutionMode','singleShot', 'StartDelay',0, 'TimerFcn',#myCallback);
start(t);
In this case, the StartDelay is 0, so myCallback will be almost immediately added to the queue of tasks to be processed by Matlab. The execution however will start only after the callback to the tcpip object has been completed. It will block the queue once started, however.
You may try something like:
properties
t=timer('ExecutionMode','singleShot', 'StartDelay',0, 'TimerFcn',#myCallback);
end
function tcpipCallback(gh,tcpObj,~)
message=fread(tcpObj,1,'double');
if message==444
if strcmp(get(t,'Running'),'on')
error('The function is running already');
else
set(gh.t,'UserData',false);
start(gh.t);
end
elseif message==777
set(gh.t,'UserData',true);
end
function myCallback(tObj,~)
ii=0;
while ii<5000
if get(tObj,'UserData'),break,end
ii=ii+1;
pause(.0001); %Pause to interrupt the callback; drawnnow might work too; or perhaps this is not needed at all.
end
end