How do I copy the image files from my resource directory to documents directory?
This is I've tried so far, this is working but the copied image file is not formatted as image file, so I can't use it.
local path = system.pathForFile( "mypicture.png", system.ResourceDirectory )
local cfile = assert(io.open(path, "rb"))
if cfile then
local imagedata = file:read("*a")
io.close(file)
local pathTo = system.pathForFile("mypicture.png", system.DocumentsDirectory)
local file = io.open( pathTo, "w")
file:write( imagedata )
io.close( file )
file = nil
else
return nil
end
Any other way to copy images from the resource directory?
you can try this
--checking if file exist
function doesFileExist( fname, path )
local results = false
local filePath = system.pathForFile( fname, path )
--filePath will be 'nil' if file doesn't exist and the path is 'system.ResourceDirectory'
if ( filePath ) then
filePath = io.open( filePath, "r" )
end
if ( filePath ) then
print( "File found: " .. fname )
--clean up file handles
filePath:close()
results = true
else
print( "File does not exist: " .. fname )
end
return results
end
--copy file to another path
function copyFile( srcName, srcPath, dstName, dstPath, overwrite )
local results = false
local srcPath = doesFileExist( srcName, srcPath )
if ( srcPath == false ) then
return nil -- nil = source file not found
end
--check to see if destination file already exists
if not ( overwrite ) then
if ( fileLib.doesFileExist( dstName, dstPath ) ) then
return 1 -- 1 = file already exists (don't overwrite)
end
end
--copy the source file to the destination file
local rfilePath = system.pathForFile( srcName, srcPath )
local wfilePath = system.pathForFile( dstName, dstPath )
local rfh = io.open( rfilePath, "rb" )
local wfh = io.open( wfilePath, "wb" )
if not ( wfh ) then
print( "writeFileName open error!" )
return false
else
--read the file from 'system.ResourceDirectory' and write to the destination directory
local data = rfh:read( "*a" )
if not ( data ) then
print( "read error!" )
return false
else
if not ( wfh:write( data ) ) then
print( "write error!" )
return false
end
end
end
results = 2 -- 2 = file copied successfully!
--clean up file handles
rfh:close()
wfh:close()
return results
end
--copy 'readme.txt' from the 'system.ResourceDirectory' to 'system.DocumentsDirectory'.
copyFile( "readme.txt", nil, "readme.txt", system.DocumentsDirectory, true )
this is the reference of the code http://docs.coronalabs.com/guide/data/readWriteFiles/index.html#copying-files-to-subfolders
There is error in your code, local imagedata = file:read("*a") must be local imagedata = cfile:read("*a") same in the next line.
Other than that, the code looks valid and should work fine.
Related
p . pginfo = function ( frame )
local title = tostring(frame.args.title) or ""
local ttlobj = mw.title.new( title )
local txt = ttlobj.text
if ttlobj.exists then
if ttlobj .isRedirect then
txt = txt .. " exists and is a redirect"
else
txt = txt .. " exists and is not a redirect"
end
else
txt = txt .. " does not exist"
end
return txt
end
{{#invoke:Sandbox/Shreyansh Saboo|pginfo|title=}}
I am getting error how can I solve the error??
Please help me out with it.
I get an "upvalue error" while I try to play audio in my app.
I have 2 files:
sound_board.lua
local enemy_damaged = audio.loadSound( "assets/audio/enemy_damaged.wav" )
local ouch = audio.loadSound( "assets/audio/ouch.wav" )
local pew = audio.loadSound( "assets/audio/pew.wav" )
local function playSound(to_play)
audio.play( to_play )
end
level1.lua
local sound_board = require("sound_board")
-- some code
function fireSinglebullet()
sound_board:playSound(pew) -- line 295
-- some other code
end
At launch I get this error:
level1.lua:295: attempt to index upvalue 'sound_board' (a boolean value)
What's wrong?
Look carefully what you return in sound_board.lua file. Error message tells that local variable sound_board in level.lua is a boolean value.
To get access to variables from another file use modules like that:
-- sound_board.lua
local M = {}
M.sounds = {
"enemy_damaged" = audio.loadSound( "assets/audio/enemy_damaged.wav" )
"ouch" = audio.loadSound( "assets/audio/ouch.wav" )
"pew" = audio.loadSound( "assets/audio/pew.wav" )
}
function M:playSound( to_play )
audio.play( self.sounds[to_play] )
end
return M
and
-- level1.lua
local sound_board = require( "sound_board" )
-- some code
function fireSinglebullet()
sound_board:playSound( "pew" ) -- line 295
-- some other code
end
Read more: External Modules in Corona
I am currently making an app in corona SDK. My goal for now is to create something (like a string or Boolean) that could be stored in a .txt file. What I want to do is in one, let us say for example scores.lua file have all the values and then, when in need use them in the main.lua file. The problem is that the main.lua does not get the files that I saved in scores.lua.
I am using something called ego.lua
function saveFile( fileName, fileData )
local path = system.pathForFile( fileName, system.DocumentsDirectory )
local file = io.open( path, "w+" )
if file then
file:write( fileData )
io.close( file )
end
end
function loadFile( fileName )
local path = system.pathForFile( fileName, system.DocumentsDirectory )
local file = io.open( path, "r" )
if file then
local fileData = file:read( "*a" )
io.close( file )
return fileData
else
file = io.open( path, "w" )
file:write( "empty" )
io.close( file )
return "empty"
end
end
and what I save in my main.lua file:
ego = require "ego"
saveFile = ego.saveFile
loadFile = ego.loadFile
valueName = loadFile( "gucci.txt" )
local money = display.newText(tostring(valueName), 200, 100, "Helvetica", 20)
and my score.lua file :
ego = require "ego"
saveFile = ego.saveFile
loadFile = ego.loadFile
saveFile( "gucci.txt", "This works")
I recommended you Simple-Table-Load-Save-Functions-for-Corona-SDK - Two very simple load and save function to store a Lua Table and Read it back in. Requires the Corona SDK JSON Library.
I have 2 different Lua files, main.lua and game_model.lua. I'm trying to save some details in a JSON file (I googled that using a JSON file would be the best way to save a user's settings and score), but I'm getting the following error:
Error: File: main.lua
Line: 11
Attempt to index local 'game' (a boolean value)
Why is am I getting this error and how can fix it?
Here is the code in my main.lua:
--Main.lua
display.setStatusBar( display.HiddenStatusBar )
local composer = require( "composer" )
local game = require("data.game_model")
myGameSettings = {}
myGameSettings.highScore = 1000
myGameSettings.soundOn = true
myGameSettings.musicOff = true
myGameSettings.playerName = "Andrian Gungon"
game.saveTable(myGameSettings, "mygamesettings.json")
composer.gotoScene("scripts.menu")
game_model.lua (in the data subdirectory) contains this code:
--game_model.lua (located at data/game_model.lua)
local json = require("json")
function saveTable(t, filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local file = io.open(path, "w")
if (file) then
local contents = json.encode(t)
file:write( contents )
io.close( file )
return true
else
print( "Error!" )
return false
end
end
function loadTable(filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if (file) then
local contents = file:read( "*a" )
myTable = json.decode(contents);
io.close( file )
return myTable
end
return nil
end
It means that the module data.game_model did not return anything when it was loaded.
In this case, require returns true.
To fix the problem identified in lhf's answer, you can put your table saving and loading functions in a table that is returned by data.game_model, like this:
-- Filename: data/game_model.lua
local model = {}
local json = require("json")
function model.saveTable( t, filename )
-- code for saving
end
function model.loadTable( filename )
-- code for loading
end
return model
Note also that a common mistake would be to declare the functions as model:saveTable( t, fn ) instead of model.saveTable( t, fn ). Remember, the former is syntactic sugar for model.saveTable( model, t, fn ).
Now the variable game in local game = require( "data.game_model" ) should be initialized to a table containing your functions. You can easily check this:
local game = require("data.game_model")
print( type( game ) )
for k,v in pairs(game) do
print(k,v)
end
Produces output like:
table
loadTable function: 0x7f87925afa50
saveTable function: 0x7f8794d73cf0
Use code below to save/load. All code comes from github/robmiracle.
local M = {}
local json = require("json")
local _defaultLocation = system.DocumentsDirectory
local _realDefaultLocation = _defaultLocation
local _validLocations = {
[system.DocumentsDirectory] = true,
[system.CachesDirectory] = true,
[system.TemporaryDirectory] = true
}
function M.saveTable(t, filename, location)
if location and (not _validLocations[location]) then
error("Attempted to save a table to an invalid location", 2)
elseif not location then
location = _defaultLocation
end
local path = system.pathForFile( filename, location)
local file = io.open(path, "w")
if file then
local contents = json.encode(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
function M.loadTable(filename, location)
if location and (not _validLocations[location]) then
error("Attempted to load a table from an invalid location", 2)
elseif not location then
location = _defaultLocation
end
local path = system.pathForFile( filename, location)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
myTable = json.decode(contents);
io.close( file )
return myTable
end
return nil
end
function M.changeDefault(location)
if location and (not location) then
error("Attempted to change the default location to an invalid location", 2)
elseif not location then
location = _realDefaultLocation
end
_defaultLocation = location
return true
end
function M.print_r ( t )
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
elseif (type(val)=="string") then
print(indent.."["..pos..'] => "'..val..'"')
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
if (type(t)=="table") then
print(tostring(t).." {")
sub_print_r(t," ")
print("}")
else
sub_print_r(t," ")
end
print()
end
M.printTable = M.print_r
return M
Usage
local loadsave = require("loadsave")
myTable = {}
myTable.musicOn = false
myTable.soundOn = true
loadsave.saveTable(myTable, "myTable.json")
I am creating a game and need to write the gamedata to a file. I have the game creating the file if its not there and reading the contents of the file (That I put in manually) but I can not get it to write to the file.
local path = system.pathForFile("gameData.gameData", system.DocumentsDirectory)
local myFile
defaultGameData = "It Worked"
if (path) then
myFile = io.open(path, "r")
end
if(myFile) then
print('file')
else
myFile:close()
--io.close(myFile)
myFile = io.open(path, 'w')
myFile:write( "My Test" )
io.close(myFile)
end
myFile = nil
That part works. i then move to the next scene and attempt to write something new
local saveData = "My app state data"
local path = system.pathForFile("gameData.gameData", system.DocumentsDirectory)
local myfile = io.open( path, "w" )
myfile:write( saveData )
io.close( myfile )
But get the error
mainMenu.lua:43: attempt to index local 'myfile' (a nil value)
I know the file is there in the sandbox, and this code was copied from the corona docs. What am I doing wrong???
here are two functions I am using
function SaveTable(t, filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local contents = JSON.encode(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
function LoadTable(filename, dir)
if (dir == nil) then
dir = system.DocumentsDirectory;
end
local path = system.pathForFile( filename, dir)
local contents = ""
local myTable = {}
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
myTable = JSON.decode(contents);
io.close( file )
return myTable
end
return nil
end
Usage:
local t = {
text = "Sometext",
v = 23
};
SaveTable(t, "filename.json");
local u = LoadTable("filename.json");
print(u.text);
print(u.v);
Enjoy!
The error occurs due to the mistake in your code line:
myFile:close()
So either comment the line as:
--myFile:close()
Or do as below (only if you need):
myFile = io.open(path, 'w')
myFile:close()
Keep Coding............. :)
I found the solution. I opened the file to read to see if the file exists. I forgot to close it again before I reopened it in the if statement if the file did exist. I only closed it if it didnt exist.