mattn / anko

Scriptable interpreter written in golang
http://play-anko.appspot.com/
MIT License
1.47k stars 118 forks source link

add default argument feature #108

Open qcdong2016 opened 6 years ago

qcdong2016 commented 6 years ago

how can i create a function like Lua function math.random([m[, n]])

When called without arguments, returns a pseudo-random float with uniform distribution in the range [0,1). When called with two integers m and n, math.random returns a pseudo-random integer with uniform distribution in the range [m, n]. (The value n-m cannot be negative and must fit in a Lua integer.) The call math.random(n) is equivalent to math.random(1,n).

MichaelS11 commented 6 years ago

Is there a particular reason why rand.Float64() will not work for you? Or was this a feature request to add default arguments in general?

https://github.com/mattn/anko/blob/master/builtins/math/rand/rand.go

https://golang.org/pkg/math/rand/#Float64

Make sure to seed first before using rand.Float64()

rand.Seed(time.Now().UTC().UnixNano())

qcdong2016 commented 6 years ago

math.random just a example. I need a sample way to create a function take arguments like that. another example: func toUpper(string, [start, [end]]) toUpper('abcde') -> ABCDE toUpper('abcde', 1) -> aBCDE toUpper('abcde', 1, 3) -> aBCDe

MichaelS11 commented 6 years ago

While this would be nice to have, I personally think that Go would need to be able handle optional arguments in order for Anko to have them. From what I have read, Go is not planing on adding optional arguments.

MichaelS11 commented 6 years ago

This can be handled by using variadic functions. There are lots of Go threads about this topic and similar topics. I can understand why it is wanted but from what I have read and understood, it is generally better to keep the arguments passed without defaults.

I think default arguments should not be added and this should be closed.

chyroc commented 6 years ago

I also think that adding default parameters in anko is not so good. 1. golang does not support the default parameters 2. the default parameters are confusing 3. if you need the default parameters, you can use the form of func xxx(args ...Option), or the client to encapsulate the default parameters

anko is a scriptable interpreter, maybe default argument feature is not bad.