手撸解释器教程-1

Date Unknown

Hello Lox

// Your first Lox program! print "Hello, world!";

数据类型

  1. Booleans
true; // Not false. false; // Not *not* false.
  1. Numbers
1234; // An integer. 12.34; // A decimal number.
  1. Strings
"I am a string"; ""; // The empty string. "123"; // This is a string, not a number.
  1. Nil

算数运算

add + me; subtract - me; multiply * me; divide / me;
所有这些操作符都是针对数字的,将任何其他类型操作数传递给它们都是错误的。唯一的例外是+运算符——你也可以传给它两个字符串将它们串接起来。

比较与相等

less < than; lessThan <= orEqual; greater > than; greaterThan >= orEqual; 1 == 2; // false. "cat" != "dog"; // true.
不同类型的值永远不会相等:
123 == "123"; // false.
反对隐式转换

逻辑运算

!true; // false. !false; // true. true and false; // false. true and true; // true. false or false; // false. true or false; // true.

优先级与分组

var average = (min + max) / 2;

语句

print "Hello, world!"; { print "One statement."; print "Two statements."; }

变量

var imAVariable = "here is my value"; var iAmNil; var breakfast = "bagels"; print breakfast; // "bagels". breakfast = "beignets"; print breakfast; // "beignets".

控制流

if (condition) { print "yes"; } else { print "no"; } var a = 1; while (a < 10) { print a; a = a + 1; } for (var a = 1; a < 10; a = a + 1) { print a; }

函数

makeBreakfast(bacon, eggs, toast); makeBreakfast(); fun printSum(a, b) { print a + b; } fun returnSum(a, b) { return a + b; }
执行到达代码块的末尾而没有return语句,则会隐式返回nil

闭包

在Lox中,函数是一等公民,这意味着它们都是真实的值,你可以对这些值进行引用、存储在变量中、传递等等。下面的代码是有效的:
fun addPair(a, b) { return a + b; } fun identity(a) { return a; } print identity(addPair)(1, 2); // Prints "3". fun outerFunction() { fun localFunction() { print "I'm local!"; } localFunction(); } fun returnFunction() { var outside = "outside"; fun inner() { print outside; } return inner; } var fn = returnFunction(); fn();

class Breakfast { cook() { print "Eggs a-fryin'!"; } serve(who) { print "Enjoy your breakfast, " + who + "."; } } // Store it in variables. var someVariable = Breakfast; // Pass it to functions. someFunction(Breakfast); var breakfast = Breakfast(); print breakfast; // "Breakfast instance". // 许您自由地向对象添加属性: breakfast.meat = "sausage"; breakfast.bread = "sourdough"; class Breakfast { serve(who) { print "Enjoy your " + this.meat + " and " + this.bread + ", " + who + "."; } // ... } class Breakfast { init(meat, bread) { this.meat = meat; this.bread = bread; } // ... } var baconAndToast = Breakfast("bacon", "toast"); baconAndToast.serve("Dear Reader"); // "Enjoy your bacon and toast, Dear Reader."
 

继承

class Brunch < Breakfast { drink() { print "How about a Bloody Mary?"; } } var benedict = Brunch("ham", "English muffin"); benedict.serve("Noble Reader"); class Brunch < Breakfast { init(meat, bread, drink) { super.init(meat, bread); this.drink = drink; } }
 

标准库

 
 

Copyright © 2025 later

logo