negative number parsing
This commit is contained in:
parent
69536783c7
commit
90284f2d06
3 changed files with 86 additions and 0 deletions
|
|
@ -145,6 +145,80 @@ func Join(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
|
|||
return ret
|
||||
}
|
||||
|
||||
/* takes three arguments:
|
||||
* 1. start index
|
||||
* 2. end index
|
||||
* 3. source
|
||||
* Returns a substring from source delimited by args 1 and 2.
|
||||
* First two args must be integers (4 or 4.0 but not 4.3)
|
||||
*
|
||||
* Example: (substr 1 5 "Linus Torvalds") -> "inus "
|
||||
*/
|
||||
func Substr(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
|
||||
start := in.Eval(ft, vt, false)
|
||||
if start == nil || start.Next == nil || start.Next.Next == nil {
|
||||
log.Log(log.ERR,
|
||||
"an argument evaluated to nil",
|
||||
"substr")
|
||||
return nil
|
||||
}
|
||||
|
||||
end := start.Next
|
||||
str := end.Next
|
||||
|
||||
if start.Tag != ast.NUMBER || end.Tag != ast.NUMBER || str.Tag != ast.STRING {
|
||||
log.Log(log.ERR,
|
||||
"incorrect types of args",
|
||||
"substr")
|
||||
return nil
|
||||
}
|
||||
|
||||
ed_idx := 0
|
||||
st_idx, err := strconv.Atoi(start.Value())
|
||||
ed_idx, err = strconv.Atoi(end.Value())
|
||||
if err != nil {
|
||||
log.Log(log.ERR,
|
||||
"error parsing args: " + err.Error(),
|
||||
"substr")
|
||||
return nil
|
||||
}
|
||||
|
||||
strlen := len(str.Value())
|
||||
if st_idx < 0 {
|
||||
st_idx += strlen
|
||||
}
|
||||
|
||||
if ed_idx < 0 {
|
||||
ed_idx += strlen
|
||||
}
|
||||
|
||||
if st_idx < 0 || st_idx >= strlen {
|
||||
log.Log(log.ERR,
|
||||
"first index out of bounds",
|
||||
"substr")
|
||||
return nil
|
||||
}
|
||||
|
||||
if ed_idx < 0 || ed_idx >= strlen {
|
||||
log.Log(log.ERR,
|
||||
"last index out of bounds",
|
||||
"substr")
|
||||
return nil
|
||||
}
|
||||
|
||||
if st_idx > ed_idx {
|
||||
log.Log(log.ERR,
|
||||
"start must be less than end",
|
||||
"substr")
|
||||
return nil
|
||||
}
|
||||
|
||||
res := str.Value()[st_idx:ed_idx]
|
||||
ret := &ast.Token{Tag: ast.STRING}
|
||||
ret.Set(res)
|
||||
return ret
|
||||
}
|
||||
|
||||
/* Takes one arg, returns nil
|
||||
* Prints a string to stdout
|
||||
* Unquotes string so user can add escaped chars like \n, \t, etc
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue