add output of a script to a number in lua - lua

I have a shell script in Linux which outputs 10.
I want to write a script in lua, which adds 5 to my output of shell script. How can I use output of my shell script?
This is what I have tried -
print(5 + tonumber(os.execute('./sample')))
This is the output -
10
lua: temp.lua:2: bad argument #2 to 'tonumber' (number expected, got string)
stack traceback:
[C]: in function 'tonumber'
temp.lua:2: in main chunk
[C]: in ?

As #Etan Reisner said, os.execute is returning multiple values, however, the exit code is not the first return value. Therefore, you'll have to stuff the values into variables:
local ok, reason, exitcode = os.execute("./sample")
if ok and reason == "exit" then
print(5 + exitcode)
else
-- The process failed or was terminated by a signal
end
By the way, if you want to return the new value as exit code, you can do so using os.exit:
os.exit(5 + exitcode)
Edit: As you have clarified via a comment, you are looking to read the output (stdout) of the process, not its return value. In this case, io.popen is the function you need:
local file = io.popen("./sample")
local value = file:read("*a")
print(5 + tonumber(value))
Note, however, that io.popen is not available on every plattform

Related

How to map a shell command in the lua nvim config?

How to map a shell command in the lua nvim config?
maps.n["<F4>"] = { function() io.popen("python3 " + vim.fn.expand("%")) end, desc = "Run current Python file"}
Error:
E5108: Error executing lua: /home/kobe/.config/nvim/lua/core/mappings.lua:19: attempt to perform arithmetic on a string value
stack traceback:
/home/kobe/.config/nvim/lua/core/mappings.lua:19: in function </home/kobe/.config/nvim/lua/core/mappings.lua:19>
Maybe this isn't exactly what you're looking for, but I use plugins like toggleterm for this. You can setup keymappings to run whatever shell command or program you want, and also have it show up in a floating or none-floating window, too.
As for just mapping it without any plugins and having the command be executing, I'm not entirely sure.
In Lua, operand to concatenate 2 strings is .. not + as in Python.
Correct your code : function() io.popen("python3 " .. vim.fn.expand("%")) end

Roblox Run Script From String in variable

I'm trying to make a ss script that runs by turning the text inside the TextBox into a variable and running the variable as a script, how do I do this?
I tried to use loadstring but it didn't work, what do I do?
script.Parent.MouseButton1Down:Connect(function()
local script = script.Parent.Parent.TextBox.Text
loadstring(script)
end)
If no errors occur loadstring returns the loaded chunk as a function.
You failed to call that function.
assert(loadstring(script))()
Please read the Lua manual. https://www.lua.org/manual/5.1/manual.html#pdf-loadstring

Got the error when use LUA script to query a list

when I use Lua script to query a list, I got the correctly result if the list is not empty. But got error if the list is empty.
Blow is my script:
const char * sLuaQueryServers = "local key_list = redis.call('KEYS',
KEYS[1]); return(redis.call('MGET', unpack(key_list)))";
I passed the "serverlist:*" as the key, it's successfully returned the server in list.
But if there no server in redis, I got below error:
ERR Error running script (call to
f_88620231033e13635dc3181f2947a740f91012dc): #user_script:1: #user_script:
1: Wrong number of args calling Redis command From Lua script
"
Please help.
To your question, add a check that the list isn't empty before calling MGET, e.g.:
local key_list = redis.call('KEYS', KEYS[1])
if #key_list > 0 then
return(redis.call('MGET', unpack(key_list)))
else
return nil
end
Note #1: no need for semicolons in Lua
Note #2: Using KEYS isn't recommended for anything, except debugging
Note #3: You're using the KEYS table to pass an argument, but since your script is running KEYS (the command) that's really a moot point

How to execute batch file silently in windows background

