Implement stdio.readToEnd API

This commit is contained in:
Filip Tibell 2024-04-18 22:10:08 +02:00
parent 4a28499aaa
commit 753897222a
No known key found for this signature in database
2 changed files with 34 additions and 1 deletions

View file

@ -2,7 +2,7 @@ use mlua::prelude::*;
use dialoguer::{theme::ColorfulTheme, Confirm, Input, MultiSelect, Select};
use mlua_luau_scheduler::LuaSpawnExt;
use tokio::io::{self, AsyncWriteExt};
use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use crate::lune::util::{
formatting::{
@ -21,6 +21,7 @@ pub fn create(lua: &Lua) -> LuaResult<LuaTable<'_>> {
.with_function("format", stdio_format)?
.with_async_function("write", stdio_write)?
.with_async_function("ewrite", stdio_ewrite)?
.with_async_function("readToEnd", stdio_read_to_end)?
.with_async_function("prompt", stdio_prompt)?
.build_readonly()
}
@ -53,6 +54,21 @@ async fn stdio_ewrite(_: &Lua, s: LuaString<'_>) -> LuaResult<()> {
Ok(())
}
/*
FUTURE: Figure out how to expose some kind of "readLine" function using a buffered reader.
This is a bit tricky since we would want to be able to use **both** readLine and readToEnd
in the same script, doing something like readLine, readLine, readToEnd from lua, and
having that capture the first two lines and then read the rest of the input.
*/
async fn stdio_read_to_end(lua: &Lua, _: ()) -> LuaResult<LuaString> {
let mut input = Vec::new();
let mut stdin = io::stdin();
stdin.read_to_end(&mut input).await?;
lua.create_string(&input)
}
async fn stdio_prompt(lua: &Lua, options: PromptOptions) -> LuaResult<PromptResult> {
lua.spawn_blocking(move || prompt(options))
.await

View file

@ -58,6 +58,11 @@ end
stdio.write("World! ")
stdio.write("All on the same line")
stdio.ewrite("\nAnd some error text, too")
-- Reading from stdin, either line-by-line or the entire input
local firstLine = stdio.readLine()
local secondLine = stdio.readLine()
local remaining = stdio.readToEnd()
```
]=]
local stdio = {}
@ -143,4 +148,16 @@ function stdio.write(s: string) end
]=]
function stdio.ewrite(s: string) end
--[=[
@within Stdio
@tag must_use
Reads the entire input from stdin.
@return The input from stdin
]=]
function stdio.readToEnd(): string
return nil :: any
end
return stdio