当前位置:网站首页>Simple application example of rhai script engine
Simple application example of rhai script engine
2022-06-30 23:58:00 【ruonou. com】
In the last article , A brief introduction Rhai Role and function of script engine , See Rhai - Rust Embedded script engine .
In this article, we start with the simplest string Application , Let's see Rhai How easy it is to write scripts . Mainly from three application points : stay Rust Call embedded Rhai Script ; independent Rhai Script ;web In terms of development , Combined template engine , call Rhai Script , Render the template .
- stay Rust Call embedded Rhai Script
First , We will be having Cargo.toml Add dependencies in :
[dependencies]
rhai = "0.19.10"then , stay Rust In the code , So we can do some research on the embedded Rhai Script for calculation . The example is to calculate the number in the string
use rhai::{Engine, EvalAltResult, INT};
fn main() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
let result = engine.eval::<INT>("40 + 2")?;
println!(" The result of the calculation is :{}", result); // Will print 42
Ok(())
}The result of the calculation can be passed on to others Rust Code 、Rhai Script , And others Python Script 、web Front end, etc , and Rust The code is basically the same .
- independent Rhai Script
The following example is pure Rhai Script example , It is also string processing , Please note that Rhai As no-std Of Rust The script engine , Introduces the dynamic type , So it's written with Rust The code is very similar , But it's easier : Easy to write 、 Easy to read .
// This script tests string operations
print(" Hello! !"); // Be careful Rust In the code , Use macros print! or println!
print(" such \n very \\ Great !"); // Embed newline
print("40 16 Into the system for :\x40"); // Convert to 16 Base number
print("unicode:\u2764"); // Unicode
print("unicode:\U0001F603"); // Unicode
print(" Chengdu " + "->" + " sanya "); // Use strings to build strings
print("foo" < "bar"); // String comparison ,Rhai Only support ==、<、> etc.
print(" you " >= " you "); // String comparison ,Rhai China does not support it. eq、lt、gt etc.
print(" The output is :" + 42); // Use a string of non string type to build
let s = "\u2764 hello, world! \U0001F603"; // String variable
print(" length =" + s.len); // The result is printed as 17
s[s.len-3] = '?'; // Modify string
print(" Change the result to :" + s); // Will print ' Change the result to :hello, world?'- Combined template engine , call Rhai Script , Render the template
The following example is in support of Rhai Script parsing ( Template dependency crate contain Rhai) In the template engine of , Use independent Rhai Script for rendering assistance .
First , In response to the template handler in , We need to register the script assistant , You can register multiple . We register for the following example 2 individual , The template rendering is processed separately according to the user's personal site category , Show the corresponding site svg, And handle the user blog name :
pub async fn user_index(req: Request<State>) -> tide::Result {
let mut user_tpl: Tpl = Tpl::new("users/index").await;
user_tpl.reg.register_script_helper_file(
"website-svg",
format!("{}{}", rhai_dir().await, "website-svg.rhai"),
)?;
user_tpl.reg.register_script_helper_file(
"blog-name",
format!("{}{}", rhai_dir().await, "blog-name.rhai"),
)?;
...
...then , independent Rhai Script website-svg.rhai by :
let website = params[0];
let is_github = website.contains("github.com");
if is_github {
"M8 0C3.58 0 0 3.58 0 ..."
} else {
"M6.5 14.5v-3.505c0-...."
}
Script blog-name.rhai We have omitted .
Last , In the template file ( namely html、jinja2、hbs etc. ) in , We use a method similar to variable parsing to call :
<div class="col-4 text-center">
<a class="blog-header-logo text-dark" href="{{ user.website }}" target="_blank">
{{ blog-name user.blogName }}
<svg width="28" height="28" viewBox="0 0 18 18" fill="currentColor">
<path d="{{ website-svg user.website }}" />
</svg>
</a>
</div>When rendering the template on the server , Template engine built-in rhai rely on crate Will be right rahi Script for calculation . And the first one in the text rhai Application way ——Rust Embed... In the code Rhai Script —— similar .
Application examples through three ways , We can find out :Rhai In terms of overall application scope , At present, it is still very narrow . also Besides the excellent performance , Other advantages are not particularly obvious .
Most of the experimenters are based on Rust Trust in language performance , So as to simplify the complex problems . For example, the author's current application , It also focuses on template rendering assistance .
For applications where performance is especially important ,Rhai The scripting engine is a very interesting one to consider . For other considerations , The technology stack will also have an option . Interested friends can visit the website :https://rhai.budshome.com, For a detailed understanding .
边栏推荐
- Pycharm is very fast to learn from installation to full armament. There are so many pictures because it is too detailed!
- 股票开户要如何办理呢?办理手机开户安全吗
- Lombok
- Prospects of world digitalization and machine intelligence in the next decade
- New trends of China's national tide development in 2022
- Makefile notes (Yiwen Institute makefile)
- 异步過渡方案—Generator
- Netease cloud sign in lottery? That year I could sign in for 365 days. No? Look.
- CentOS 6.3 x64 PHP 5.2.6 扩展安装OpenSSL出错的解决方法
- 8253A寄存器浅析
猜你喜欢

To tell you the truth, ThreadLocal is really not an advanced thing

8253A寄存器浅析

Netease cloud sign in lottery? That year I could sign in for 365 days. No? Look.

Which is better, server rental or hosting services in the United States?

BeanUtils. Copyproperties() vs. mapstruct

女朋友说:你要搞懂了MySQL三大日志,我就让你嘿嘿嘿!

What is SRM system and how to standardize the internal procurement process of the company

Zero sample and small sample learning

Fh6908a negative pole turn off synchronous rectification analog low voltage drop diode control IC chip tsot23-6 ultra low power rectifier 1W power consumption < 100ua static replacement mp6908

The girlfriend said: if you want to understand the three MySQL logs, I will let you heiheihei!
随机推荐
Achieve secure data sharing among multiple parties and solve the problem of asymmetric information in Inclusive Finance
How does the VR cloud exhibition hall bring vitality to offline entities? What are the functions?
6-1 exploit -ftp exploit
Mysql database query optimization
Explain kubernetes backup and recovery tools velero | learn more about carina series phase III
conv2d详解--在数组和图像中的使用
Combining online and offline, VR panorama is a good way to transform furniture online!
[NLP] [textcnn] text classification
异步过渡方案—Generator
Reason why wechat payment wxpaypubhelper V3 callback XML is empty
The college entrance examination in 2022 is over. Does anyone really think programmers don't need to study after work?
1. crawler's beautifulsoup parsing library & online parsing image verification code
JMeter cross thread parameter association requires no script
Qlineedit of QT notes (74) specifies the input type
2022-06-30:以下golang代码输出什么?A:0;B:2;C:运行错误。 package main import “fmt“ func main()
[designmode] singleton pattern
How do I open a stock account on my mobile phone? In addition, is it safe to open a mobile account?
76 page comprehensive solution 2022 for smart Logistics Park (download attached)
QQmlApplicationEngine failed to load component qrc:/main. qml:-1 No such file or directory
1175. 质数排列 / 剑指 Offer II 104. 排列的数目