Skip to content

Commit

Permalink
improve file.write; add nil check to seek
Browse files Browse the repository at this point in the history
Signed-off-by: Flipez <[email protected]>
  • Loading branch information
Flipez committed Jan 15, 2022
1 parent c1d7b72 commit d9a4ea0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
4 changes: 2 additions & 2 deletions docs/content/en/docs/literals/file.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ Seek sets the offset for the next Read or Write on file to offset, interpreted a


### write(STRING)
> Returns `BOOLEAN|NULL`
> Returns `BOOLEAN|ERROR`
Writes the given string to the file. Returns `true` on success, `false` on failure and `null` if pointer is invalid.
Writes the given string to the file. Returns `true` on success.



Expand Down
21 changes: 13 additions & 8 deletions object/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,11 @@ func init() {
},
method: func(o Object, args []Object) Object {
f := o.(*File)

if f.Handle == nil {
return &Error{Message: "Invalid file handle."}
}

seekAmount := args[0].(*Integer).Value
seekRelative := args[1].(*Integer).Value
newOffset, err := f.Handle.Seek(seekAmount, int(seekRelative))
Expand All @@ -167,9 +172,9 @@ func init() {
},
},
"write": ObjectMethod{
description: "Writes the given string to the file. Returns `true` on success, `false` on failure and `null` if pointer is invalid.",
description: "Writes the given string to the file. Returns `true` on success.",
returnPattern: [][]string{
[]string{BOOLEAN_OBJ, NULL_OBJ},
[]string{BOOLEAN_OBJ, ERROR_OBJ},
},
argPattern: [][]string{
[]string{STRING_OBJ},
Expand All @@ -182,14 +187,14 @@ func init() {
return &Error{Message: "Invalid file handle."}
}

_, err := f.Handle.Write(content)
if err == nil {
return &Boolean{Value: true}
}
bytesWritten, err := f.Handle.Write(content)
f.Position += int64(bytesWritten)

f.Position += int64(len(content))
if err != nil {
return &Error{Message: err.Error()}
}

return &Boolean{Value: false}
return &Boolean{Value: true}
},
},
}
Expand Down

0 comments on commit d9a4ea0

Please sign in to comment.