Lua, Specify where to create files for io.open? - lua

How can I put the file created by io.open somewhere besides the folder the lua file is in.
local test = io.open("Test.html", "w")
test:write("Hello world.")
test:close()

Yoy simply supply a full path (or relative path) and not just a filename.
local test = io.open("c:\temp\Test.html", "w")

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()

Lua is refusing to read from a file

I typed up my code not expecting it to work first try, and of course it didn't. I kept tweaking it for hours on end, but I kept getting the same result until I made as simple as possible.
local file = io.open("File_Name", "r")
io.output(file)
local test = io.read('*all')
io.close(file)
print(test)
After getting (no return) from this, I've decided to take a break and let someone else answer my question.
The problem with your code is that you're trying to read from whatever is defined as your input file. You only opened a file, but you didn't tell Lua to use it as the input file, so io.read won't read from the opened file, yet.
local file = io.open(filename, "r")
local test = file:read("a")
io.close(file)
print(test)
Alternatively:
local file = io.open(filename, "r")
io.input(file)
local test = io.read("a")
io.close(file)
print(test)
or
local file = io.open(filename, "r")
local test = io.input(file):read("a")
io.close(file)
print(test)
Of course you should check wether opening the file succeeded befor using the file handle.
Depending on your Lua version the read format is either *a or a. I cannot remember if both is ok in all versions. At least that's what the manual says.

How to copy latest file from a directory using lua

I am trying to copy only latest file from a directory using lua file.
Latest file means : depends on modified time/created time.
How can i do this?
Referring to this question: How can I get last modified timestamp in Lua
You might be able to leverage the io.popen function to execute a shell command to get the name of the file. It seems like there's no builtin function that exposes filesystem metadata or stats. Something like this might work:
local name_handle = io.popen("ls -t1 | head -n 1")
local filename = name_handle:read()
I'm not familiar with Lua, but perhaps this helps. I imagine that once you have the name of the newest file you can use the other IO functions to do the copying.
local function get_last_file_name(directory)
local command = 'dir /a-d /o-d /tw /b "'..directory..'" 2>nul:'
-- /tw for last modified file
-- /tc for last created file
local pipe = io.popen(command)
local file_name = pipe:read()
pipe:close()
return file_name
end
local directory = [[C:\path\to\your\directory\]]
local file_name = get_last_file_name(directory)
if file_name then
print(file_name)
-- read the last file
local file = io.open(directory..file_name)
local content = file:read"*a"
file:close()
-- print content of the last file
print(content)
else
print"Directory is empty"
end

How do I make require() take a direct path to a file

so I have the following code, and the problem is that when I loop through each file in my array and try to require the file path, it gives me an error of the module isn't found.
local Commands = {}
function getCommands()
local readdir = fs.readdir
local readdirRecursive = require('luvit-walk').readdirRecursive
readdirRecursive('./Desktop/Discord/ArtifexBot/Discordia/resources/commands/', function(k, files)
for i,v in pairs(files) do
if v:match(".lua") and not v:match("commands.lua") then
local cmd = v:match("([^/]-)%..-$")
fs.readlink(v,function(err,thing)
print(err,thing)
end)
Commands[cmd] = require(v)
end
end
end)
end
getCommands()
The recursive function works, and the files are just strings of the path. But after research, require() needs a relative path, not a direct path. So I think I need to do something with fs to make the file path a relative path instead? I couldn't find the answer anywhere.
Thanks!
require doesn't take a path at all. The standard loaders simply use the string you give it in a sequence of patterns, in accord with its algorithm.
What you want is to load and execute a given Lua script on disk. That's not spelled require; that's spelled dofile.

Load Lua-files by relative path

If I have a file structure like this:
./main.lua
./mylib/mylib.lua
./mylib/mylib-utils.lua
./mylib/mylib-helpers.lua
./mylib/mylib-other-stuff.lua
From main.lua the file mylib.lua can be loaded with full path require('mylib.mylib'). But inside mylib.lua I would also like to load other necessary modules and I don't feel like always specifying the full path (e.g. mylib.mylib-utils). If I ever decide to move the folder I'm going to have a lot of search and replace. Is there a way to use just the relative part of the path?
UPD. I'm using Lua with Corona SDK, if that matters.
There is a way of deducing the "local path" of a file (more concretely, the string that was used to load the file).
If you are requiring a file inside lib.foo.bar, you might be doing something like this:
require 'lib.foo.bar'
Then you can get the path to the file as the first element (and only) ... variable, when you are outside all functions. In other words:
-- lib/foo/bar.lua
local pathOfThisFile = ... -- pathOfThisFile is now 'lib.foo.bar'
Now, to get the "folder" you need to remove the filename. Simplest way is using match:
local folderOfThisFile = (...):match("(.-)[^%.]+$") -- returns 'lib.foo.'
And there you have it. Now you can prepend that string to other file names and use that to require:
require(folderOfThisFile .. 'baz') -- require('lib.foo.baz')
require(folderOfThisFile .. 'bazinga') -- require('lib.foo.bazinga')
If you move bar.lua around, folderOfThisFile will get automatically updated.
You can do
package.path = './mylib/?.lua;' .. package.path
Or
local oldreq = require
local require = function(s) return oldreq('mylib.' .. s) end
Then
-- do all the requires
require('mylib-utils')
require('mylib-helpers')
require('mylib-other-stuff')
-- and optionally restore the old require, if you did it the second way
require = oldreq
I'm using the following snippet. It should work both for files loaded with require, and for files called via the command line. Then use requireRel instead of require for those you wish to be loaded with a relative path.
local requireRel
if arg and arg[0] then
package.path = arg[0]:match("(.-)[^\\/]+$") .. "?.lua;" .. package.path
requireRel = require
elseif ... then
local d = (...):match("(.-)[^%.]+$")
function requireRel(module) return require(d .. module) end
end
Under the Conky's Lua environment I've managed to include my common.lua (in the same directory) as require(".common"). Note the leading dot . character.
Try this:Here is my findings:
module1= require(".\\moduleName")
module2= dofile("..\\moduleName2.lua")
module3 =loadfile("..\\module3.lua")
To load from current directory. Append a double backslash with a prefix of a fullstop.
To specify a directory above use a prefix of two fullstops and repeat this pattern for any such directory.e.g
module4=require("..\\..\\module4")

Resources