1

I'm trying to write a function in Lua, which essentially is supposed to write out each character sequentially to the console after given a piece of text as the input parameter each time the function is called. So for example, if I call the function and put "Hello World" as the parameter, I want the function to sequentially print out each character to the console one at a time (with a given amount of time between each character, therefore creating a kind of "flow" of letters). The function that I've been working on technically does what I want it to, however it doesn't display any text at all until the loop is completely done iterating over each character in the string. So if I wanted to display "hello" to console with one second between each character being printed, it would take roughly 5-6 seconds before any text at all would appear (and when it did, it would be the full string). I've tried re-organizing the function in any way I can think of, but I can't think of any other way to sequentially output each character without a loop. Is this just a Lua problem? I've seen this same general question but for C#, and it appears they both work in the same way (How to make text be "typed out" in console application?). Also, for the record, I'm coding in an online IDE called "repl.it" and I haven't abandoned the idea that that might be a problem. Thanks in advance.

--[[ Delay function --]]
function wait(seconds)
    local start = os.time()
    repeat until os.time() > start + seconds
end


--[[ Function for "saying" things --]]
function say(string)
  speakchar = {}
  speakindex = 1;
  for c in (string):gmatch"." do
    table.insert(speakchar, c);
    io.write(speakchar[speakindex])
    wait(1);
    speakindex = speakindex + 1;
  end
  print("");
end
edubugi
  • 13
  • 2
  • Add `io.flush()` after `io.write`. – lhf Apr 21 '21 at 16:02
  • No need to store the chars in a table btw. Just `io.write(c)`will do. – lhf Apr 21 '21 at 16:03
  • Oh wow thank you so much! It totally worked! I'll get rid of that table as well, thanks a bunch! – edubugi Apr 21 '21 at 16:05
  • I strongly suggest to build your own wait() with C - If you are on linux you can do it by: https://stackoverflow.com/questions/67112973/embedded-lua-5-4-2-link-errors/67115641#67115641 - That dont bring your CPU fans to noisy ;-) - And you can easy make waits lower than one second – koyaanisqatsi Apr 23 '21 at 15:24

1 Answers1

2

You need to flush the output buffer. Here is the simplified code:

function say(string)
  for c in (string):gmatch"." do
    io.write(c):flush()
    wait(1);
  end
  io.write("\n")
end
lhf
  • 70,581
  • 9
  • 108
  • 149