i have a batch file which helps to start my rails server.when i am starting my batch file the command prompt is opening but here i need the cmd should not visible to user or it will execute at windows background.I am explaining mt .bat file code below.
c:
cd c:\\Site\swargadwara_puri
rails server
Please help me.
You could run it silently using a Vbscript file instead. The Run Method allows you running a script in invisible mode. Create a .vbs file like this one :
Option Explicit
Dim MyBatchFile
MyBatchFile = "C:\New Floder\toto 1.bat"
Call Run(MyBatchFile,1,False) 'Showing the console
Call Run(MyBatchFile,0,False) 'Hidding the console
'*********************************************************************************
Function Run(MyBatchFile,Console,bWaitOnReturn)
Dim ws,Result
Set ws = CreateObject("wscript.Shell")
'A value of 0 to hide the MS-DOS console
If Console = 0 Then
Result = ws.run(DblQuote(MyBatchFile),Console,bWaitOnReturn)
If Result = 0 Then
'MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
'A value of 1 to show the MS-DOS console
If Console = 1 Then
Result = ws.run(DblQuote(MyBatchFile),Console,bWaitOnReturn)
If Result = 0 Then
'MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function
'*********************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************************
The second argument in this example sets the window style. 0 means "hide the window, and 1 means "show the window"
Complete syntax of the Run method:
object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
Arguments:
object: WshShell object.
strCommand: String value indicating the command line you want to run. You must include any parameters you want to pass to the executable file.
intWindowStyle: Optional. Integer value indicating the appearance of the program's window. Note that not all programs make use of this information.
bWaitOnReturn: Optional. Boolean value indicating whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).
You can minimize the batch command, for example using:
START /MIN rails server

Getting return status AND program output

I need to use Lua to run a binary program that may write something in its stdout and also returns a status code (also known as "exit status").
I searched the web and couldn't find something that does what I need. However I found out that in Lua:
os.execute() returns the status code
io.popen() returns a file handler that can be used to read process output
However I need both. Writing a wrapper function that runs both functions behind the scene is not an option because of process overhead and possibly changes in result on consecutive runs. I need to write a function like this:
function run(binpath)
...
return output,exitcode
end
Does anyone has an idea how this problem can be solved?
PS. the target system rung Linux.
With Lua 5.2 I can do the following and it works
-- This will open the file
local file = io.popen('dmesg')
-- This will read all of the output, as always
local output = file:read('*all')
-- This will get a table with some return stuff
-- rc[1] will be true, false or nil
-- rc[3] will be the signal
local rc = {file:close()}
I hope this helps!
I can't use Lua 5.2, I use this helper function.
function execute_command(command)
local tmpfile = '/tmp/lua_execute_tmp_file'
local exit = os.execute(command .. ' > ' .. tmpfile .. ' 2> ' .. tmpfile .. '.err')
local stdout_file = io.open(tmpfile)
local stdout = stdout_file:read("*all")
local stderr_file = io.open(tmpfile .. '.err')
local stderr = stderr_file:read("*all")
stdout_file:close()
stderr_file:close()
return exit, stdout, stderr
end
This is how I do it.
local process = io.popen('command; echo $?') -- echo return code of last run command
local lastline
for line in process:lines() do
lastline = line
end
print(lastline) -- the return code is the last line of output
If the last line has fixed length you can read it directly using file:seek("end", -offset), offset should be the length of the last line in bytes.
This functionality is provided in C by pclose.
Upon successful return, pclose() shall return the termination status
of the command language interpreter.
The interpreter returns the termination status of its child.
But Lua doesn't do this right (io.close always returns true). I haven't dug into these threads but some people are complaining about this brain damage.
http://lua-users.org/lists/lua-l/2004-05/msg00005.html
http://lua-users.org/lists/lua-l/2011-02/msg00387.html
If you're running this code on Win32 or in a POSIX environment, you could try this Lua extension: http://code.google.com/p/lua-ex-api/
Alternatively, you could write a small shell script (assuming bash or similar is available) that:
executes the correct executable, capturing the exit code into a shell variable,
prints a newline and terminal character/string onto standard out
prints the shell variables value (the exit code) onto standard out
Then, capture all the output of io.popen and parse backward.
Full disclosure: I'm not a Lua developer.
yes , your are right that os.execute() has returns and it's very simple if you understand how to run your command with and with out lua
you also may want to know how many variables it returns , and it might take a while , but i think you can try
local a, b, c, d, e=os.execute(-what ever your command is-)
for my example a is an first returned argument , b is the second returned argument , and etc.. i think i answered your question right, based off of what you are asking.

Resources