跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[程序员] 凹语言开发 WebAssembly 应用 3 分钟入门

发表于

凹语言是国内首个面向 WebAssembly 设计通用编程语言,也是目前被 CNCF 基金会 wasm 全景图 收录的的唯一一个来自中国的开源编程语言项目。凹语言项目诞生时的一个愿景就是简化 WebAssembly 网页应用的开发。这里我们将展示如何快速开启一个 WebAssembly 应用。

1. 安装凹语言命令行

凹语言采用 Go 语言实现,目前可以通过以下 Go 命令安装最新的凹语言命令行:

$ go install wa-lang.org/wa@master

安装完成后输出wa命令查看帮助信息。

2. 初始化凹语言工程

通过wa init命令初始化一个名为hello的工程。

3. 编译并执行凹语言程序

hello目录对应的命令行环境通过wa run命令编译并执行:

$ wa run
listen at http://localhost:8000
...

该命令在编译得到 wasm 文件后,会在 output 命令启动一个 web 服务。然后通过以上网址可以访问index.html页面。效果如下:

st0053-01.png

在开发者控制台窗口输出了“你好,凹语言!”和5050结果。

4. 定制 html 页面

打开网页看到的是1+2+3+...+100 = 5050,这是在output/index.html网页调用Sum函数计算的结果。index.html文件如下:

<!DOCTYPE html>
<html lang="en">
<body>
  <pre id="output"></pre>
  <script type="text/javascript" src="./hello.js"></script>

  <script>
    let app = new WaApp();
    app.init().then((result) => {
      app.main();
      document.getElementById('output').innerText = `1+2+3+...+100 = ${app.Sum(100)}`;
    })
  </script>
</body>
</html>

首先是通过hello.js胶水代码初始化wasm模块,得到了WaApp对象。然后通过app.init()执行凹语言的init初始化代码,然后通过app.main()执行main函数代码。app.Sum对应的是导出的Sum函数,然后将计算结果更新到页面的output区域。

5. 凹语言版本的 Brainfuck 解释器

在 “st0013:凹语言、图灵机和 BF 语言” 文章中,我们介绍过用凹语言写了一个命令行版本的 Brainfuck 解释器,现在可以将其改造为网页版本。

首先是修改 main.wa 导出 Run 函数,代码在 (waroot/examples/brainfuck)。在线测试地址: https://wa-lang.org/wa/brainfuck/,执行效果如下:

st0053-02.png

6. 展望

WebAssembly 是一个非常有前景的基础技术,但是至少使用门槛较高。凹语言作为面向 WebAssembly 设计的通用语言,希望通过简化流程让大家更方便地使用该技术从而享受技术发展带来的红利。也希望对该技术方向感兴趣的同学一起共建。


完整文章: https://wa-lang.org/smalltalk/st0053.html

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.