Saltar para o conteúdo principal
Version: v18

Uma visita rápida

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 Method editor:

alt-text

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 a C_XXX command. Por exemplo, para criar uma variável do tipo dados, pode escrever:

C_DATE(MyDate) //Date type for MyDate variable

Even if it is usually not recommended, you can create variables simply by using them; you do not necessarily need to formally define them as you do with fields. 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 creates the variable, assigns it with both the (temporary) date type and a content. A variable created 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 C_XXX cannot change the type. In compiled mode, the type can never be changed, regardless of how the variable was created.

Comandos

Os comandos 4D são métodos integrados para realizar uma ação. All 4D commands, such as CREATE RECORD, or ALERT, are described in the 4D Language Reference manual, grouped by theme. 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 methods 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. Por exemplo, Read Mode é uma constante (valor 2). Predefined constants appear underlined by default in the 4D Method editor. Isso permite escrever código mais legível.

vRef:=Open document("PassFile";"TEXT";Read Mode) // abre documento em modo apenas leitura

Página 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. Uma linha de instrução realiza uma ação e pode ser simples ou complexa.

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))
//Fazer algo com o carácter se for um 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 (;). Os parâmetros estão disponíveis dentro do método chamado como variáveis locais numeradas sequencialmente: $1, $2,..., $n. A method can return a single value in the $0 parameter. Quando chamar um método, apenas digite seu nome:

$myText:="hello"
$myText:=Do_Something($myText) //Chamar o método Do_Something
ALERT($myText) //"HELLO"

//Aqui o código do método Do_Something
$0:=Uppercase($1)

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:=New formula(ALERT("Hello world!"))
$myText:="hello"
$myText:=Do_Something($myText) //Call the Do_Something method

To access a collection element, you have to pass the element number embedded in square brackets:

C_COLLECTION(myColl)
myColl:=New collection("A";"B";1;2;Current time)
myColl[3] //access to 4th element of the collection

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. You are already familiar with many operators.

OperadorOperaçãoExemplo
+Adição1 +2 = 3
Subtração3 - 2 = 1
*Multiplicação2 * 3 = 6
/Divisão6 / 2 = 3

Os operadores numéricos são apenas um dos tipos de operadores disponíveis. 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 dadosOperaçãoExemplo
NúmeroAdição1 + 2 adiciona os números e resultados em 3
StringConcatenação“Hello ” + “there” concatenates (joins together) the strings and results in “Hello there”
Data e NúmeroDate 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.

ExpressionTipoDescrição
“Hello”StringThe word Hello is a string constant, indicated by the double quotation marks.
“Hello ” + “there”StringTwo strings, “Hello ” and “there”, are added together (concatenated) with the string concatenation operator (+). The string “Hello there” is returned.
“Sr. ” + [People]NameStringTwo 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")StringEsta expressão utiliza Uppercase, um comando da linguagem, para converter a cadeia de caracteres "smith" em maiúsculas. Retorna "SMITH".
4NúmeroEsta é uma constante numérica, 4.
4 * 2NúmeroDois números, 4 e 2, são multiplicados utilizando o operador de multiplicação (*). O resultado é o número 8.
myButtonNúmeroEsta é uma variável associada a um botão. It returns the current value of the button: 1 if it was clicked, 0 if not.
!1997-01-25!DateThis is a date constant for the date 1/25/97 (January 25, 1997).
Current date+ 30DateThis 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?HoraThis is a time constant that represents 8 hours, 5 minutes, and 30 seconds.
?2:03:04? + ?1:02:03?HoraThis expression adds two times together and returns the time 3:05:07.
TrueParâmetrosEste comando devolve o valor Booleano TRUE.
10 # 20ParâmetrosThis 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”ParâmetrosThis is a logical comparison between two strings. They are not equal, so the expression returns FALSE.
My Picture + 50ImagemThis expression takes the picture in My Picture, moves it 50 pixels to the right, and returns the resulting picture.
->[People]NamePonteiroEsta expressão devolve um ponteiro ao campo chamado [People]Name.
Table(1)PonteiroThis is a command that returns a pointer to the first table.
JSON Parse (MyString)ObjetoThis is a command that returns MyString as an object (if proper format)
JSON Parse (MyJSONArray)CollectionThis is a command that returns MyJSONArray as a collection (if proper format)
Form.pageNumberPropriedade objectoAn object property is an expression that can be of any supported type
Col[5]Elemento de colecçãoA collection element is an expression that can be of any supported type
$entitySel[0]EntityA 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->)

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
  • /*...*/ para comentarios em linha ou multilinha.

Both styles of comments can be used simultaneously.

Single line comments (//)

Insert // at the beginning of a line or after a statement to add a single line comment. Exemplo:

/Este é um comentário
For($vCounter;1;100) //Starting loop
//comment
//comment
//comment
End for

Inline or multiline comments (/**/)

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