Skip to content

Commit ca2462d

Browse files
committed
Добавлена функция length
1 parent 28c7b38 commit ca2462d

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.annimon.ownlang.lib.modules.functions;
2+
3+
import com.annimon.ownlang.lib.*;
4+
5+
public final class std_length implements Function {
6+
7+
@Override
8+
public Value execute(Value... args) {
9+
if (args.length == 0) throw new RuntimeException("At least one arg expected");
10+
11+
final Value val = args[0];
12+
int length;
13+
switch (val.type()) {
14+
case Types.ARRAY:
15+
length = ((ArrayValue) val).size();
16+
break;
17+
case Types.MAP:
18+
length = ((MapValue) val).size();
19+
break;
20+
case Types.STRING:
21+
length = ((StringValue) val).length();
22+
break;
23+
case Types.FUNCTION:
24+
final Function func = ((FunctionValue) val).getValue();
25+
if (func instanceof UserDefinedFunction) {
26+
length = ((UserDefinedFunction) func).getArgsCount();
27+
} else {
28+
length = 0;
29+
}
30+
break;
31+
default:
32+
length = 0;
33+
34+
}
35+
return new NumberValue(length);
36+
}
37+
}

src/com/annimon/ownlang/lib/modules/std.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public final class std implements Module {
1313
public void init() {
1414
Functions.set("echo", new std_echo());
1515
Functions.set("newarray", new std_newarray());
16+
Functions.set("length", new std_length());
1617
Functions.set("rand", new std_rand());
1718
Functions.set("sleep", new std_sleep());
1819
Functions.set("thread", new std_thread());

0 commit comments

Comments
 (0)