Lua io.write() not working - lua

I am using a luvit Lua environment to run my lua code through my control panel. I am looking to write to a .txt file, but with the simple code that i am running, its not working.
The reason I wish to write to a .txt file is to log notices from my Discord Bot I am working on in the Discordia library.
I have a folder called MezzaBOT. In this file i have a write.lua file and also a log.txt file. I have this simple code in my write.lua file:
io.output('log.txt')
io.write('hello\n')
io.close()
I then run in my command promt with Luvit environment:
>luvit Desktop\mezzabot\write.lua
I don't get any errors but the log.txt file continues to stay empty. Am I missing a line in my code, or do i need to access log.txt differently?
edit: my new code is the following
file = io.open('log.txt')
file:write('hello', '\n')
file:close()
and it is not making a new line for each time with \n
edit B:
Ok, i found my problem, its creating a log.txt in my C:\Users\PC.
One other problem is when writing, its not making a new line with the \n. Can someone please help me?

Lua, by default, opens files in read mode. You need to explicitly open a file in write mode if you want to write to it (see manual)
file = io.open('log.txt', 'w')
file:write('hello', '\n')
file:close()
Should work :)

Related

Using io.tmpfile() with shell command, ran via io.popen, in Lua?

I'm using Lua in Scite on Windows, but hopefully this is a general Lua question.
Let's say I want to write a temporary string content to a temporary file in Lua - which I want to be eventually read by another program, - and I tried using io.tmpfile():
mytmpfile = assert( io.tmpfile() )
mytmpfile:write( MYTMPTEXT )
mytmpfile:seek("set", 0) -- back to start
print("mytmpfile" .. mytmpfile .. "<<<")
mytmpfile:close()
I like io.tmpfile() because it is noted in https://www.lua.org/pil/21.3.html :
The tmpfile function returns a handle for a temporary file, open in read/write mode. That file is automatically removed (deleted) when your program ends.
However, when I try to print mytmpfile, I get:
C:\Users\ME/sciteLuaFunctions.lua:956: attempt to concatenate a FILE* value (global 'mytmpfile')
>Lua: error occurred while processing command
I got the explanation for that here Re: path for io.tmpfile() ?:
how do I get the path used to generate the temp file created by io.tmpfile()
You can't. The whole point of tmpfile is to give you a file handle without
giving you the file name to avoid race conditions.
And indeed, on some OSes, the file has no name.
So, it will not be possible for me to use the filename of the tmpfile in a command line that should be ran by the OS, as in:
f = io.popen("python myprog.py " .. mytmpfile)
So my questions are:
Would it be somehow possible to specify this tmpfile file handle as the input argument for the externally ran program/script, say in io.popen - instead of using the (non-existing) tmpfile filename?
If above is not possible, what is the next best option (in terms of not having to maintain it, i.e. not having to remember to delete the file) for opening a temporary file in Lua?
You can get a temp filename with os.tmpname.
local n = os.tmpname()
local f = io.open(n, 'w+b')
f:write(....)
f:close()
os.remove(n)
If your purpose is sending some data to a python script, you can also use 'w' mode in popen.
--lua
local f = io.popen(prog, 'w')
f:write(....)
#python
import sys
data = sys.stdin.readline()

Dynamically use current date in OUTPUT EXPORT filename

Stripped down example code using a static file name:
OUTPUT EXPORT /CONTENTS EXPORT=ALL /PDF DOCUMENTFILE='example.pdf'
My question is how to generate a datestamped file. I have tried using $DATE, '$DATE' and running it through a macro but can't seem to find the syntax.
Hey this is a really nice Idea for saving backups in a running syntax production - I will use this myself from now on :) .
So the following syntax works for me:
compute tdy= $time.
formats tdy (date11).
temporary.
select if $casenum=1.
write out="somepath\datemacro.sps" /"define !dated__filename () !quote(!concat('YOUR FILE NAME',' ','", tdy, "','.pdf')) !enddefine.".
exe.
Insert file ="somepath\datemacro.sps".
delete vars tdy.
The file name you used in the code above is now stored in a macro with the date added, and you can use it here:
OUTPUT EXPORT /CONTENTS EXPORT=ALL /PDF DOCUMENTFILE= !dated__filename .
Note that you can change "YOUR FILE NAME" into anything you like, including adding a path. And you can also change ".pdf" so save other kinds of files.
EDIT: Also of course change "somepath" to a valid path on your machine.

