A Quick Tour
Usando a linguagem 4D, imprimir a mensagem tradicional ""Hello, world!" na tela pode ser feito de várias maneiras. A maneira mais simples é provavelmente escrever a linha única abaixo em um método de projeto:
ALERT("Hello, World!")
Esse código vai exibir um alerta normal de plataforma com a mensagem "hello world" contendo um botão OK. To execute the code, you just need to click on the execution button in the Code Editor:
Ou poderia anexar esse código a um botão em um formulário e executar o formulário, nesse caso, clicar no botão exibira a caixa de diálogo de alerta. Em qualquer caso, acabou de executar sua primeira linha de código 4D!
Atribuir valores
Dados podem ser colocado ou copiados de ou em variáveis, campos, elementos arrays... Colocar dados em uma variável é chamado atribuiindo os dados a uma variável e é feito com o operador de atribuição (:=). O operador de atribuição também é usado para atribuir dados para elementos campos ou arrays.
$MyNumber:=3 //assigns 3 to MyNumber variable
[Products]Size:=$MyNumber //assigns MyNumber variable to [Products]Size field
arrDays{2}:="Tuesday" //assigns "Tuesday" string to the 2nd arrDays element MyVar:=Length("Acme") //assigns the result of the function (4) to MyVar
$myDate:=!2018/01/21! //atribui uma data literal
$myHour:=?08:12:55? //atribui uma hora literal
Você DEVE diferenciar o operador atribuição := dos outros operadores. Ao invés de combinar expressões a uma nova, o operador de atribuição copia o valor da expressão para a direita do operador de atribuição para a variável ou campo para a esquerda do operador.
Importante: Não confunda o operador de atribuição := com o operador de comparação de igualdade =. Um operador de atribuição diferente (e não =) foi escolhido deliberadamente para evitar problemas e confusão que ocorrem frequentemente em outras linguagens com operadores como == ou ===. Esses erros são geralmente difíceis de reconhecer pelo compilador e geram problemas trabalhosos.
Variáveis
A linguagem 4D é baseada em tipos, mas com alguma flexibilidade. You create a typed variable using the var
keyword. Por exemplo, para criar uma variável do tipo dados, pode escrever:
var MyDate : Date
The var
keyword allows declaring object variables of a defined class type, for example:
var myPerson : cs. Person
//variable of the Person user class
Even if it is usually not recommended, you can declare variables simply by using them; you do not necessarily need to formally define them. Por exemplo, se quiser criar uma variável que contenha a data atual mais 30 dias, pode escrever:
MyOtherDate:=Current date+30
A linha de código lê “MyOtherDate gets the current date plus 30 days.” This line declares the variable, assigns it with both the (temporary) date type and a content. A variable declared by assignment is interpreted as typeless, that is, it can be assigned with other types in other lines and then changes the type dynamically. A variable typed with var
cannot change the type. In compiled mode however, the type can never be changed, regardless of how the variable was declared.
Comandos
Os comandos 4D são métodos integrados para realizar uma ação. Comandos são frequentemente usados com parâmetros, que são passados em parênteses () e separados por ponto e vírgula (;). Exemplo:
COPY DOCUMENT("folder1\\name1";"folder2\\" ; "new")
Some commands are attached to collections or objects, in which case they are named functions and are used using the dot notation. Por exemplo:
$c:=New collection(1;2;3;4;5)
$nc:=$c.slice(0;3) //$nc=[1,2,3]
$lastEmployee:=$employee.last()
Pode utilizar os plug-ins ou os componentes 4D que adicionem novos comandos a seu entorno de desenvolvimento 4D.
Há vários plug-ins propostos pela comunidade de usuários 4D ou desenvolvedores de terceira parte no mercado. Por exemplo, usar 4d-plugin-pdf-pages em macOS:
PDF REMOVE PAGE(path;page)
4D SVG é um exemplo de componente utilitário que aumenta as capacidades de sua aplicação:
//desenhar uma imagem
svgRef:=SVG_New
objectRef:=SVG_New_arc(svgRef;100;100;90;90;180)
4D SVG é incluído em 4D.
Constantes
4D oferece um conjunto extensivo de constantes predefinidas, cujos valores são acessíveis por nome. Isso permite escrever código mais legível. Por exemplo, Read Mode
é uma constante (valor 2).
vRef:=Open document("PassFile";"TEXT";Read Mode) // abre documento em modo apenas leitura
Predefined constants appear underlined by default in the 4D Code Editor.
Métodos
4D oferece un grande número de métodos (ou comandos) integrados, mas também lhe permite criar seus próprios métodos de projeto. Os métodos de projeto são métodos definidos pelo usuário que contenham comandos, operadores e outras partes da linguaje. Los métodos projeto são métodos genéricos, mas há outros tipos de métodos: métodos objeto, métodos formulário, métodos tabela (Triggers) e métodos base.
Um método projeto é composto de várias linhas de instruções, cada uma das quais consta de uma linha no método. A statement performs an action, and may be simple or complex.
Por exemplo, a linha abaixo é uma declaração que mostará uma caixa de diálogo de confirmação:
CONFIRM("Quer realmente fechar esta conta?"; "Sím"; "Não")
Um método também contém testes e loops que controlam o fluxo da execução. 4D methods support If... End if
and Case of... End case
branching structures as well as looping structures: While... End while
, Repeat... Until
, For... End for
, and For each... End for each
:
O exemplo abaixo recorre todos os caracteres do texto vtSomeText:
For($vlChar;1;Length(vtSomeText))
//Do something with the character if it is a TAB
If(Character code(vtSomeText[[$vlChar]])=Tab)
//...
End for
Um método projeto pode chamar a outro método projeto com ou sem parâmetros (argumentos). Os parâmetros se passam ao método entre parêntesis, depois do nome do método. Cada parâmetro está separado do próximo por um ponto e vírgula (;). The parameters are directly available within the called method if they have been declared. A method can return a single value in a parameter, which have to be declared. Quando chamar um método, apenas digite seu nome:
$myText:="hello"
$myText:=Do_Something($myText) //Call the Do_Something method
ALERT($myText) //"HELLO"
//Here the code of the method Do_Something
#DECLARE ($in : Text) -> $out : Text
$out:=Uppercase($in)
Tipos de dados
Na linguagem, os diferentes tipos de dados que podem ser manejados são denominados tipos de dados. Existem tipos de dados básicos (string, numérico, data, hora, booleano, imagem, ponteiros, arrays), e também tipos de dados compostos (BLOBs, objetos, coleções).
Lembre que os dados de tipo string e numérico podem ser associados a mais de um tipo de campo. Quando são introduzidos dados em um campo, a linguagem converte automaticamente os dados no tipo correto para o campo. Por exemplo, se um campo inteiro for usado, seus dados são tratados automaticamente como numéricos. Em outras palavras não precisa se preocupar sobre misturar tipos de campos similares quando usando a linguagem; vai ser gerenciada por você.
Entretanto, quando usar a linguagem é importante que não misture diferentes tipos de dados. Da mesma forma que não tem sentido armazenar "ABC" em um campo de data, tampouco tem sentido por "ABC" em uma variável utilizada para datas. Na maioria dos casos, 4D é muito tolerante e tentará dar sentido ao que está fazendo. For example, if you add a number to a date, 4D will assume that you want to add that number of days to the date, but if you try to add a string to a date, 4D will tell you that the operation cannot work.
There are cases in which you need to store data as one type and use it as another type. The language contains a full complement of commands that let you convert from one data type to another. For example, you may need to create a part number that starts with a number and ends with characters such as “abc”. Neste caso, poderá escrever:
[Products]Part Number:=String(Number)+"abc"
If Number is 17, then [Products]Part Number will get the string “17abc”.
The data types are fully defined in the section Data Types.
Objectos e colecções
You can handle 4D language objects and collections using the object notation to get or to set their values. Por exemplo:
employee.name:="Smith"
You can also use a string within square brackets, for example:
$vName:=employee["name"]
Uma vez que um valor de propriedade de objeto pode ser um objeto ou uma coleção, a notação de objeto aceita uma sequência de símbolos para acessar subpropriedades, por exemplo:
$vAge:=employee.children[2].age
Note that if the object property value is an object that encapsulates a method (a formula), you need to add parenthesis () to the property name to execute the method:
$f:=New object
$f.message:=Formula(ALERT("Hello world!"))
"Hello World"
To access a collection element, you have to pass the element number embedded in square brackets:
var myColl : Collection
myColl:=New collection("A";"B";1;2;Current time)
myColl[3] //acesso ao 4º elemento da colecção
Classes
A linguagem 4D suporta classes de objectos. Add a myClass.4dm
file in the Project/Sources/Classes folder of a project to create a class named "myClass".
To instantiate an object of the class in a method, call the user class from the class store (cs
) and use the new()
member function. You can pass parameters.
// num método 4D
$o:=cs.myClass.new()
In the myClass
class method, use the Function <methodName>
statement to define the methodName class member function. A class member function can receive and return parameters like any method, and use This
as the object instance.
//in o ficheiro myClass.4dm
Function hello -> $welcome : Text
$welcome:="Hello "+This.who
To execute a class member function, just use the ()
operator on the member function of the object instance.
$f:=New object
$f.message:=New formula(ALERT("Hello world!"))
$f.message() //displays "Hello world!"
Optionally, use the Class constructor
keyword to declare properties of the object.
//no ficheiro Rectangle.4dm
Class constructor ($width : Integer; $height : Integer)
This.height:=$height
This.width:=$width
This.name:="Rectangle"
Uma classe pode estender outra classe utilizando Class extends <ClassName>
. Superclasses can be called using the Super
command. Por exemplo:
//in the Square.4dm file
Class extends rectangle
Class constructor ($length : Integer)
// It calls the parent class's constructor with lengths
// provided for the Rectangle's width and height
Super($length;$length)
This.name:="Square"
Operadores
When you use the language, it is rare that you will simply want a piece of data. It is more likely that you will want to do something to or with that data. You perform such calculations with operators. Operators, in general, take two pieces of data and perform an operation on them that results in a new piece of data. You are already familiar with many operators. You are already familiar with many operators. For example, 1 + 2 uses the addition (or plus sign) operator to add two numbers together, and the result is 3.
Operator | Operação | Exemplo |
---|---|---|
+ | Adição | 1 +2 = 3 |
– | Subtração | 3 - 2 = 1 |
* | Multiplicação | 2 * 3 = 6 |
/ | Divisão | 6 / 2 = 3 |
Numeric operators are just one type of operator available to you. 4D supports many different types of data, such as numbers, text, dates, and pictures, so there are operators that perform operations on these different data types.
The same symbols are often used for different operations, depending on the data type. For example, the plus sign (+) performs different operations with different data:
Tipo de dados | Operação | Exemplo |
---|---|---|
Número | Adição | 1 + 2 adds the numbers and results in 3 |
String | Concatenação | “Hello ” + “there” concatenates (joins together) the strings and results in “Hello there” |
Data e Número | Date addition | !1989-01-01! + 20 adds 20 days to the date January 1, 1989, and results in the date January 21, 1989 |
Expressões
Simply put, expressions return a value. In fact, when using the 4D language, you use expressions all the time and tend to think of them only in terms of the value they represent. Expressions are also sometimes referred to as formulas.
Expressions are made up of almost all the other parts of the language: commands, operators, variables, fields, object properties, and collection elements. You use expressions to build statements (lines of code), which in turn are used to build methods. The language uses expressions wherever it needs a piece of data.
Expressions rarely “stand alone.” There are several places in 4D where an expression can be used by itself. Inclui:
- Formula editor (apply formula, query with formula, order by formula)
- O comando
EXECUTE FORMULA
- A lista de propriedades, onde uma expressão pode ser usada como fonte de dados para a maioria dos widgets
- Depurador onde o valor das expressões pode ser verificado
- Quick Report editor as a formula for a column
Tipos de expressões
You refer to an expression by the data type it returns. There are several expression types. The following table gives examples of each type of expression.
Expression | Tipo | Descrição |
---|---|---|
“Hello” | String | The word Hello is a string constant, indicated by the double quotation marks. |
“Hello ” + “there” | String | Two strings, “Hello ” and “there”, are added together (concatenated) with the string concatenation operator (+). The string “Hello there” is returned. |
“Sr. ” + [People]Name | String | Two strings are concatenated: the string “Mr. ” and the current value of the Name field in the People table. If the field contains “Smith”, the expression returns “Mr. Smith”. |
Uppercase("smith") | String | This expression uses Uppercase , a command from the language, to convert the string “smith” to uppercase. Retorna "SMITH". |
4 | Número | Esta é uma constante numérica, 4. |
4 * 2 | Número | Dois números, 4 e 2, são multiplicados utilizando o operador de multiplicação (*). O resultado é o número 8. |
myButton | Número | This is a variable associated to a button. It returns the current value of the button: 1 if it was clicked, 0 if not. |
!1997-01-25! | Date | This is a date constant for the date 1/25/97 (January 25, 1997). |
Current date+ 30 | Date | This is a date expression that uses the Current date command to get today’s date. It adds 30 days to today’s date and returns the new date. |
?8:05:30? | Hora | This is a time constant that represents 8 hours, 5 minutes, and 30 seconds. |
?2:03:04? + ?1:02:03? | Hora | This expression adds two times together and returns the time 3:05:07. |
True | Booleano | Este comando devolve o valor Booleano TRUE. |
10 # 20 | Booleano | This is a logical comparison between two numbers. The number sign (#) means “is not equal to”. Since 10 “is not equal to” 20, the expression returns TRUE. |
“ABC” = “XYZ” | Booleano | This is a logical comparison between two strings. They are not equal, so the expression returns FALSE. |
My Picture + 50 | Imagem | This expression takes the picture in My Picture, moves it 50 pixels to the right, and returns the resulting picture. |
->[People]Name | Ponteiro | Esta expressão devolve um ponteiro ao campo chamado [People]Name. |
Table(1) | Ponteiro | This is a command that returns a pointer to the first table. |
JSON Parse (MyString) | Objeto | This is a command that returns MyString as an object (if proper format) |
JSON Parse (MyJSONArray) | Collection | This is a command that returns MyJSONArray as a collection (if proper format) |
Form.pageNumber | Propriedade objecto | An object property is an expression that can be of any supported type |
Col[5] | Collection element | A collection element is an expression that can be of any supported type |
$entitySel[0] | Entity | A element of an ORDA entity selection is an expression of the entity type. This kind of expression is non-assignable |
Assignable vs non-assignable expressions
An expression can simply be a literal constant, such as the number 4 or the string "Hello", or a variable like $myButton
. It can also use operators. For example, 4 + 2 is an expression that uses the addition operator to add two numbers together and return the result 6. In any cases, these expressions are non-assignable, which means that you cannot assign a value to them. In 4D, expressions can be assignable. An expression is assignable when it can be used on the left side of an assignation. Por exemplo:
//$myVar variable is assignable, you can write:
$myVar:="Hello" //assign "Hello" to myVar
//Form.pageNumber is assignable, you can write: Form.pageNumber:=10 //assign 10 to Form.pageNumber
//Form.pageTotal-Form.pageNumber is not assignable: Form.pageTotal- Form.pageNumber:=10 //error, non-assignable
In general, expressions that use an operator are non-assignable. For example, [Person]FirstName+" "+[Person]LastName
is not assignable.
Ponteiro
The 4D language provides an advanced implementation of pointers, that allow writing powerful and modular code. You can use pointers to reference tables, fields, variables, arrays, and array elements.
A pointer to an element is created by adding a "->" symbol before the element name, and can be dereferenced by adding the "->" symbol after the pointer name.
MyVar:="Hello" MyPointer:=->MyVar ALERT(MyPointer->)
Código em várias linhas
You can write a single statement on several lines by terminating each line of the statement with a trailing backslash \
character. The 4D language will consider all the lines at once. For example, both the following statements are equivalent:
$str:=String("hello world!")
$str:=String("hello"+\
" world"+\
+"!")
Comentários
Comments are inactive lines of code. These lines are not interpreted by the 4D language and are not executed when the code is called.
There are two ways to create comments:
//
para comentários de linha única/*...*/
for inline or multiline commnents.
Both styles of comments can be used simultaneously.
Single line comments (//comment
)
Insert //
at the beginning of a line or after a statement to add a single line comment. Exemplo:
//This is a comment
For($vCounter;1;100) //Starting loop
//comment
//comment
//comment
End for
Inline or multiline comments (/*comment*/
)
Surround contents with /*
... */
characters to create inline comments or multiline comment blocks. Both inline and multiline comment blocks begin with /*
and end with */
.
- Inline comments can be inserted anywhere in the code. Exemplo:
For /* inline comment */ ($vCounter;1;100)
...
End for
- Multiline comment blocks allows commenting an unlimited number of lines. Comment blocks can be nested (useful since the 4D code editor supports block collapsing). Exemplo:
For ($vCounter;1;100)
/*
comentarios
/*
outros comentarios
*/
*/
...
End for
Escape sequences
The 4D language allows you to use escape sequences (also called escape characters). An escape sequence is a sequence of characters that can be used to replace a "special" character.
The sequence consists of a backslash \
, followed by a character. For instance, \t
is an escape sequence for the Tab character. Escape sequences facilitate the entry of special characters: the previous example (\t
) replaces the entry "Character(Tab)".
In 4D, the following escape sequences can be used:
Escape sequence | Character replaced |
---|---|
\n | LF (Avanço de linha) |
\t | HT (Tab) |
\r | CR (Carriage return) |
`\\ | ``` (Backslash) |
\" | " (aspas) |
It is possible to use either upper or lower case in escape sequences.
In the following example, the Carriage return character (escape sequence \r
) is inserted in a statement in order to obtain a dialog box:
ALERT("The operation has been completed successfully.\rYou may now disconnect.")