I want to Search a file inside n number of sub folder (in windows environment).
Then copy that file and place in destination folder.
function search_and_copy(filename, src_folder, dest_folder)
local pipe = io.popen("reg query HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage /v ACP 2>nul:")
local acp = pipe:read("*a"):match"ACP%s+REG_SZ%s+(%d+)"
pipe:close()
local function search_recursively(path)
local src_filespec = path..filename
local file = io.open(src_filespec)
if file then
file:close()
return src_filespec
end
local subfolders = {}
local pipe = io.popen((acp and 'chcp '..acp..'|' or '')..'dir /b/ad "' ..path..'*.*" 2>nul:')
for line in pipe:lines() do
table.insert(subfolders, line)
end
pipe:close()
for _, subfolder_name in ipairs(subfolders) do
src_filespec = search_recursively(path..subfolder_name.."\\")
if src_filespec then
return src_filespec
end
end
end
local src_filespec = search_recursively(src_folder:gsub("/", "\\"):gsub("\\*$", "\\"))
if src_filespec then
os.execute('copy /b "'..src_filespec..'" "'..dest_folder:gsub("/", "\\"):gsub("\\*$", "\\")..filename..'" 1>nul: 2>&1')
end
end
-- find file.txt somewhere on drive C: and save it as D:\Found\file.txt
search_and_copy("file.txt", "C:\\", "D:\\Found")
Related
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'm trying to get the name of all the file saved in two folders, the name are saved as :
1.lua 2.lua 3.lua 4.lua and so on
the folders name are :
first folder : "/const/"
second folder: "/virt/"
what I'm trying to do is only get the number of the files and this works but not in the right order, when I get the 17 file for example I get the 17th delivered from the function before the 15 and this causes for me a problem here the code of the function that I'm using :
local virt_path = "/virt/"
local const_path = "/const"
local fs = require "lfs"
local const = {}
for num = 1, (numberoffile)do -- numberoffile is predfined and can't be change
const[num] = assert(
dofile (const_path .. mkfilename(num)),
"Failed to load constant ".. num ..".")
end
local function file_number() --this is the function that causes me a headach
local ci, co, num = ipairs(const)
local vi, vo, _ = fs.dir(virt_path)
local function vix(o)
local file = vi(o)
if file == nil then return nil end
local number = file:match("^(%d+).lua$")
if number == nil then return vix(o) end
return tonumber(number)
end
local function iter(o, num)
return ci(o.co, num) or vix(o.vo, num)
end
return iter, {co=co, vo=vo}, num
end
As I said the function delive the need return values but not the right Arithmetic order.
any idea what I'm doing wrong here ?
I use my path[1] library.
1 We fill table with filenames
local t = {}
for f in path.each("./*.lua", "n") do
t[#t + 1] = tonumber((path.splitext(f)))
end
table.sort(t)
for _, i in ipairs(t) do
-- do work
end
2 We check if files exists
for i = 1, math.huge do
local p = "./" .. i .. ".lua"
if not path.exists(p) then break end
-- do work
end
[1] https://github.com/moteus/lua-path
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.
I was wondering if there was a way to read data from a file or maybe just to see if it exists and return a true or false
function fileRead(Path,LineNumber)
--..Code...
return Data
end
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
local fileContent = read_file("foo.html");
print (fileContent);
Just a little addition if one wants to parse a space separated text file line by line.
read_file = function (path)
local file = io.open(path, "rb")
if not file then return nil end
local lines = {}
for line in io.lines(path) do
local words = {}
for word in line:gmatch("%w+") do
table.insert(words, word)
end
table.insert(lines, words)
end
file:close()
return lines;
end
There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.