Jump to content

Search the Community

Showing results for tags 'string'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Multi Theft Auto: San Andreas 1.x
    • Support for MTA:SA 1.x
    • User Guides
    • Open Source Contributors
    • Suggestions
    • Ban appeals
  • General MTA
    • News
    • Media
    • Site/Forum/Discord/Mantis/Wiki related
    • MTA Chat
    • Other languages
  • MTA Community
    • Scripting
    • Maps
    • Resources
    • Other Creations & GTA modding
    • Competitive gameplay
    • Servers
  • Other
    • General
    • Multi Theft Auto 0.5r2
    • Third party GTA mods
  • Archive
    • Archived Items
    • Trash

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Member Title


Gang


Location


Occupation


Interests

Found 6 results

  1. Hello dear MTA players,My name is Eren(Shady) ,today I will show you String and Strings types in a simple and short way with examples, this string formula, which I needed very much at the time, is very useful for me today, so I decided to use it and make this tutorial to learn more, I hope I was able to explain it well. Strings and String Methods In Lua, a string is a sequence of characters that represents text data. Strings are used extensively in programming for storing and manipulating text-based information. In this tutorial, we will explore the different string types in Lua and how to manipulate them. Single Quoted Strings A single-quoted string is created by enclosing a sequence of characters between two single quotes. For example: local str = 'Hello, world!' Single-quoted strings are useful for creating short, simple strings that do not contain any special characters. If you need to include a single quote character within a single-quoted string, you can escape it using a backslash: local str = 'It\'s a beautiful day!' Double Quoted Strings A double-quoted string is created by enclosing a sequence of characters between two double quotes. For example: local str = "Hello, world!" Double-quoted strings are useful for creating more complex strings that may contain special characters such as escape sequences or variables. If you need to include a double quote character within a double-quoted string, you can escape it using a backslash: local str = "She said, \"Hello!\"" Long Strings A long string is created by enclosing a sequence of characters between two square brackets. For example: local str = [[This is a long string that spans multiple lines]] Long strings are useful for creating strings that contain multiple lines of text, such as paragraphs or blocks of code. They can also be used to create strings that contain special characters without the need for escape sequences. String Concatenation You can concatenate two or more strings together using the .. operator. For example: local str1 = "Hello" local str2 = "world" local str3 = str1 .. ", " .. str2 .. "!" In this example, str3 would contain the string "Hello, world!". String Manipulation Lua provides a number of built-in functions for manipulating strings. Some of the most commonly used string functions include: string.sub(str, start, end): Returns a substring of str starting at start and ending at end. string.len(str): Returns the length of str. string.lower(str): Returns str with all letters in lowercase. string.upper(str): Returns str with all letters in uppercase. string.rep(str, n): Returns str repeated n times. Pattern Matching Lua also provides a powerful pattern matching library that can be used to search and manipulate strings based on a pattern. The string.gsub() function is particularly useful for replacing parts of a string that match a pattern with another string. Here is an example of using string.gsub() to replace all occurrences of the word "dog" with the word "cat" in a string: local str = "I have a dog, but my neighbor has two dogs." local newStr = string.gsub(str, "dog", "cat") In this example, newStr would contain the string "I have a cat, but my neighbor has two cats.". The string we are working with is "My name is John_Smith". We want to swap the order of the two names in the string, so that it becomes "My name is Smith_John". str = "My name is John_Smith" new_str = string.gsub(str, "(John)_(Smith)", "%2_%1") Here's how the code achieves this: string.gsub() is called with the original string str, and two patterns to match: (John) and (Smith). The parenthesis around "John" and "Smith" indicates that they are capture groups, which means that any match to these patterns will be stored as a variable. The replacement string "%2_%1" is passed as the third argument to gsub(). This string contains the % modifier, which is used to reference the captured groups. In this case, %2 refers to the second captured group ("Smith"), and %1 refers to the first captured group ("John"). gsub() performs the substitution on the original string, replacing the matched pattern (John)_(Smith) with the replacement string "%2_%1". The resulting string, "My name is Smith_John", is stored in the new_str variable. So essentially, this code swaps the order of two captured groups in a string using the gsub() function and the % modifier. But how to make it dynamic and so it matches even if it's another First and Lastname (like Bruce_Willis) ? Well, we can use what we call character classes. They are special "codes" to match a specific type of thing in your string. For example, %a means "any letter", %d means "any digit". Here is the full list those character classes: . all characters %a letters %c control characters %d digits %l lower case letters %p punctuation characters %s space characters %u upper case letters %w alphanumeric characters %x hexadecimal digits %z the character with representation 0 So in our previous example we can replace the pattern like so: str1 = "My name is John_Smith" str2 = "My name is Bruce_Willis" new_str1 = string.gsub(str1, "(%a+)_(%a+)", "%2_%1") new_str2 = string.gsub(str2, "(%a+)_(%a+)", "%2_%1") new_str will contain "My name is Smith_John" and new_str2 will contain "My name is Willis_Bruce". So it works as long as it finds one or more letters followed by an underscore followed by one or more letters. Here I also used a modifier (+) to tell the matcher he has to look for 1 or more repetition of a letter. Here are the list of the possible modifiers: + 1 or more repetitions * 0 or more repetitions - also 0 or more repetitions ? optional (0 or 1 occurrence) More infos here In Lua, "\n" is known as a newline character. It is used to represent a new line of text in a string. When a newline character is encountered in a string, it tells the computer to move the cursor to the beginning of the next line. For example : local myString = "Hello\nworld" print(myString) In this example, the string "Hello" is followed by "\n" which tells Lua to add a new line. The string "world" is then printed on the next line. Output : Hello world You can also use multiple "\n" characters in a row to add multiple new lines: local myString = "This is the first line.\n\nThis is the third line." print(myString) In this example, two "\n" characters are used to add two new lines between the first and third lines. Output : This is the first line. This is the third line. You can use newline characters to format your text in a more readable way. For example, if you want to print a list of items, you can use a newline character to separate each item: local myString = "List of items:\n- Item 1\n- Item 2\n- Item 3" print(myString) In this example, the string "List of items:" is followed by "\n" to add a new line, then each item is listed on a new line with a hyphen (-) to indicate a bullet point. Output : List of items: - Item 1 - Item 2 - Item 3 In summary, "\n" is a newline character in Lua that is used to add a new line in a string. It is a useful tool for formatting text and making it more readable. string.sub(str, start, end): This function returns a substring of the input string, str, starting at the start index and ending at the end index. For example: local str = "Hello, World!" local subStr = string.sub(str, 7, 12) -- This will return "World!" string.len(str): This function returns the length of the input string, str. For example: local str = "Hello, World!" local len = string.len(str) -- This will return 13 string.lower(str): This function returns a new string with all letters in the input string, str, converted to lowercase. For example: local str = "HeLLo, WoRLd!" local lowerStr = string.lower(str) -- This will return "hello, world!" string.upper(str): This function returns a new string with all letters in the input string, str, converted to uppercase. For example: local str = "HeLLo, WoRLd!" local upperStr = string.upper(str) -- This will return "HELLO, WORLD!" string.rep(str, n): This function returns a new string that is n copies of the input string, str. For example: local str = "Hello" local repStr = string.rep(str, 3) -- This will return "HelloHelloHello" string.format string.format is a Lua function that is used to format strings based on a pattern. The basic syntax of string.format is: string.format(formatstring, ...) Here, formatstring is a string that contains placeholders for values that you want to include in the formatted string. The placeholders are indicated by % symbols followed by a letter that indicates the type of value to be included. The ... is a variable argument list that contains the values to be formatted. Here are some of the most commonly used placeholders in string.format: %s: Inserts a string value %d or %i: Inserts an integer value %f: Inserts a floating-point value %%: Inserts a literal % symbol Let's see some example codes that use string.format: -- Example 1: Formatting a simple string local name = "John" local age = 25 local formattedString = string.format("My name is %s and I am %d years old.", name, age) print(formattedString) -- Output: My name is John and I am 25 years old. -- Example 2: Formatting a floating-point value with a specific precision local pi = math.pi local formattedString = string.format("The value of pi is approximately %.2f.", pi) print(formattedString) -- Output: The value of pi is approximately 3.14. -- Example 3: Formatting an integer value with leading zeros local number = 42 local formattedString = string.format("The answer is %04d.", number) print(formattedString) -- Output: The answer is 0042. In Example 1, we format a simple string with placeholders for name and age. In Example 2, we format a floating-point value for pi with a precision of two decimal places. In Example 3, we format an integer value with leading zeros to make it four digits long. Hope this helps!
  2. Good night, good morning, or good afternoon! I am a beginner on the moon, I would like to know how to use string.find, or some other method, to start a mod that has a particular tag. In my case, I put the tag "[VZR]" in my mods. Thank you.
  3. Eae galera. Encontrei um bug na lista do meu painel de ranking. Onde os valores numéricos que são decimais não ficam na ordem correta do maior pro menor nem vice-versa. Eles ficam aleatórios. Os valores inteiros ficam organizados corretamente. Já configurei para a lista considerá-los como números usando guiGridSetItemText e setando o parâmetro number como true. Ele organiza os valores inteiros corretamente, mas os valores float não. Alguém sabe como resolver? Segue a print mostrando o problema: Os valores estão sendo cortados para somente 3 casas decimais usando a função math.round, que está funcionando perfeitamente. Parte do script que preenche a lista:
  4. Olá senhores. Estou fazendo um script cujo menu GUI é construído a partir de informações de um arquivo.xml No arquivo.xml, estão os textos que devem aparecer nos botões e texto do painel. O problema é que em alguns botões, preciso colocar quebra de linha. (\n) [contra-barra + N) Se eu criar um botão dentro do script.lua e colocar um texto com quebra de linha, funciona normal. Porém se eu obter esse mesmo texto com quebra de linha do arquivo.xml, ele carrega \n no lugar da quebra de linha, como se o \n deixasse de funcionar. buttons[i][k] = guiCreateButton (250, 50*(k-1)-30, 150, 40, xmlACLValues[i][2], false, PainelTAG) O valor xmlACLValues[2] é igual a "recruta\n(membro)" e foi obtido do arquivo.xml. O botão é criado corretamente, porém a quebra de linha não funciona e o botão fica assim: Se eu setar o texto de dentro do script.lua, dai a quebra de linha funciona normal usando a mesma string "recruta\n(membro)". xmlACLValues[i][2] = "recruta\n(membro)" buttons[i][k] = guiCreateButton (250, 50*(k-1)-30, 150, 40, xmlACLValues[i][2], false, PainelTAG) Alguém sabe por que ocorre isso e como resolver? Já tentei usar tostring, string.gsub (parece tolice substituir um \n por outro \n mas eu tava na esperança de ele criar um \n novo que funcione.) Obs: Eu sei que é possível evitar isso entupindo de espaços até a segunda parte ir pra baixo, mas eu não queria fazer gambiarras. Arquivo.xml:
  5. i got this error, but the script working fine... -.- bad argument #1 to 'len' (string expected, got boolean) how to fix this? code: function currentSongName() local radio_title = getElementData(resourceRoot, "radio.title") if string.len(radio_title) >= x*0.0625 then radio_title = string.sub(radio_title, 1, 80)..".." end for i, shading in pairs ( offsetShadings ) do dxDrawText("Radio: "..radio_title, xD+shading[1], yD+shading[2], xD, yD+textHeight, tocolor ( 0, 0, 0, 255 ), scale, font, "left", "center", false, false, true, true) end dxDrawText("Radio: #ffffff"..radio_title, xD, yD, xD, yD+textHeight, tocolor ( 70, 215, 0, 255 ), scale, font, "left", "center", false, false, true, true) end addEventHandler('onClientRender', root, currentSongName)
  6. Не нашел информации в Русском разделе MTA о функции string.upper. Проблема состоит в том, что при попытке перевести все символы строки в ВВЕРХНИЙ регистр (для кириллических символов), этого не происходит. Подскажите в чем может быть проблема? Кодировка файла UTF-8 без BOM. local number = tostring(guiGetText(GUINumch.edit[1])) number = string.upper(number) number = number:gsub("%s", {["А"] = "A", ["В"] = "B", ["С"] = "C", ["К"] = "K", ["М"] = "M", ["Н"] = "H", ["О"] = "O", ["Р"] = "P", ["С"] = "C", ["Т"] = "T", ["У"] = "Y", ["Х"] = "X"}) local b1e = tostring(string.sub(number,1,2)) local c1e = tostring(string.sub(number,3,3)) local c3e = tostring(string.sub(number,4,4)) local c4e = tostring(string.sub(number,5,5)) local b2e = tostring(string.sub(number,6,7)) local b3e = tostring(string.sub(number,8,9)) outputChatBox("#FF6146 Результат: "..b1e..c1e..c3e..c4e..b2e..b3e, 255, 255, 255, true) Фрагмент кода, в котором string.upper не работает.
×
×
  • Create New...