Declaring variables: var and let
Both var and let can be used to declare a variable. Unlike in JavaScript, there is no difference in scope between let and var in Ninox.
The type of the variable depends on the type of value assigned to it:
var t := "my text";
var b := false;
var n := 10;A variable can be declared multiple times within the same code. In such cases, the variable will retain the type and value assigned to it until the new declaration is reached:
var b := true;
dialog("Message 1", "Value of b: " + b, ["ok"]);
var b := 12;
dialog("Message 2", "Value of b: " + b, ["ok"]);Confusion Between Variable Names and Table/Field IDs
Ninox saves its code in a slightly different format than what is displayed on the screen. Specifically, field and table names are replaced with their IDs, which are letters.
For example, the following script, which calculates the sum of sold items:
sum('Invoice Items'.Total)Will be saved in the system code as follows, where D is the ID of the table 'Invoice Items' and E is the ID of the field Total:
sum(D.E)In this context, if a variable D is created, it can cause confusion for the compiler, as the following system code would make it unclear whether D.E refers to a table or the previously declared variable D:
(var D := "hello"; sum(D.E))To avoid such confusion, variables should be given names that are unlikely to match table or field IDs, or table/field names. This is why variables are often named with short, lowercase names (e.g., a, b, or c) to prevent them from being confused with IDs.
Which One Wins: the Variable, Without Any Message
Ninox reports nothing: once the code is saved, the variable wins over the field that has the same ID. Example, in a database where the field Number of the table Sessions has the ID B:
var B := 5;
cnt(select Sessions[Number = 1])This code is saved as (var B := 5; cnt(select A[B = 1])). When it is read back, the filter no longer compares the field Number with 1, but the variable B: the result is 0, without any error. With [Number = 5], it would count every record; an order by Number sort would no longer follow the numbers. (Measured through the API, on a table of 48 records.)
The trap only appears after the code is saved: a test of the text as it is displayed, with the field names (a query sent through the API, for example), compiles and gives the right result. In the code read back after saving, the ID B remains written as is where the field name used to be: that is the sign of the confusion (observed in the code downloaded by the Ninox command-line tool; not verified in the code editor).
The simplest rule: never give a variable or a parameter a name made of one or two capital letters (B, KD, A1). Prefer lowercase names that say what they hold (firstDay, total).
