Skip to content

Commit

Permalink
添加面向对象部分
Browse files Browse the repository at this point in the history
  • Loading branch information
lollipopkit committed Oct 1, 2022
1 parent 3a72c40 commit 8643380
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 15 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
**仅包含语言LK的变化**

## 0.1.3

- 添加`prefixexp : Name args`的语法
- 支持面向对象
- `REPL`支持自动添加`print`

## 0.1.2
- `Table`索引从`0`开始
Expand Down
29 changes: 29 additions & 0 deletions LANG.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,35 @@ shy add = fn (a, b) {
```
除去常规的函数声明,`LK` 还可以将函数赋值给变量,这样可以实现匿名函数。

## 面向对象
```js
// 定义一个对象Rect
Rect = {}

// 定义一个函数,可以用来构造Rect
fn Rect:new() {
o = {}
for k, v in Rect {
o[k] = v
}
rt o
}

// 给Rect对象添加一个函数,可以用来打印Rect的信息
fn Rect:printArea() {
print("Rect area: ", self.width * self.height)
}

fn Rect:set(width, height) {
self.width = width
self.height = height
}

shy rect = Rect:new()
rect:set(10, 20)
rect:printArea() // Rect area: 200
```


##
```js
Expand Down
10 changes: 9 additions & 1 deletion test/basic.lk
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import "test/import"
import "test/object"

shy func = fn (e) {print(e)}
func(1!=2 and 3!=3)
Expand All @@ -19,4 +20,11 @@ if #long >= 0 and '' {

print(6 ~/ 2, 6 & 2, 6 / 2)
print({'a'} .. '', 1 .. 2, _VERSION, math.pi)
print(str({5, 'd': false}))
print(str({5, 'd': false}))

shy square = Rect:square(10)
shy rect = Rect:new()
rect:set(10, 20)

square:printArea()
rect:printArea()
33 changes: 20 additions & 13 deletions test/object.lk
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
Rectangle = {'area': 0, 'length': 0, 'breadth': 0}
Rect = {'width': 0, 'height': 0}

fn Rectangle:new(o,length,breadth) {
o = o or {}
setmetatable(o, self)
self.__index = self
self.length = length or 0
self.breadth = breadth or 0
self.area = length*breadth;
rt o
fn Rect:new() {
o = {}
for k, v in Rect {
o[k] = v
}
rt o
}

fn Rectangle:printArea() {
print("矩形面积为 ", self.area)
fn Rect:square(len) {
o = self:new()
o.width = len
o.height = len
rt o
}

shy rect = Rectangle:new(nil, 10, 20)
rect:printArea()
fn Rect:printArea() {
print("Rect area: ", self.width * self.height)
}

fn Rect:set(width, height) {
self.width = width
self.height = height
}

0 comments on commit 8643380

Please sign in to comment.