LEFT$

Syntax

Syntax: LEFT$(string$, n)
Source: pb_cg_emit_left_builtin (pb_codegen.c:2820)

Description

Returns the leftmost n characters of string$. The function extracts the first n characters from the source string and returns them as a new string. The original string is not modified.

If n is less than 1, an empty string is returned. If n exceeds the length of string$, the entire string is returned. The n parameter is automatically clamped to a valid range at the assembly level.

Common uses include extracting filename extensions, parsing fixed-width data formats, pulling prefixes from identifiers, and truncating display text. Unlike MID$, LEFT$ always starts from position 1.

Parameters

ParameterDescription
string$The source STRING expression. Can be a literal, variable, or any expression that evaluates to a string.
nNumber of characters to extract from the left side. A numeric expression (byte, integer, long). Clamped to 0..capacity-1.

Return Value

A new STRING containing the leftmost n characters of string$.

Example

FUNCTION PBMAIN() AS LONG
    LOCAL full$, part$ AS STRING
    LOCAL count AS LONG
    
    full$ = "Hello World"
    count = 5
    
    ' Basic extraction
    part$ = LEFT$(full$, 5)       ' part$ = "Hello"
    PRINT "First 5 chars: "; part$
    
    ' Using a variable for the count
    part$ = LEFT$(full$, count)   ' same result
    PRINT "First "; count; " chars: "; part$
    
    ' Count larger than string length
    part$ = LEFT$(full$, 999)     ' part$ = "Hello World"
    PRINT "Entire string: "; part$
    
    ' Count zero or negative
    part$ = LEFT$(full$, 0)       ' part$ = ""
    PRINT "Empty result: ["; part$; "]"
    
    ' Practical: extract drive letter from path
    full$ = "C:\Windows\System32\"
    part$ = LEFT$(full$, 2)       ' part$ = "C:"
    PRINT "Drive: "; part$
    
    FUNCTION = 0
END FUNCTION

Generated Assembly

Source: pb_cg_emit_left_builtin (pb_codegen.c:2820)
; Clamp n to [0, buffer_capacity-1]
cmp    rax, 0
jge    __pb_left_count_nonneg_N
xor    rax, rax
__pb_left_count_nonneg_N:
cmp    rax, <capacity-1>
jle    __pb_left_count_cap_N
mov    rax, <capacity-1>
__pb_left_count_cap_N:
mov    [rbp - print_len_offset], rax   ; effective count

lea    rcx, [rbp - asciiz_scratch]     ; dest buffer
mov    rdx, [rbp - print_ptr_offset]   ; source
mov    r8, [rbp - print_len_offset]
add    r8, 1                           ; count + 1 for NUL
call   [__imp_lstrcpynA]               ; lstrcpynA(dest, src, n+1)
lea    rax, [rbp - asciiz_scratch]     ; return buffer ptr

Notes