Skip to content

Run Method ​

After initializing the VM and configuring your desired capabilities, you can load your bytecode and start the execution process.

Using TypeScript ​

For TypeScript, you can pass raw bytecode arrays directly to the loader. It is recommended to use optimizeBytecode beforehand to ensure the VM runs the most efficient version of your instructions.

ts
import { Capability, LightVM } from 'lightvm';

const vm = new LightVM({ caps: [Capability.Control] });
const tools = vm.tools();

const raw = [
  ['push', 5],
  ['val', 'x'],
  ['set', 'x'],
  ['get', 'x'],
  ['println'],
];

const optimized = tools.optimizeBytecode(raw);
vm.load(optimized).run();

Using Rust ​

In Rust, you typically work with serialized bytecode strings (or serde_json). Similar to the TypeScript implementation, always optimize your bytecode before loading it into the VM to maintain optimal performance.

rust
use lightvm::LightVM;
use lightvm::types::{capability::Capability, vmconfig::VmConfig};

fn main() {
  let mut vm = LightVM::new(VmConfig {
    caps: vec![Capability::Control],
    ..Default::default()
  });
  let tools = vm.tools();

  let raw = r#"[
    ["push", 5],
    ["val", "x"],
    ["set", "x"],
    ["get", "x"],
    ["println"]
  ]"#;

  let optimized = tools.optimize_bytecode(raw);
  vm.load(optimized.clone())
    .run(None);
}
rust
use lightvm::LightVM;
use lightvm::types::{capability::Capability, vmconfig::VmConfig};

fn main() {
  let mut vm = LightVM::new(VmConfig {
    caps: vec![Capability::Control],
    ..Default::default()
  });
  let tools = vm.tools();

  let raw = serde_json::json!([
    ["push", 5],
    ["val", "x"],
    ["set", "x"],
    ["get", "x"],
    ["println"]
  ]);

  let optimized = tools.optimize_bytecode(raw);
  vm.load(optimized.clone())
    .run(None);
}

INFO

Capability Required: Control

TIP

The .run() method is the final step in the execution pipeline. Ensure all necessary capabilities have been granted during initialization to avoid runtime security exceptions.