Hi guys,
I have a const table which I want to know if all of the values, referenced in the code exist at compile time.
Example:
const myTable = {
1: 14.cint,
2: 23.cint
3: 4.cint,
}.toTable()
echo myTable[33] # <-- Can I get a compile time error here?
Is it possible to get an compile-time error in the last line? Or is it better to use a different object for this purpose? Also is there a way to define the table values as cint without using .cint after every value declaration?
Thanks.
If you write the following you'll get a compile-time error:
const a = myTable[33]
echo a
This isn't terribly convenient. Marginally more so is:
template try_const(expression:typed):auto =
## Evaluate an expression at compile-time if possible.
when compiles((const c = expression)):
const c = expression
c
else:
expression
echo try_const myTable[33]
Better still would be a version of echo that implicitly runs try_const on all arguments. It may be possible with the varargs[type, converter] syntax mentioned here. I get the feeling it may work better as a macro that wraps its arguments.
Is it possible to get an compile-time error in the last line?
If that line is executed at compile-time, like in a static block:
import tables
const myTable = {
1: 14.cint,
2: 23.cint,
3: 4.cint
}.toTable()
static:
echo myTable[33]
Of course, when your keys are integers without holes you can and should use a plain array or seq.
For the check at compile time, maybe something like
static:
assert(myTable(33)) != nil # or assert(myTable.hasKey(33))
Or maybe compileTime pragma -- can not remember the difference to static...
For an array you can write something like
const myArray = array[1 .. 3, cint] = [14.cint, 23, 4]
static and assert, right.
Unfortunately there are holes in the keys, so arrays are not suitable for this purpose.
Thanks guys!
Well when the holes are not too big, then an array is still suitable.
Be aware you can create compile time variables and constants. compile time variables are only existent at compilation time, but can be modified, and constants are readable at compilation time as well as at runtime.
static:
var myTable = {
1: 14.cint,
2: 23.cint,
3: 4.cint
}.toTable()
myTable can be accessed and modified from macros and other static blocks but at runtime it doesn't exist anymore.
@Krux02 , I did not know that!
Then it's possible to use a combination of static and constants to check if all referenced table keys exist at compile time? Very good!