I'm struggling with a permission error in Lua when trying to read/write from/to a text file. As you can see below, I've pulled the error message from the io.open function and I'm getting "file.txt: permission denied". If it helps at all, I'm using Mac OSX Yosemite and the Love2D engine.
function fileWrite()
outputFile, error = io.open("new.txt", "w")
if outputFile then
for k,v in pairs(clicks) do
outputFile:write(tostring(v[1]) .. "," .. tostring(v[2]) .. "\n")
end
outputFile:close()
else
errorText = error
end
end
Am I making a silly error somewhere by any chance? I've dealt with writing to files in Lua before (on Windows 7), and I've never had this problem before.
Any feedback would be greatly appreciated! :)
In LÖVE your game shouldn't be interacting directly with the file system through io. Instead uselove.filesystem.newFile so your assets will still be available within a .love (zip) file. This should also handle the permission issues your having on OS X as it will write to /Users/user/Library/Application Support/LOVE/ to which love will have write permissions.
function fileWrite()
outputFile, error = love.filesystem.newFile("new.txt")
if outputFile:open("w") then
outputFile:write("Hello World!")
outputFile:close()
else
print(error)
end
end
Check your current directory. For OS X and Linux like systems:
require "os"
print( os.getenv("PWD") )
You do not have access to the file system where the application is running.
Related
I'm writing a Mac OS program, and I have the following lines:
os.execute("cd ~/testdir")
configfile = io.open("configfile.cfg", "w")
configfile:write("hello")
configfile:close()
The problem is, it only creates the configfile in the scripts current directory instead of the folder I have just cd' into. I realised this is because I'm using a console command to change directory, then direct Lua code to write the file. To combat this I changed the code to this:
configfile = io.open("~/testdir/configfile.cfg", "w")
However I get the following result:
lua: ifontinst.lua:22: attempt to index global 'configfile' (a nil value)
stack traceback:
ifontinst.lua:22: in main chunk
My question is, what's the correct way to use IO.Open to create a file in a folder I have just created in the users home directory?
I appreciate I'm making a rookie mistake here, so I apologise if you waste your time on me.
You have problems with ~ symbol. In your os.execute("cd ~/testdir") is the shell who interprets the symbol and replaces it by your home path. However, in io.open("~/testdir/configfile.cfg", "w") is Lua who receives the string and Lua doesn't interprets this symbol, so your program tries to open a file in the incorrect folder. One simple solution is to call os.getenv("HOME") and concatenate the path string with your file path:
configfile = io.open(os.getenv("HOME").."/testdir/configfile.cfg", "w")
In order to improve error messages I suggests you to wrap io.open() using assert() function:
configfile = assert( io.open(os.getenv("HOME").."/testdir/configfile.cfg", "w") )
I have a file called backup.lua, which the program should write to every so often in order to backup its status, in case of a failure.
The problem is that the program writes the backup.lua file completely fine first-time round, but any other times it refuses to write to the file.
I tried removing the file while the program was still open but Windows told me that the file was in use by 'CrysisWarsDedicatedServer.exe', which is the program. I have told the host Lua function to close the backup.lua file, so why isn't it letting me modify the file at will after it has been closed?
I can't find anything on the internet (Google actually tried to correct my search) and the secondary programmer on the project doesn't know either.
So I'm wondering if any of you folks know what we are doing wrong here?
Host function code:
function ServerBackup(todo)
local write, read;
if todo=="write" then
write = true;
else
read = true;
end
if (write) then
local source = io.open(Root().."Mods/Infinity/System/Read/backup.lua", "w");
System.Log(TeamInstantAction:GetTeamScore(2).." for 2, and for 1: "..TeamInstantAction:GetTeamScore(1))
System.LogAlways("[System] Backing up serverdata to file 'backup.lua'");
source:write("--[[ The server is dependent on this file; editing it will lead to serious problems.If there is a problem with this file, please re-write it by accessing the backup system ingame.--]]");
source:write("Backup = {};Backup.Time = '"..os.date("%H:%M").."';Backup.Date = '"..os.date("%d/%m/%Y").."';");
source:write(XFormat("TeamInstantAction:SetTeamScore(2, %d);TeamInstantAction:SetTeamScore(1, %d);TeamInstantAction:UpdateScores();",TeamInstantAction:GetTeamScore(2), TeamInstantAction:GetTeamScore(1) ));
source:close();
for i,player in pairs(g_gameRules.game:GetPlayers() or {}) do
if (IsModerator(player)) then
CMPlayer(player, "[!backup] Completed server backup.");
end
end
end
--local source = io.open(Root().."Mods/Infinity/System/Read/backup.lua", "r"); Can the file be open here and by the Lua scriptloader too?
if (read) then
System.LogAlways("[System] Restoring serverdata from file 'backup.lua'");
--source:close();
Backup = {};
Script.LoadScript(Root().."Mods/Infinity/System/Read/backup.lua");
if not Backup or #Backup < 1 then
System.LogAlways("[System] Error restoring serverdata from file 'backup.lua'");
end
end
end
Thanks all :).
Edit:
Although the file is now written to the disk fine, the system fails to read the dumped file.
So, now the problem is that the "LoadScript" function isn't doing what you expect:
Because I'm psychic, i have divined that you're writing a Crysis plugin, and are attempting to use it's LoadScript API call.
(Please don't assume everyone here would guess this, or be bothered to look for it. It's vital information that must form part of your questions)
The script you're writing attempts to set Backup - but your script, as written - does not separate lines with newline characters. As the first line is a comment, the entire script will be ignored.
Basicallty the script you've written looks like this, which is all treated as a comment.
--[[ comment ]]--Backup="Hello!"
You need to write a "\n" after the comment (and, I'd recommend in other places too) to make it like this. In fact, you don't really need block comments at all.
-- comment
Backup="Hello!"
I am working on porting a project in Windows over to OSX. I have overcome issues with VBA for OSX Word 2011 not allowing you to send POSTs to a server and have figured out how to return a string result from an external script. Now I have to insert an image in my Word file from a URL that is built using the return of my external script.
The current attempt is as follows, and works in Windows but crashes Word in OSX:
Selection.InlineShapes.AddPicture FileName:=File_Name, _
LinkToFile:=False, SaveWithDocument:=True
After doing some research, it looks like MS may have disabled this functionality in OSX as a "security risk". I still need to make it work. Does anybody know of a way within VBA for Office 2011 to make this work, or barring that a workaround? I am trying to avoid writing the image file to the disk if possible.
UPDATE: I have created a Python script for getting the image file from a URL, but I still do not know how to get this image from the Python script into VBA, and from there into the Word document at the location of the cursor. The important bits of the script are below. The image is read in as a PIL object and I can show it using img.show() just fine, but I am not sure what filetype this is or how to get VBA to accept it.
# Import the required libraries
from urllib2 import urlopen, URLError
from cStringIO import StringIO
from PIL import Image
# Send request to the server and receive response, with error handling!
try:
# Read the response and print to a file
result = StringIO(urlopen(args.webAddr + args.filename).read())
img = Image.open(result)
img.show()
except URLError, e:
if hasattr(e, 'reason'): # URL error case
# a tuple containing error code and text error message
print 'Error: Failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # HTTP error case
# HTTP error code, see section 10 of RFC 2616 for details
print 'Error: The server could not fulfill the request.'
print 'Error code: ', e.code
Note that in the above, args.webAddr and args.filename are passed to the script using the argparse library. This script works, and will show the image file that I expect. Any ideas on how to get that image into Word 2011 for OSX and insert it under the cursor?
Thanks a lot!
Edit: updated the link to the project since migrating to github.
Old question, but no answer, and I see the same crash here when the image is at an http URL. I think you can use the following workaround
Sub insertIncludePictureAndUnlink()
' Put your URL in here...
Const theImageURL As String = ""
Dim f As Word.Field
Dim r As Word.Range
Set f = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldIncludePicture, Text:=Chr(34) & theImageURL & Chr(34), PreserveFormatting:=False)
Set r = f.Result
f.Unlink
Set f = Nothing
' should have an inlineshape in r
Debug.Print r.InlineShapes.Count
' so now you can do whatever you need, e.g....
r.Copy
Set r = Nothing
End Sub
I am running a Rails (3.2.3) application with Ruby 1.9.3p194 on the basic Ubuntu lucid32 image in a Vagrant virtual box. The virtual box is running on Leopard, for what it's worth. I'm trying to use rubyzip in the application to decompress a zip archive - 2009_da_lmp.zip. Using code directly from examples in the rubyzip repository, I can confirm that I can list the archive file contents:
#f is the absolute path to 2009_da_lmp.zip (string)
Zip::ZipFile.open(f) { |zf| zf.entries[0] }
=> 20090101_da_lmp.csv #that is indeed a file in the archive.
Using some more code from the examples in the repository, I try to get at an actual file in the archive:
Zip::ZipInputStream.open(f) { |zis|
entry = zis.get_next_entry
print "first line of '#{entry.name}' (#{entry.size} bytes: ) "
puts "'#{zis.gets.chomp}'" }
=> first line of '20090101_da_lmp.csv' (826610 bytes: ) Zlib::DataError:
invalid stored block lengths #and a long stack trace I can provide
#if that might help
The Mac OS decompression utility unzips the archive fine. I was wondering if it was some kind of encoding-related thing (my locale is set to en_US.UTF-8 because to make using PostgreSQL in dev less painful), but I don't know how to tell if that's the case. I can't find any information on what might cause this error.
This is a typical error found when feeding random data to an inflater. In fact you will get this error about 1/4 of the time from random data (when the low three bits of the first byte are 000 or 001). So I would guess that the inflation is simply starting at the wrong byte for some reason.
Within a Oracle Forms trigger I am using the host command to make a directory on the file server. An example of this part of my code is below:
HOST ('mkdir'||:GLOBAL.DIRECTORY_PATH||'\FERTILIZER\'||ADDY);
I need to have the error code returned to me if the directory is not created on the server. Any suggestions of the code I need to add?
Thank you.
FORM_SUCCESS will return FALSE if the command fails for any reason (unless you're on Windows 95 in which case it will still return TRUE).
HOST('...');
IF NOT FORM_SUCCESS THEN
MESSAGE('something went wrong');
END IF;
If you are looking for the actual OS level error code, then you are out of luck. The aforementioned answer from Jeffrey Kemp
is the best you will get.
If you are having failures, keep in mind that the HOST built-in runs on the machine that actually runs the form (normally the application server). So, your command must be valid for the particular OS of the application server.
Also, and you may have figured this out already, in your example, 'mkdir'||:GLOBAL.DIRECTORY_PATH||'\FERTILIZER\'||ADDY
could result in your command having no space between the command - mkdir and the string, resulting in a failed command.
You still can get the error message by using this statement HOST(vCommand || ' > error.txt');