Pointers and references: Difference between revisions

Content deleted Content added
No edit summary
Added Toka
Line 316: Line 316:
set arr($pointer); # returns 3
set arr($pointer); # returns 3
set arr($pointer) 42; # arr(var) now has value 42
set arr($pointer) 42; # arr(var) now has value 42

==[[Toka]]==
[[Category:Toka]]
Toka is an untyped language, and treats pointers in a manner similar to that of assembly language. In Toka, memory can be addressed in characters and cells. Cells are the native word size of the host processor, and are generally either 32 or 64 bits in size. Address alignment is dependent on the host processor.

To declare a variable that lives in memory:

variable myvar #! stores 1 cell

This creates the word "myvar", which when executed leaves the address of a cell of memory on the stack. This address may be accessed with @ (fetch) or ! (store):

1 myvar ! #! place the value 1 into myvar
myvar @ . #! prints the value stored in myvar
1 myvar +! #! add 1 to the value stored in myvar

Other fetch and store operations:
c@ c! \ fetch/store a single character
@ ! \ fetch/store one cell

Toka also has an optional "value", which is a construct similar to other languages' "reference":

needs values
10 value myval #! create a new word that returns the value 10
myval . #! prints 10
20 to myval #! Changes myval to return 20 instead of 10

Toka has a concept similar to that of function pointers. The word ` returns the address of a quote which can be invoked or passed around.

` myval #! Leaves the address of myval on the stack
` myval invoke #! Equivalent to just typing "myval"

For pointer arithmetic, standard integer math operations may be used. There are some words that are specifically designed to enable portable pointer arithmetic:

cell-size #! Puts the number of bytes in one cell on the stack
cell+ #! Adds one cell
10 cells + #! Adds 10 cells
char-size #! Puts the number of bytes in one character on the stack
char+ #! Adds one char
10 chars + #! Adds 10 chars