Search code examples
textluaconsole

How can I make each character in a string sequentially appear in the console like in a game? (Lua)


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

Solution

  • 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