Last active
December 14, 2020 04:28
-
-
Save tonetheman/35c62e72d3d9cf7f333de40147bc5991 to your computer and use it in GitHub Desktop.
Testing objects in nim lang. Trying to understand the overloads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# define an object type | |
type Foo = object | |
x : int | |
y : int | |
name : string | |
# define a proc that takes a Foo | |
# I named it self for no real reason | |
proc bob(self:Foo) = | |
echo "foo.bob",self | |
# define a mutable Foo | |
var f = Foo(x:0,y:0,name:"tony") | |
# call the proc, f is passed as first argument | |
f.bob() | |
# define some more procs that all take Foo | |
# this is a setter for a field "fake" that | |
# does not exist | |
proc `fake=`(f : var Foo, value : string ) = | |
f.name = value | |
# define a getter for fake | |
# really return name | |
proc fake(f : Foo) : string = | |
return f.name | |
# tell nim what to call when you pass | |
# two foo objects to the + operator | |
proc `+`(f1 : Foo, f2: Foo) : Foo = | |
return Foo(x:0,y:0,name:"nope") | |
# calls the setter | |
f.fake = "crud" | |
# print the object | |
echo f | |
# calls the getter | |
echo "this is fake: ", f.fake() | |
var g = Foo(x:0,y:0,name:"ethan") | |
# adds 2 Foos, calls plus operator | |
echo f+g | |
# define a new tuple type v2 | |
type v2 = tuple | |
x : int | |
y : int | |
var vv = (x:10,y:10) | |
# define what happens for unary minus | |
proc `-`(v : v2) :v2 {.inline.} = | |
return (x: -v.x , y: -v.y) | |
# define what happens for int - v2 | |
proc `-`(i : int, v : v2) : v2 = | |
return (x: v.x-i, y : v.y-i) | |
# define what happens for v2 - int | |
# should match int - v2 | |
proc `-`(v : v2, i : int) : v2 = | |
return (x: v.x-i, y: v.y-i) | |
# call the unary proc | |
echo -vv | |
# call int - Foo | |
echo 10-vv | |
# call Foo - int | |
echo vv-100 | |
# define a += for Foo and an int | |
# += modifies the passed object | |
# so you must use var in the signature | |
proc `+=`(f : var Foo, i : int) = | |
f.x = f.x + i | |
echo f | |
f += 10 | |
echo f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment