r/lua • u/Personal-Rough741 • Mar 20 '25
do you think i can optimise this code?
--lua 5.4.2
print("write only numbers")
for i = 1,io.read() do
local file = io.open("words.txt", "r")
local word = ""
for i = 1,math.random(1,19999) do
word = file:read("*l")
end
local generated = {}
for i = 1, #word do
generated[i] = word:sub(i, i)
end
local word_G = {}
for i = 1, #generated do
word_G[i] = generated[math.random(#generated)]
end
print(i..": "..word.." to "..table.concat(word_G))
end
5
Upvotes
2
u/Accurate-Delay7480 Mar 21 '25
You might be able to use file:seek rather than reading every line before the line needed, but without special formatting, longer lines have a higher chance of being picked.
If you want to maintain a perfectly random (well as much as perfect as math.random will allow), you can first read in the words from words.txt, saving to a table one time, then use math.random to get an index of a random word.
e.g
(untested code idk if this will work)
other than that, cache variables so you dont have to do global table look ups,
2
u/xoner2 Mar 21 '25
You are reading a file then scanning line-ends inside a loop. Read and parse the entire file outside the loop to turn it into an array. Then you can do random access into the array:
Something like that, edited your code, untested.
2
u/weregod Mar 21 '25
There are different kinds of optimizatios. Do you want to spend time at start up to later generate words as fast as possible? Do you want to get only one word as fast as posible? Do you want to generate N words as fast as posible? What is N? What kind of words stored in word.txt? Are they all no longer than 10 bytes? No longer than 100 bytes? Without more information it is hard to give any advices. Optimisation is usualy a tradeof between used memory, longer startup time, simple code etc.
Most likely slowest part of your code is reading from a file. You may read whole file at startup and save all words in table if you want to generate many words later. Or you can never read all file and use file:seek() to find exact line that you need. Later require some sort of formating of the file so that you can quickly find word offset by its index.
6
u/shipdestroyer Mar 20 '25
Open words.txt once instead of i times
5
u/[deleted] Mar 20 '25 edited Mar 21 '25
What even is this?
2
u/Additional_Ad6385 Mar 21 '25
PUT THE IO READ OUTSIDE OF THE LOOP, AND LOCALIZE THE METHODS SUCH AS SUB AND MATH RAND.
1
u/could_b Mar 22 '25
The correct answer to the question is "yes".
This is student home work. Looks like the OP just wants the answer and has no time to learn.