load file in lua - lua

I have directory that contain multiple file
i need to load on specified file.
i know i can use loadfile(path) but how i need to specify which file to load
thank you
Jp

I'm not 100% sure I understand what you are asking, but here's my take on it. If you know the directory you need to load the file from, you'd just prefix it to the name of the file:
local f, error = loadfile(mydir .. "/my_file")
Note that this reads and parses the file. To actually execute it, you need to invoke the function you get back from loadfile() (so f() in this example). If there is an error, loadfile() returns nil and an error message.

path = "./path/to/a/file.lua"
local myreturn1, myreturn2 --[[etc]] = assert(loadfile(path))(myarg1, myarg2, myarg3 --[[etc]])

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

Attempt to index local 'file' (a nil value)?

I'm doing a project in corona simulator that involves reading some data in from a csv file ("car.csv") that is in the project directory, I have this code that is supposed to read the first line in, but when I run it it gives me the error "Attempt to index local 'file' (a nil value)". Any idea how I can fix this?
local function init()
local path = system.pathForFile( "car.csv", system.DocumentsDirectory );
local file = io.open(path, "r");
line = file:read();
print(line);
end
For some reason it won't read it in to 'file'.
Edit: Ok if I use the full path rather than the relative file path it works. But I need to use the relative one and I don't know why it doesn't work.
When using io.open, you should always make sure that it actually succeeded before trying to read the file, or you will get an ugly "attemp to index nil" error.
If you want your program to still crash, just do
local file = assert(io.open(path, 'r'))
And it will give you a more helpful error message if the file can't be found. Alternatively, you could also manualle save the return values of io.open and check for errors:
local file, err, code = assert(io.open(path))
if not file then
print("Error opening file", path, err)
-- Do something to handle the error
end

Access Denied when creating file in Visual F#

The following code runs without a hitch:
On the other hand, I get an access-denied error with this:
The destination is in my personal folder and I have full control. The directory is not read-only. Anyway, in either of those cases, the first code sample should not run either! I appreciate the help ...
In the second sample, you have two problems:
There are back slashes instead of forward slashes, so some of them may get interpreted as escape sequences.
You completely ignore the first parameter of write and specify what I assume is a folder as destination. You can't open a file stream on a folder, no wonder you get access denied.
This should work:
let write filename (ms:MemoryStream) =
let path = System.IO.Path.Combine( "C:/Users/<whatever>/signal_processor", filename )
use fs = new FileStream( path, FileMode.Create )
ms.WriteTo(fs)

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.

Writing a file to a specific path in ruby taking the file name from excel

I am having some trouble writing a file to a specific path taking the file name from excel. Here is the code which I am using
out_file = File.new (#temp_path/ "#{obj_info[3].to_s}","w")
"#{obj_info[3].to_s}" = sample.txt
The value sample.txt comes from Excel during run time
#temp_path = "C:/Users/Somefolder/"
The error displayed is:
NoMethodError: undefined method `[]' for nil:NilClass
However, if the code is:
out_file = File.new ("#{obj_info[3].to_s}","w")
it successfully creates a file called sample.txt in the default directory. However, I want it to be stored in a specific directory and the file name needs to be passed from Excel.
Any help is much appreciated.
I believe your problem is because there a space between / and "
#temp_path/ "#{obj_info[3].to_s}
and I guess you want to build a path.
My advice is that you use File.join
f_path = File.join(#temp_path,obj_info[3].to_s)
out_file = File.new (f_path,"w")
Let me know if that solved the problem
You have 2 problems:
obj_info is nil so you make an error reading the value from excel, the error you get indicates it is on an array, in the code you published the only thing that's an array is what you read from excel.
Print the contents with p obj_info right before your code to check.
#temp_path and {obj_info[3].to_s} need to be concatenated to make a path.
You can do that with File.join like Mauricio suggests or like this
out_file = File.new ("#{#temp_path}/#{obj_info[3]}","w")
You can drop the to_s in this case.
It would be better if you publish the whole of your script that is meaningful.

Resources