how to use lua to get all files from desktop - lua

I am making a project with lua that gets a list of all the file names from your desktop in lua. however, I can't figure out how to do it, and I am also going to be using love2d for it, because it is going to be a game. can you tell me how to do it? thanks!
Here is the code
function love.load()
require "player"
-- Lets add Some Variables!
-- Some Directory Suff first for Variables...
DesktopDirectory = love.filesystem.getUserDirectory().."Desktop"
DesktopFiles = love.filesystem.getDirectoryItems(DesktopDirectory)
-- These are the Images!
images = {
background = love.graphics.newImage("gfx/desktop.png")
}
players = {Player.New(50, 300, 40, 40, "gfx/stickman.png", true)}
love.graphics.setBackgroundColor(100, 220, 255)
for k in pairs(DesktopFiles) do
print(DesktopFiles[k])
end
end
function love.keypressed(k)
if k == "j" then
players[1].jump()
end
end
function love.update(dt)
for i in pairs(players) do
players[i].update()
end
end
function love.draw()
love.graphics.draw(images.background)
for i in pairs(players) do
players[i].draw()
end
end

Love2D (tries to) sandbox file system access, you're not supposed to touch anything outside your game's code or the "save directory" (where anything that you write goes). In particular, the Desktop folder is also out of reach. If you try to use love.filesystem.getDirectoryItems on that path, you'll just get an empty table. Same for other functions – they'll just refuse to work.
The easiest way to get that functionality is to include lfs and use its functions together with Lua's base io library for general file system access.

Related

Why the lua function io.write() did not work. It only display the results on the terminal, rather than writing to a file

I am learning the Lua IO library. I'm having trouble with io.write(). In Programming Design in Lua, there is a piece of code that iterates through the file line by line and precedes each line with a serial number.
This is the file I`m working on:
test file: "iotest.txt"
This is my code
io.input("iotest.txt")
-- io.output("iotest.txt")
local count = 0
for line in io.lines() do
count=count+1
io.write(string.format("%6d ",count), line, "\n")
end
This is the result of the terminal display, but this result cannot be written to the file, whether I add IO. Output (" iotest.txt ") or not.
the results in terminal
This is the result of file, we can see there is no change
The result after code running
Just add io.flush() after your write operations to save the data to the file.
io.input("iotest.txt")
io.output("iotestout.txt")
local count = 0
for line in io.lines() do
count=count+1
io.write(string.format("%6d ",count), line, "\n")
end
io.flush()
io.close()
Refer to Lua 5.4 Reference Manual : 6.8 - Input and Output Facilities
io.flush() will save any written data to the output file which you set with io.output
See koyaanisqatsi's answer for the optional use of file handles. This becomes especially useful if you're working on multiple files at a time and gives you more control on how to interact with the file.
That said you should also have different files for input and output. You'll agree that it doesn't make sense to read and write from and to the same file alternatingly.
For writing to a file you need a file handle.
This handle comes from: io.open()
See: https://www.lua.org/manual/5.4/manual.html#6.8
A file handle has methods that acts on self.
Thats the function after the : at file handle.
So io.write() puts out on stdout and file:write() in a file.
Example function that can dump a defined function to a file...
fdump=function(func,path)
assert(type(func)=="function")
assert(type(path)=="string")
-- Get the file handle (file)
local file,err = io.open(path, "wb")
assert(file, err)
local chunk = string.dump(func,true)
file:write(chunk)
file:flush()
file:close()
return 'DONE'
end
Here are the methods, taken from io.stdin
close = function: 0x566032b0
seek = function: 0x566045f0
flush = function: 0x56603d10
setvbuf = function: 0x56604240
write = function: 0x56603e70
lines = function: 0x566040c0
read = function: 0x56603c90
This makes it able to use it directly like...
( Lua console: lua -i )
> do io.stdout:write('Input: ') local result=io.stdin:read() return result end
Input: d
d
You are trying to open the same file for reading and writing at the same time. You cannot do that.
There are two possible solutions:
Read from file X, iterate through it and write the result to another file Y.
Read the complete file X into memory, close file X, then delete file X, open the same filename for writing and write to it while iterating through the original file (in memory).
Otherwise, your approach is correct although file operations in Lua are more often done using io.open() and file handles instead of io.write() and io.read().

Can't get PlayerSay working in Gmod lua addon

I have tried making a Garry's Mod lua file to look for messages containing "/discord" at the beginning of them and save that message as a text file in the same directory, I'm not familliar to lua files so I am unsure of syntax but when I look at console, nothing happens, when I look at the server command line, nothing happens and no new file is created, I even serached my entire PC.
I used the following page on the Garry's mod wiki: https://wiki.garrysmod.com/page/GM/PlayerSay and the code given there works but as soon as I added anything, it stopped working completely. Here is my code:
hook.Add( "PlayerSay", "GmodToDiscord", function( player, text, team )
if ( string.sub( string.lower( text ), 0, 7 ) == "/discord" ) then -- Makes message lowercase to be read by the program.
local file = io.open("message.txt", "w") -- Opens a text file in write mode.
file:write(message) -- Pastes in the message.
file:close() -- Closes the text file.
end
end)
Any help would be greatly appreciated.
You cannot use Lua's io library within Gary's mod. Use the Gary's Mod's file module instead.
https://wiki.garrysmod.com/page/file/Open
Example:
local f = file.Open( "cfg/mapcycle.txt", "r", "MOD" )
print( f:ReadLine() )
print( f:ReadLine() )
print( f:Tell() )
f:Close()
A thing to note about Lua, and what makes it a rather whacky language, is that it's arrays begin at index 1. You will need to check between 1 and 8 to get your tags; that should help you get started on #Piglet's implementation of the file IO.
Good luck, and happy modding!

Lua emulating the require function

In the embeded lua environment (World of Warcraft - WoW) is missing the require function.
I want port one existing lua source code (an great OO-library) for the use it in the WoW. The library itself is relatively small (approx 8 small files) but of course it heavily uses the require.
World of Warcraft loads files and libraries by defining it in an XML file, like:
<Ui xsi:schemaLocation="http://www.blizzard.com/wow/ui/">
<Script file="LibOne.lua"/>
<Script file="LibTwo.lua"/>
</Ui>
but i don't know how the low level library manipulation is done in the WoW.
AFAIK in the WoW is missing even the package. table too. :(
So the question(s): For me, the streamlined way would be write an function which will emulate the require function using the interface available in WoW. The question is how. Could someone give me some directions?
Or as alternative, for the porting the mentioned existing source to WoW, I need replace the require Some.Other.Module lines in the lua sources to something what WoW will understand. What is the equivalent/replacement for such require Some.Module in the WoW?
How the WoW handles modules/libraries at low-level?
You could merge all files into one using one of the various amalgamation scripts, e.g. amalg. Then you can load this file and a stub that implements the require function using the usual WoW way:
<Ui xsi:schemaLocation="http://www.blizzard.com/wow/ui/">
<Script file="RequireStub.lua"/>
<Script file="AllModules.lua"/><!-- amalgamated Lua modules -->
<Script file="YourCode.lua"/>
</Ui>
The file RequireStub.lua could look like:
package = {}
local preload, loaded = {}, {
string = string,
debug = debug,
package = package,
_G = _G,
io = io,
os = os,
table = table,
math = math,
coroutine = coroutine,
}
package.preload, package.loaded = preload, loaded
function require( mod )
if not loaded[ mod ] then
local f = preload[ mod ]
if f == nil then
error( "module '"..mod..[[' not found:
no field package.preload[']]..mod.."']", 1 )
end
local v = f( mod )
if v ~= nil then
loaded[ mod ] = v
elseif loaded[ mod ] == nil then
loaded[ mod ] = true
end
end
return loaded[ mod ]
end
This should emulate enough of the package library to get you a working require that loads modules in the amalgamated file. Different amalgamation scripts might need different bits from package, though, so you probably will have to take a look at the generated Lua source code.
And in the specific case of Coat you might need to implement stubs for other Lua functions as well. E.g. I've seen that Coat uses the debug library ...
WoW environment doesn't have dofile or any other means to read external files at all. You need to explicitly mention all files that must be loaded in .toc file or .xml referenced from .toc.
You can then write your own implementation of require to maintain compatibility with your library, which would be quite trivial as it would only need to parse module name and retrieve it's content from modules.loaded table, but you'd still need to alter original source to make files register in that table and you'll need to manually arrange all files into correct order of loading.
Alternatively you can rearrange files into separate WoW-addons and use its own built-in Dependencies/OptionalDeps facilities or popular LibStub framework to handle loading order automatically.

Require LUA files using a standard relative path approach - problems with: attempt to call global 'myfunc' (a nil value)

I need to call a LUA function, defined in another my .lua file; from another. So, what I want is the classic C/C++ include approach.
I tried with the following:
(file funcs.lua)
function myfunc(arg1, arg2)
..dosomething
end
and
(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
require "funcs"
myfunc(1, 2)
The require works good, but at execution I get this error:
attempt to call global 'myfunc' (a nil value)
How come?
Thanks in advance,
Thank you all for the comments; I'm running LUA under OpenResty/Nginx.
I solved by exporting directly the function(s), I don't know if this is the preferred method, but I noticed that is used by lots of newer LUA modules.
For example, I changed the code as follows:
file (funcs.lua)
local A = {}
function A.myfunc(arg1, arg2)
..dosomething
end
return A
(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
funcs = require "funcs"
funcs.myfunc(1, 2)
This works good and it's nice to have every function to be manually exported, in a sort of OOP-style.

Corona adding collision and playing a sound

EDIT: Ignore most the below as the problem seems to be I don't have the "movieclip" module loaded according to the debugger... how in the hell do you load the movieclip or physics module I have wrote code for both and that is the issue. Is this module included? do I download it from somewhere? what gives?
I have the following code in Lua (corona specifically)
function scene:createScene( event )
local group = self.view
local bg = display.newImage("stage.png")
local vio = display.newImage("vio.png")
vio.x = 150
vio.y = 180
local b = display.newImage("b.png")
b.x = -70
b.y = 200
end
I need there to be a touch screen event so that dragging left or right moves object B left or right on the horizontal axis..and detects it crossing the center of the screen and plays an sound...
I found some code that would do this as a movieclip but the example code
local myAnim = movieclip.newAnim( b.png )
local function pressFunction()
myAnim.alpha = 0.7
end
local function releaseFunction()
myAnim.alpha = 1
end
myAnim:setDrag()
drag=true,
onPress=pressFunction,
onRelease=releaseFunction,
bounds= { 50,200, 220, 200}
end
Also I added the local movieclip = requires (movieclip) at the top of my code and it removes all my background images and tabBar :(
Please help me figure this out I am new to Corona and Lua.
Physics is part of the core Corona SDK API. You should not have to include any external files. Simply adding:
local physics = require("physics")
at the top of the module where you plan to use physics should suffice. As #speeder said, the movieclip.lua module has been deprecated in favor of using the new sprite sheets. Personally I loved using movieclip, but it's pretty wasteful on memory and isn't nearly as efficient or functional as sprite sheets.
Movieclip is a ancient thing...
It is a library, that used now deprecated and obsolete parts of the API.
I wonder even how you found it (I never had heard of it until seeing your question, and had to dig some forum skills to figure what it was).
So, yes, movieclip is a separate .lua file that you need to find and download. But I suggest you don't do that, since it uses things that don't exist anymore.

Resources