Rainmeter's "Quote" plugin allows you to read a text file and return a random line from the file on every update. The plugin actually opens and rereads the file on every update, which is great if you have a file that is constantly being updated with new information. Otherwise, however, this is a waste of resources, and could take a toll on your hard drive if your skin is updating too frequently.
This script approximates the behavior of the Quote plugin when returning random lines from a single file, but only reads the file once, when the skin is loaded or refreshed.
PROPERTIES = {
PathName = '';
}
function Initialize()
tLines = {}
for line in io.lines(PROPERTIES.PathName) do
table.insert(tLines, line)
end
end
function Update()
return tLines[math.random(#tLines)]
end
I think I can also replicate the rest of the Quote plugin's abilities if/when the LuaFileSystem library becomes available. This would not only allow us to use Quote-esque features with dynamic variables, but also give us much finer control over its performance without mucking around with C++. So consider this an ongoing pet project. :)
You don't need to open a file to use io.lines, and thus do not need to close it. Also, you can just use #tLines to see how many lines are in the table instead of your iNumberOfLines approach.
PROPERTIES = {
PathName = '"';
}
function Initialize()
tLines = {}
for line in io.lines(PROPERTIES.PathName) do
table.insert(tLines, line)
end
end
function Update()
return tLines[math.random(#tLines)]
end
GitHub | DeviantArt | Tumblr
This is the song that never ends. It just goes on and on my friends. Some people started singing it not knowing what it was, and they'll continue singing it forever just because . . .
There are a lot of ways to skin the "file" cat in Lua, and the only trick is to not mix two different approaches on one file / read / write construct.
I personally prefer:
MyFile = io.open('Path/SomeFile.txt', 'r')
if not MyFile then print('Can't open file: Path/SomeFile.txt'); return 'File Error'; end
for FileLine in MyFile:lines() do
...
end
MyFile:close()
The reasons are that first, you can easily test for an error condition as the file handle will not be created. Second, you can open and deal with more than one file at a time, where just using io.lines() restricts you to one. Third, it feels more readable to me as it is very specific about what file handle and thus what file is being used at all times.
I was wondering how to deal with such an error. That should work perfectly.
GitHub | DeviantArt | Tumblr
This is the song that never ends. It just goes on and on my friends. Some people started singing it not knowing what it was, and they'll continue singing it forever just because . . .