diff --git a/docs/docs/builtins/Time.md b/docs/docs/builtins/Time.md new file mode 100644 index 0000000..06db207 --- /dev/null +++ b/docs/docs/builtins/Time.md @@ -0,0 +1,33 @@ +# Time + + + + +## Module Function + +### sleep(INTEGER) +> Returns `NIL` + +Stops the RocketLang routine for at least the stated duration in seconds + + +```js +🚀 > Time.sleep(2) +``` + + +### unix() +> Returns `INTEGER` + +Returns the current time as unix timestamp + + +```js +🚀 > Time.Unix() +``` + + + +## Properties +| Name | Value | +| ---- | ----- | diff --git a/evaluator/evaluator_test.go b/evaluator/evaluator_test.go index 4018d33..d2c0ef2 100644 --- a/evaluator/evaluator_test.go +++ b/evaluator/evaluator_test.go @@ -381,6 +381,7 @@ func TestBuiltinFunctions(t *testing.T) { {`IO.open("fixtures/module.rl", 1, "0644")`, "wrong argument type on position 2: got=INTEGER, want=STRING"}, {`IO.open("fixtures/module.rl", "r", 1)`, "wrong argument type on position 3: got=INTEGER, want=STRING"}, {`IO.open("fixtures/module.rl", "nope", "0644").read(1)`, "undefined method `.read()` for ERROR"}, + {"a = Time.unix(); Time.sleep(2); b = Time.unix(); b - a", 2}, } for _, tt := range tests { diff --git a/stdlib/std.go b/stdlib/std.go index 2d871cd..b94937d 100644 --- a/stdlib/std.go +++ b/stdlib/std.go @@ -15,6 +15,7 @@ func init() { RegisterModule("JSON", "", jsonFunctions, jsonProperties) RegisterModule("IO", "", ioFunctions, ioProperties) RegisterModule("OS", "", osFunctions, osProperties) + RegisterModule("Time", "", timeFunctions, timeProperties) } func RegisterFunction(name string, layout object.MethodLayout, function func(object.Environment, ...object.Object) object.Object) { diff --git a/stdlib/time.go b/stdlib/time.go new file mode 100644 index 0000000..3004c77 --- /dev/null +++ b/stdlib/time.go @@ -0,0 +1,41 @@ +package stdlib + +import ( + "time" + + "github.com/flipez/rocket-lang/object" +) + +var timeFunctions = map[string]*object.BuiltinFunction{} +var timeProperties = map[string]*object.BuiltinProperty{} + +func init() { + timeFunctions["sleep"] = object.NewBuiltinFunction( + "sleep", + object.MethodLayout{ + Description: "Stops the RocketLang routine for at least the stated duration in seconds", + ArgPattern: object.Args( + object.Arg(object.INTEGER_OBJ), + ), + ReturnPattern: object.Args( + object.Arg(object.NIL_OBJ), + ), + Example: `🚀 > Time.sleep(2)`, + }, + func(_ object.Environment, args ...object.Object) object.Object { + time.Sleep(time.Duration(args[0].(*object.Integer).Value) * time.Second) + return object.NIL + }) + timeFunctions["unix"] = object.NewBuiltinFunction( + "unix", + object.MethodLayout{ + Description: "Returns the current time as unix timestamp", + ReturnPattern: object.Args( + object.Arg(object.INTEGER_OBJ), + ), + Example: `🚀 > Time.Unix()`, + }, + func(_ object.Environment, args ...object.Object) object.Object { + return object.NewInteger(time.Now().Unix()) + }) +}