Hi all, I tried a lot but can't find. How can i use table inside a type ?. This is failed attempt.
import tables
type
Person = ref object
name : string
age : int
jobSal : Table[string, int] # tell me how to declare
proc newPerson() : Person =
result = new Person
result.name = "A Name"
result.age = 50
result.jobSal = ["A Job" , 35000].toTable # And tell me how to initialize it.
proc print(me : Person) =
echo "Person Name = ", me.name
echo "Person age = ", me.age
# echo "Person Job = ", me.jobSal[] # And also tell me how to get the value
# echo "Person Salary = ", me.jobSal[]
import tables
type
Person = ref object
name: string
age: int
jobSal: Table[string, int] # tell me how to declare
proc newPerson() : Person =
result = new Person
result.name = "A Name"
result.age = 50
result.jobSal = {"A Job": 35000}.toTable # And tell me how to initialize it.
proc print(me : Person) =
echo "Person Name = ", me.name
echo "Person age = ", me.age
echo "Person Job = ", me.jobSal["A Job"] # And also tell me how to get the value
# echo "Person Salary = ", me.jobSal[]
yeah i must say the table examples are a little bit strange.
Here is some basic usage
import tables
var table: Table[string, string] # simple table with string as key, and string as values
## Set entries, examples
table = {"key": "value", "key2": "value2"}.toTable
table["a key"] = "some value"
table.add("more key", "more value")
## Access
# access a single key
echo "ONE KEY: ", table["a key"]
# loop over the table get key and value
for key, value in table:
echo "KEY/VAL: ", key, " -> ", value
# get only values
for value in table.values:
echo "VALUE: ", value
# get only keys
for key in table.keys:
echo "KEY: ", key
# check for existance
assert true == table.hasKey("a key")
echo "entries in table: ", table.len
table.clear()
echo "entries in table after clear: ", table.len
## use tables in a type
type
MyObj = object
mytable: Table[string, string]
var myObj = MyObj()
myObj.mytable = {"foo": "FOO", "baa": "BAA"}.toTable
assert myObj.mytable["foo"] == "FOO"
## More complex table
var complex = Table[int, seq[MyObj]]()
complex[0] = @[MyObj(), MyObj(), MyObj()]
complex[1] = @[MyObj(), MyObj(), MyObj()]
echo "Senseless complex: ", complex[1][0].mytable.len