Assign text file into a variable - lua

Is it possible to assign a text file into a variable and access the file by just calling the variable? If so, how do you do it?

Use the IO library
local input = assert(io.open(inputfile, "r"))
local data = f:read("*all")
--do some processing to data
local output = assert(io.open(outfule, "w"))
output:write(data)
input:close()
output:close()

Let's say you want to do as such from a function. You would have:
function writeToFile(_fileName) -- _fileName being the file you want to write to
local file = io.open(_fileName, "w")
file:write("This is a string that will be written to the file")
file:write("This is a second string")
file:flush( ) -- save the contents
file:close( ) -- stop accessing the file
end
If you only want to read the file then all you need to do is
function readFromFile(_fileName)
local file = io.open(_fileName, "r")
for line in file:lines() do
print(""..line.."\n")
end
end

If you mean "calling the variable" literally, then try this:
local filename="/etc/passwd"
local f=assert(io.open(filename,"r"))
getmetatable(f).__call = f.read
repeat
local s=f()
print(s)
until s==nil

Related

Is there a possiblity to create a variable with a string for everything inside of a table?

Just wondering about that, because i don't find a solution for it. Pretty sure because I'm new to this c: Thanks for your help.
Edit: for explanation im gonna explain it with the code a bit.
local FileList = fs.list("") --Makes a Table with all the files and directories available (as strings) on the PC it's running on (Inside of a mod called computercraft for minecraft)
for _, file in ipairs(FileList) do
--Here I need a function which assigns every string from the table to a variable, just for the explanation I'll call it unknown.function
unknown.function
end
while true do
print(a) --a is for example one of the different variables made from the "unknown.function"
sleep(1)
end
LIKE this?
AllFiles = {}
function Crazyfunction(file)
AllFiles[table.getn(AllFiles)+1] = file
end
local FileList = fs.list("")
for _, file in ipairs(FileList) do
Crazyfunction(file)
end
while true do
print(AllFiles[NUMBE_OF_FILE_HERE])
sleep(1)
end
You mean like this?
local FileList = fs.list("")
for _, file in ipairs(FileList) do
-- file is the variable which contains a string from the table.
print(file)
sleep(1)
end
What you want is... already what your loop does. You just added an extra loop for no reason.

Lua Sandbox "hacking"

So I use a program where I script mods in lua, the lua is in a sandbox state, meaning most functions are blocked like IO and OS, I can't even use REQUIRE to add libs.
I need to have a function that unzips files in one of my mods and I don't seem to find a way.
Is there anyway to do it?
If it's not possible in an easy way, is it possible to hack the program .exe or dlls to re-enable those functions in the lua?
Thank you in advance, Regards
There are decompression librarys in pure Lua, you should be able to embed these in any environment that allows loading Lua scripts: http://lua-users.org/wiki/CompressionAndArchiving
If you can't access any files at all, you could try a simple packer:
#!/usr/bin/env lua
local files = arg
local w = io.write
local function pack(...) return {...} end
w("files = {\n")
for i, filename in ipairs(arg) do
w('\t["' ..filename .. '"] = "')
local file = assert(io.open(filename, "r"), "Can't open file!")
local data = file:read("*a")
data = data:gsub("\a", "\\a")
:gsub("\\", "\\\\")
:gsub("\f", "\\f")
:gsub("\n", "\\n")
:gsub("\r", "\\r")
:gsub("\t", "\\t")
:gsub("\v", "\\v")
:gsub('"', '\\"')
:gsub("'", "\\'")
w(data, '",\n')
end
w("}\n")
w([[
function require(path)
local data = assert(files[path..".lua"], "file not found")
local func = assert(loadstring(data))
local _, ret = assert(pcall(func))
return ret
end
]])
w('require("', arg[1]:match("^(.-)%.lua$"),'")\n')
This should create a script like this:
$ ./packer.lua init.lua
files = {
["init.lua"] = "for k,v in pairs(arg) do\n\tprint(k,v)\nend\n",
}
function require(path)
local data = assert(files[path..".lua"], "file not found")
local func = assert(loadstring(data))
local _, ret = assert(pcall(func))
return ret
end
require("init")

reading special lines in lua

I am searching for the easiest way to read a string which is located in a file with a variable number of lines behind:
UserName=herecomesthestring
I thought about hardcoding a the linenumber, but this won't work, because in this file, the UserName can be more then once and the line numbers aren't the same (from user to user they may change).
Read the file line-by-line
Match the line and extract the username
Put it in a list
function getusers(file)
local list, close = {}
if type(file) == "string" then
file, close = io.open(file, "r"), true
end
for line in file:lines() do
local user, value = line:match "^([^=]+)=([^\n]*)$"
if user then -- Dropping mal-formed lines
table.insert(list, user)
list[user] = value -- Might be of interest too, so saving it
end
end
if close then
file:close()
end
return list
end
Call with either a file or a filename.
I edited the function above a bit, now it works more or less, just need to edit the RegEx.
function getusers(file)
local list, close = {}
local user, value = string.match(file,"(UserName=)(.*)")
print(value)
f:close()
end

Save a textarea into a file using lua

i have a webserver (uhttpd) that uses CGI with LUA.
I made a form with a textarea.
What i need is saving the content of the textarea on a file located in /etc/list.txt
I think that the LUA script have to read the POST variables, and then save them into a local file /etc/list.txt.
I already have the script for reading the file:
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
local file = '/etc/list.txt'
local lines = lines_from(file)
print ('<textarea name="mensaje" cols="40" rows="40">')
for k,v in pairs(lines) do
print(v)
end
print ("</textarea>")
This script shows me the content of file.txt onto the textarea.
Now i need a button "Save" that POST the textarea again into the file.
Thank you for your help and have a good day.
Small critique: lines_from files is overwriting a global variable lines every time it is called. That should be made local. Also opening and closing the file to see if it exists before reading it is wasteful. That operation can be folded into lines_from:
function lines_from(filename)
local lines = {}
local file = io.open(filename)
if file then
for line in file:lines(file) do
lines[#lines + 1] = line
end
file:close();
end
return lines
end
In your case there's no reason to even read the text as lines. Just read all the file's text:
function text_from(filename)
local text = ''
local file = io.open(filename)
if file then
text = file:read('*a')
file:close();
end
return text
end
local file = 'test.lua'
local text = text_from(file)
print ('<textarea name="mensaje" cols="40" rows="40">')
print(text)
print ("</textarea>")
To write the text back to the file, just reverse the procedure, opening the file in "w+" mode (replace existing data):
function save_text_to(filename, text)
local file = io.open(filename, 'w+')
if file then
text = file:write(text);
file:close();
end
end
save_text_to('foo', text)

Lua os.execute return value

Is it possible to read the following from the local variable in Lua?
local t = os.execute("echo 'test'")
print(t)
I just want to achieve this: whenever os.execute returns any value, I would like to use it in Lua - for example echo 'test' will output test in the bash command line - is that possible to get the returned value (test in this case) to the Lua local variable?
You can use io.popen() instead. This returns a file handle you can use to read the output of the command. Something like the following may work:
local handle = io.popen(command)
local result = handle:read("*a")
handle:close()
Note that this will include the trailing newline (if any) that the command emits.
function GetFiles(mask)
local files = {}
local tmpfile = '/tmp/stmp.txt'
os.execute('ls -1 '..mask..' > '..tmpfile)
local f = io.open(tmpfile)
if not f then return files end
local k = 1
for line in f:lines() do
files[k] = line
k = k + 1
end
f:close()
return files
end
Lua's os.capture returns all standard output, thus it will be returned into that variable.
Example:
local result = os.capture("echo hallo")
print(result)
Printing:
hallo
Sorry,
but this is impossible.
If the echo programm exit with success it will return 0. This returncode is what the os.execute() function get and returned too.
if 0 == os.execute("echo 'test'") then
local t = "test"
end
This is a way to get what you want, i hope it helps you.
Another Tip for getting the return code of a function is the Lua reference.
Lua-Reference/Tutorial

Resources