125 lines
2.9 KiB
Python
125 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Example usage of the Rhai Python bindings
|
|
"""
|
|
|
|
import rhai
|
|
|
|
|
|
def main():
|
|
print("=== Basic Rhai Python Bindings Demo ===\n")
|
|
|
|
# Quick evaluation
|
|
print("1. Quick evaluation:")
|
|
result = rhai.eval("40 + 2")
|
|
print(f" rhai.eval('40 + 2') = {result}")
|
|
print()
|
|
|
|
# Using the engine directly
|
|
print("2. Using RhaiEngine:")
|
|
engine = rhai.RhaiEngine()
|
|
|
|
# Basic arithmetic
|
|
result = engine.eval("10 * 5 + 3")
|
|
print(f" 10 * 5 + 3 = {result}")
|
|
|
|
# String operations
|
|
result = engine.eval('"Hello, " + "World!"')
|
|
print(f" String concatenation: {result}")
|
|
|
|
# Boolean operations
|
|
result = engine.eval("true && false")
|
|
print(f" Boolean operation: {result}")
|
|
print()
|
|
|
|
# Variables
|
|
print("3. Variable operations:")
|
|
engine.set_var("x", 42)
|
|
engine.set_var("name", "Rhai")
|
|
|
|
result = engine.eval("x * 2")
|
|
print(f" x = 42, x * 2 = {result}")
|
|
|
|
result = engine.eval('"Hello, " + name + "!"')
|
|
print(f" name = 'Rhai', greeting = {result}")
|
|
|
|
# Check variables
|
|
print(f" Variables in scope: {engine.list_vars()}")
|
|
print(f" Has variable 'x': {engine.has_var('x')}")
|
|
print(f" Get variable 'x': {engine.get_var('x')}")
|
|
print()
|
|
|
|
# Arrays
|
|
print("4. Array operations:")
|
|
result = engine.eval("[1, 2, 3, 4, 5]")
|
|
print(f" Array creation: {result}")
|
|
|
|
engine.set_var("arr", [10, 20, 30])
|
|
result = engine.eval("arr[1]")
|
|
print(f" Array indexing arr[1]: {result}")
|
|
|
|
result = engine.eval("arr.len()")
|
|
print(f" Array length: {result}")
|
|
print()
|
|
|
|
# Objects/Maps
|
|
print("5. Object/Map operations:")
|
|
engine.set_var("obj", {"name": "test", "value": 123})
|
|
result = engine.eval("obj.name")
|
|
print(f" Object property access: {result}")
|
|
|
|
result = engine.eval('#{a: 1, b: "hello", c: true}')
|
|
print(f" Object creation: {result}")
|
|
print()
|
|
|
|
# Control flow
|
|
print("6. Control flow:")
|
|
result = engine.eval("""
|
|
let x = 10;
|
|
if x > 5 {
|
|
"x is greater than 5"
|
|
} else {
|
|
"x is not greater than 5"
|
|
}
|
|
""")
|
|
print(f" If statement result: {result}")
|
|
|
|
result = engine.eval("""
|
|
let sum = 0;
|
|
for i in 1..6 {
|
|
sum += i;
|
|
}
|
|
sum
|
|
""")
|
|
print(f" Loop sum 1-5: {result}")
|
|
print()
|
|
|
|
# Functions
|
|
print("7. Functions:")
|
|
result = engine.eval("""
|
|
fn double(x) {
|
|
x * 2
|
|
}
|
|
double(21)
|
|
""")
|
|
print(f" Custom function result: {result}")
|
|
print()
|
|
|
|
# Error handling
|
|
print("8. Error handling:")
|
|
try:
|
|
engine.eval("undefined_variable")
|
|
except RuntimeError as e:
|
|
print(f" Caught error: {e}")
|
|
|
|
try:
|
|
engine.compile("invalid syntax {{")
|
|
except RuntimeError as e:
|
|
print(f" Compilation error: {e}")
|
|
|
|
print("\n=== Demo Complete ===")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|