Skip to content

Instantly share code, notes, and snippets.

@kkharji
Created February 16, 2022 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkharji/abc24155ee745364f9daf308654986a8 to your computer and use it in GitHub Desktop.
Save kkharji/abc24155ee745364f9daf308654986a8 to your computer and use it in GitHub Desktop.
pub fn create_query_table<'lua>(
lua: &'lua Lua,
scope: &str,
socket_path: &str,
) -> LuaResult<LuaTable<'lua>> {
let scope_with_dashes = format!("--{scope}");
let query_all = vec!["query".to_owned(), scope_with_dashes.clone()];
let mut scope_singler = scope_with_dashes;
let mut query_single = query_all.clone();
scope_singler.pop();
query_single.push(scope_singler);
let scope = scope.to_string();
let socket_path = socket_path.to_string();
let table = lua.create_table()?;
table.set("name", scope.to_string())?;
table.set("socket_path", socket_path.to_string())?;
table.set(
"current",
lua.create_function(move |_, _: ()| {
Ok(request::native(&socket_path, &query_single)
.map_err(LuaError::external)?)
})?,
)?;
if scope.as_str() != "windows" {
for i in 1..10 {
table.set::<i32, LuaFunction>(
i,
lua.create_function(|_, _: ()| {
Ok(request::native(&socket_path, &query_single)
.map_err(LuaError::external)?)
})?,
);
}
};
let mtable = lua.create_table()?;
mtable.set(
"__call",
lua.create_function(move |_, t: LuaTable| {
let socket_path = t.get::<_, String>("socket_path")?;
Ok(request::native(socket_path, &query_all)
.map_err(LuaError::external)?)
})?,
)?;
table.set_metatable(Some(mtable));
Ok(table)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment