Support for constants?
alexspurling opened this issue · comments
Is it possible to declare constant values in Onyx? If not, it would be useful to add support for them. Here is an example of what I mean:
use core {println}
CHECKERBOARD_SIZE: i32 = 20;
CHECKERBOARD_BUFFER_SIZE: i32 = CHECKERBOARD_SIZE * CHECKERBOARD_SIZE * 4;
main :: () {
generateCheckerBoard();
}
generateCheckerBoard :: () {
for x: 0 .. CHECKERBOARD_SIZE {
for y: 0 .. CHECKERBOARD_SIZE {
println(x);
}
}
}
Here the value of the two constants CHECKERBOARD_SIZE
and CHECKERBOARD_BUFFER_SIZE
should be calculated at compile time. Currently using this syntax in Onyx 0.1.8 results in the error "Top level expressions must be compile time known."
Onyx does have support for constants. The way you would do it to use a ::
instead of :=
. So your top two lines would be:
CHECKERBOARD_SIZE :: 10
CHECKERBOARD_BUFFER_SIZE :: CHECKERBOARD_SIZE * CHECKERBOARD_SIZE
This will will make them constant and compile time know. Hope this helps!
Great thanks. I might raise another issue to add a mention of this syntax to the docs.
I do need to clarify it in the docs for sure. It is mentioned in the Bindings section, but I don't explicitly say that you can use it with numeric values like that. I will leave this issue open until those docs are updated.
Is it possible to define fixed arrays as constants? When I try to compile this I get the error "Binary operator '[]' not understood for arguments of type 'type_expr' and 'unsized int'."
use core {println}
CHECKERBOARD_SIZE :: 20;
CHECKERBOARD_BUFFER_SIZE :: CHECKERBOARD_SIZE * CHECKERBOARD_SIZE * 4;
CHECKERBOARD_BUFFER_POINTER :: [CHECKERBOARD_BUFFER_SIZE] i32;
main :: () {
CHECKERBOARD_BUFFER_POINTER[3] = 2;
}
I want to define an area of memory that can be exported from the wasm module and referenced by the javascript runtime. I am trying to translate this AssemblyScript example to Onyx: https://wasmbyexample.dev/examples/reading-and-writing-graphics/reading-and-writing-graphics.assemblyscript.en-us.html
So let me explain this a little bit. The line,
CHECKERBOARD_BUFFER_POINTER :: [CHECKERBOARD_BUFFER_SIZE] i32;
is actually binding CHECKERBOARD_BUFFER_POINTER
as a type alias to the type [1600] i32
, or a fixed-sized array of i32
that is 1600
elements long.
What you actually want is simply to remove one colon:
CHECKERBOARD_BUFFER_POINTER: [CHECKERBOARD_BUFFER_SIZE] i32;
This makes CHECKERBOARD_BUFFER_POINTER
a global variable of type [1600] i32
.
Hope this makes sense!
The documentation has been updated and is now live, so I am going to close this issue.