Read Files Using Lua by Directory Using Command Prompt

I was trying to read a .txt file using lua in command prompt, I'm using 'Lua For Windows' but in the way I tried it's not working, it don't give me any error, it don't return anything, not even 'nil'.
I tried this:
file = io.open("C:\Users\user\Desktop\a.txt", "r") --(and my user's name)
io.input(file)
print(io.read())
io.close(file)
The backslash is an escape character in Lua quoted strings.
Try "C:\\Users\\user\\Desktop\\a.txt".
Or avoid the issue using long strings: [[C:\Users\user\Desktop\a.txt]].

Set Owner+Access-rights with io.open

In a lua-script (for Domoticz # Raspberry) I apply the following script-segment to generate an htm-file and to put it in the designated folder.
Line02text till Line30text are variables which are dynamically filled elsewhere in the lua-script.
file = io.open("/home/pi/domoticz/scripts/lua/XXXXX.htm", "w+")
-- Opens a file named XXXXX.htm (stored under the designated sub-folder of Domoticz)
-- in append mode
-- write lines to opened file
file:write("SOF<br>")
file:write(Line02text .. "<br>")
file:write(Line03text .. "<br>")
....
file:write(Line29text .. "<br>")
file:write(Line30text .. "<br>")
file:write("EOF<br>")
file:close() -- closes the open file
All seems OK, because the htm-file appears as planned.
Next steps would be to copy the file to different folder, open in browser, etc..
But Owner of the htm-file is 'root' and Permission is 0640.
For further application Owner should be different, and Permission e.g. 777.
Trying manual change or use of chmod results in report 'Permission denied' by server.
Question:
How to set (as result of the lua-script) different Owner and other Permission for the htm-file?
Lua's target is to be as portable as possible, and ownership/permissions management is very os-specific. There's no embedded functions to handle that.
You'll need to expose some native function that will do what you need with files' permissions. Or use some already existing library for that, like maybe lua-fs: (https://github.com/clementfarabet/lua-fs-0.3)

Produce a download file from CGI in Lua

I am writing a simple CGI program in lua. What I want to achieve is produce a response from CGI which enables a file to be downloaded from the browser. But I just can't print the data. I have no idea what's going on here. Here is the code below:
print("Content-Type: text/html; charset=UTF-8")
print("Content-Length:" .. sys.getenv("CONTENT_LENGTH"))
print("Content-Disposition:",'attachment;filename="backup.tar.gz"\n')
print("Content-Type:application/x-tar-gz\n\n")
file=io.popen("some command")
output = file:read('*a')
print(output)
--file:close()
The problem is I just can't print the output whose content is binary. I can see the type of output is string.
What is the problem? Please give some hints about it. Thank you.
ADD : I have no idea about this and Where is the issue. Let me put more info about the command I want run. But I don't think that matters.
Actually, I work in openwrt, the web server uhttpd. (No LuCI here)
The command is:sysupgrade -b - 2>/dev/null. This command is used to backup the config file. I want to write a CGI to download the backup file from the web.
But I can not print the output to the server. Even in the terminal(in lua IDE) I cannot print out the output except one or two messy code. But I can write the output to a file in terminal. Maybe it has some relationship with the content of out.
When I print the content line by line, it prints some, but not all of it. After I download the file. I can't open it.
print("Content-Disposition:",'attachment;filename="backup.tar.gz"\n')
print("Content-Type:application/x-tar-gz\n\n")
I think you have way too many new lines. First of all, you can newline in Content-Disposition and this is in addition to the newline that print adds, which ends the headers and makes Content-Type a part of the payload (which breaks the content). You also have two newlines in Content-Type where you only need one (as one is added by the print command).
I think something like this should work:
local file = io.popen("some command")
local output = file:read('*a')
file:close()
print("Content-Type: text/html; charset=UTF-8")
print("Content-Length: " .. #output)
print("Content-Disposition: " .. 'attachment;filename="backup.tar.gz"')
print("Content-Type: application/x-tar-gz\r\n")
print(output)

Resources