GameMaker string functions let you create, inspect, search, edit, split, and format text in GML. The essentials include string() for conversion, string_length() for measuring, string_copy() for extracting text, and string_pos() for searching; together they cover many common tasks such as building interface messages and checking player input.
What strings are in GameMaker
A string is a sequence of text characters, such as a player name, a menu label, a dialogue line, or a number displayed in a score readout. In GML, strings are values you can store in variables, pass to functions, and combine with other strings. For example, var player_name = "Mira"; stores text, while var message = "Welcome, " + player_name; creates a longer message.
String functions are useful because text is not always ready to display or compare as soon as it enters a game. A player may type extra spaces, a save file may contain a value represented as text, or a dialogue system may need to find and replace a token. The relevant functions operate on strings and return either another string, a number, or—in some cases—an array of strings.
GML also supports ordinary operators for common work. The plus operator joins strings, and equality or comparison operators can compare values. Dedicated functions are helpful when you need a specific operation, such as extracting a substring or changing letter case, rather than simply combining text.
Converting values and combining text
Use string(value) to convert a value to its text representation. This is especially helpful when assembling a message that includes a number. For example, var score_text = "Score: " + string(score); makes the conversion explicit before joining the score to the label. This keeps the intention clear and avoids relying on implicit conversion in code that may later be changed.
Concatenation creates a new string; it does not edit the original variable in place. You can assign the result back to the same variable when that is what you want:
var greeting = "Hello, ";creates the first part.greeting += player_name;appends the name to it.greeting += "!";adds punctuation.
For a label that updates every frame, consider whether it needs to be rebuilt every frame or only when its underlying value changes. The string functions themselves are straightforward, but unnecessarily constructing many temporary strings in frequently run code can make logic harder to follow and may add avoidable work.
Measuring and extracting characters
string_length(text) returns the length of a string. It can help with input limits, simple layout decisions, and checking whether a field is empty. For instance, if (string_length(player_name) == 0) checks whether the name has no characters. If spaces should count as empty too, trim the text first, as described below.
string_char_at(text, index) returns the character at a specified position. String positions in the common GML string functions are one-based: the first character is at position 1, not position 0. Likewise, string_copy(text, index, count) returns a portion of a string beginning at the given position and containing the requested number of characters. For example, string_copy("GameMaker", 1, 4) returns "Game".
That indexing convention matters when translating an idea from a language or data structure that uses zero-based positions. A loop that starts at zero and passes its counter to string_char_at() will not address the first character as intended. A typical character-by-character loop uses positions from 1 through the string length:
- Get the total with
string_length(text). - Start the position at 1 and continue while it is no greater than the length.
- Read each character with
string_char_at(text, position).
For text containing accented letters, symbols, or emoji, do not assume that a character behaves like a single byte in every representation or that visual width equals character count. If a game edits or limits multilingual text, check the behavior with the actual characters and target runtime rather than treating string length as a measure of on-screen width.
Searching and replacing text
string_pos(search, text) searches for a substring and returns its position in the text, or 0 when it is not found. This makes it useful for simple checks, such as deciding whether a command contains a separator. For example, var separator_at = string_pos(":", command); stores the colon’s position if one exists. Remember that a successful position is one-based, while 0 signals no match.
string_count(search, text) counts how many times a substring occurs. For example, it can count a punctuation mark or a token in a line of dialogue. It is not a substitute for parsing a complex language: if the same characters can have different meanings depending on context, a parser or a more deliberate scan may be needed.
For substitutions, string_replace(text, search, replacement) replaces the first matching occurrence, while string_replace_all(text, search, replacement) replaces every occurrence. The distinction is important in a template such as "{name} defeated {name}": replacing only the first token leaves the second one unchanged. Use the all-occurrences version when every matching token should change, and check the function’s arguments carefully—the original text comes first.
Editing, trimming, and changing case
string_insert(insert_text, text, index) inserts text at a position, and string_delete(text, index, count) removes a span. These are useful for small text edits, but the one-based position rule still applies. To add an exclamation mark after "Hello", for example, insert it at position 6, just after the five existing characters.
Whitespace can cause subtle input bugs. A name that looks like "Mira" may actually contain spaces before or after the visible letters. string_trim(text) removes leading and trailing whitespace; string_trim_start(text) and string_trim_end(text) target one side. Trimming is not the same as removing spaces inside a name: "Mira Vale" retains its internal space.
string_lower(text) and string_upper(text) return lowercase and uppercase forms. They can normalize text for simple case-insensitive checks—for example, converting a typed command and the expected command to the same case before comparing them. Keep the original text if capitalization is meaningful for display. Language-specific case rules can also be more complicated than changing each character independently, so test localized input where it matters.
Formatting numbers for display
string_format(value, total_width, decimal_digits) converts a real number to a formatted string with a requested field width and number of decimal places. This can help keep a score or measurement visually consistent. For example, string_format(12.5, 6, 2) formats the value with two decimal places in a field of width six; the returned text can then be joined to a label or drawn.
Formatting for display is different from converting text back into a number. Use real(text) when you need to convert numeric text to a real value for calculations. Do not treat a formatted display string as a robust input-validation method: a player can enter unexpected characters, separators, or blank text. Validate input according to the rules of your game before using it in calculations, and test how invalid input is handled in the runtime you target.
Also distinguish a string’s stored value from its presentation on screen. String formatting does not choose a font, set alignment, or guarantee that the text fits in a UI element. Those concerns belong to drawing and interface layout. A string can be correctly formatted and still be clipped if the UI does not allow enough room.
Splitting and joining strings
string_split(text, separator) divides a string at a separator and returns an array of pieces. This is handy for uncomplicated formats such as a line of comma-separated settings or a dialogue line divided by a known marker. For example, splitting "red|green|blue" on "|" gives separate text values that can be read by array index.
string_join(array, separator) performs the reverse kind of task: it joins array elements into a string with a separator between them. Splitting and joining can simplify basic data handling, but neither function automatically defines a complete file format. A separator that can also appear inside a field needs an escaping rule or a different data format, or splitting may divide a value incorrectly.
After splitting, check the array’s size before reading an element at an expected position. Input may be missing a separator or contain fewer fields than expected. A safe workflow is to split, verify the number of pieces, and only then convert or use each piece. For data that must survive game updates or contain arbitrary player text, use a structured serialization approach rather than inventing an ambiguous delimiter convention.
Choosing the right function and avoiding mistakes
Pick a function based on the operation, not just its name. A useful quick guide is:
- Convert a number or other value to text:
string(). - Check length or read a character:
string_length()orstring_char_at(). - Extract a section:
string_copy(). - Find or count a match:
string_pos()orstring_count(). - Replace one or every match:
string_replace()orstring_replace_all(). - Clean edges or normalize case:
string_trim(),string_lower(), orstring_upper(). - Break text into fields or combine array values:
string_split()orstring_join().
Common errors usually come from assumptions around positions, replacement scope, or input quality. Check whether a search result of 0 means no match before using it as an index. Decide whether only the first occurrence or all occurrences should change. Trim user-entered values when leading or trailing spaces should not matter, but do not strip meaningful spaces from names or sentences.
Another misconception is that a string function automatically makes text safe or suitable for every purpose. Replacing a few characters is not a general solution for parsing, security, or file-format correctness. Keep text handling aligned with its use: display text, a command, a player-entered name, and serialized data have different requirements.
Frequently Asked Questions
How do I join strings in GameMaker?
Use the plus operator, such as "Lives: " + string(lives). Converting the number with string() makes the intended text conversion explicit.
Does GameMaker string indexing start at 0 or 1?
The standard string functions such as string_char_at(), string_copy(), and string_delete() use positions starting at 1. The first character is position 1; a search that finds no match with string_pos() returns 0.
How can I check whether text contains a word?
Call string_pos("word", text) and check whether the result is greater than 0. If case should not matter, compare normalized forms, for example by applying string_lower() to both the input and search term.
What is the difference between string_replace and string_replace_all?string_replace() changes the first matching occurrence. string_replace_all() changes every matching occurrence in the text.
How do I remove spaces around player input?
Use string_trim(input_text) to remove whitespace at the beginning and end. It preserves spaces inside the text, so a multiword name remains separated.
Can I use string functions to validate a number?
String functions can help inspect or clean text, and real() converts numeric text to a real value. For player input, define and check the accepted format before relying on the converted result; conversion alone is not a complete validation policy.
Related
- Split Sheet Meaning: What It Is and How It Works
- Snowflake SELECT SPLIT Example: Parse Delimited Strings
- Split Data in R for Training and Testing: A Practical Guide
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Column Comparison: Formulas, Methods, and TipsTo compare two Excel columns, use a row-by-row equality test when corresponding cells should match, or check whether…
- Databricks SQL SPLIT Function: Syntax and ExamplesIn Databricks SQL, split(str, regex [, limit]) divides a string wherever it matches a regular expression and returns…
- Excel XLOOKUP and Power Query: How They Work TogetherExcel XLOOKUP and Power Query work together, but they do different jobs: Power Query imports, cleans, and combines…
- BMI Calculator Excel Formula: Steps, Examples, and TipsTo calculate BMI in Excel, divide weight in kilograms by height in meters squared. If weight is in…
- Break-Even Excel Formula: Calculate Units and SalesThe basic break-even formula in Excel is fixed costs divided by the contribution margin per unit: =B2/(B3-B4). If…
- Search Excel for Text: Find Cells and Match ContentTo search Excel for text, press Ctrl+F on Windows, type the word or phrase, then press Enter or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.