Skip to main content
  1. Lumesh Document/
  2. Lumesh Syntax/

Functions and Commands

1082 words·6 mins
Table of Contents

Functions and Commands

VI. Functions
#

Function Definition with fn
#

  • Defined using fn, supports default parameters and rest parameter collection.
     1fn add(a,b,c=10,*d) {
     2   return  a + b + c + len(c)
     3}
     4
     5# Equivalent to:
     6fn add(a,b,c=10,*d) {
     7   a + b + c + len(c)
     8}
     9
    10echo add(2, 3)  # Outputs 5
    11echo add(2,3,4, 5)  # Outputs 10

Lambda Expressions
#

  • Defined using ->.

    1let add = (x,y) -> x + y
  • Differences between lambda and regular functions:

    • Lambda does not support default parameters and return statements, nor does it support rest parameter collection.
    • Lambda supports partial application of parameters, returning subsequent lambdas.
  • Similarities: Both lambda and functions inherit the current environment variables and run in an isolated environment, without polluting the current environment.

Function Calls
#

Function names are followed immediately by () or ! to execute the function.

1# Custom functions can be called like this
2add(3,5)
3# Or like this
4add! 3 5   # Note the need to add the ! suffix to distinguish from command calls.

Distinguishing between function calls and command executions helps avoid name clashes, such as:

1# Test case 6: Function and command name clash
2fn ls() { echo "My ls" }
3ls -l                # Executes the system command ls
4ls()                 # Calls the function
5ls!                  # When using the ! suffix, calls the function; this is a syntax sugar that flattens the parentheses.

Tips:

  • When the parameter is a literal lambda expression, please use the parentheses pattern; the flat pattern cannot be parsed.
  • Similarly, when the parameter is a logical operation like &&, please use the parentheses pattern or the flat pattern after grouping with parentheses.

Edge Cases:

  • When function names conflict, the new definition will override the old one.
  • Calling a function with a mismatched number of parameters will throw an error. For example: [ERROR] arguments mismatch for function add: expected 3, found 1

Chained Calls
#

1[1,3,5,6].sum()
2
3"hello world"
4    .split(' ')
5    .map(s -> s.to_upper())
6    .join('-')
7    .green()

For commonly used data types, chained calls can be used directly, including: String, List, Map, Time, Integer, Float, Range

Decorators
#

Decorators are a special type of higher-order function that can insert required logic before and after the execution of a specific function.

 1# Using a decorator in function definition
 2@timeit
 3fn test(n){
 4  for i in 0..n {
 5    n += i
 6  }
 7  print 'sum is' n
 8}
 9
10# Decorator function
11fn timeit(){
12    fn wrapper(func_t){
13        (args_t) -> {
14            let start = Time.stamp_ms()                       # Logic before function execution
15            func_t(args_t)                                  # Function execution
16            let end = Time.stamp_ms()                         # Logic after function execution
17            print '>Time:'.green().bold() (end - start) 'ms'
18        }
19    }
20}

Please Note

  • All variable names defined by decorators applied to the same function cannot be duplicated. For example, if a second decorator is to be applied to the test function above, that decorator cannot use the variable names func_t or args_t. This is a trade-off for performance and convenience; for higher performance, we accept this small inconvenience.

VII. Running System Commands
#

Command Invocation
#

In Lumesh, you can conveniently run programs just like in other shells, such as:

1ls
2ls -l
  • Multiple commands: if the preceding command fails, subsequent commands will not continue executing;

  • Unless the error has been handled:

    1ls '/0' ; ls -l         # The latter will not execute
    2ls '/0' ?. ; ls -l      # The latter will execute
  • Use the ^ suffix to force command mode

    1let id = 5
    2id^ -u              # Informs the system this is a command
  • Empty parameter commands

    1notepad.exe             # If not recognized as a command (e.g., on Windows, commands with extensions)
    2notepad.exe _           # Pass an empty parameter to force recognition as a command

Wildcard Expansion
#

In Lumesh, ~ directory expansion and * expansion are also supported:

1ls ~/**/*.md

But does not support {} expansion as in bash.

Background Execution and Output Control Characters
#

  • Like bash, use the & symbol to run programs in the background.

  • Output control character &: we adopt a simpler way to suppress command output.

  • Output control characters apply only to commands, not to functions.

    1thunar &         # run in background, and shutdown stdout and stderr
    2ls &-            # shutdown stdout
    3ls /o &?         # shutdown stderr
    4ls  /o '/' &+            # shutdown stdout and stderr
    5
    6ls  /o '/' &? | bat            # shutdown stderr and pipe stdout to next cmd.

Here is a comparison of syntax with bash:

TaskLumeshbash
Background Runcmd &cmd &
Close Std Outputcmd &-cmd 1> /dev/null
Close Error Outputcmd &?cmd 2> /dev/null
Close All Outputcmd &.cmd 2>&1 > /dev/null
Output Error to Std*cmd &+cmd 2>&1

Output Channels
#

  • Standard Output (defined the same as in bash, can use &- to close standard output)

  • Error Output (defined the same as in bash, can use &? to close standard output, can use error handling symbols to handle errors)

  • Structured Data Channel (specific to Lumesh, can be disabled in configuration)

    Set let LUME_PRINT_DIRECT= False in the configuration file to disable the structured data channel.

     1❯ ls
     2Documents  Downloads  dprint.json  typescript        # Standard output
     3
     4❯ ls /x
     5ls: cannot access '/x': No such file or directory    # Error output
     6[ERROR] command `ls` failed: "exit status: 2"        # Lumesh error capture, target of error handling symbols
     7
     83 + 5
     98                           # Standard output
    10  >> [Integer] <<           # Structured channel data type hint
    118                           # Structured channel (operation result)

Output Printing

  • print consumes the operation result and prints it to standard output.

  • tap prints to standard output but retains the operation result.

    1❯ print 3+5
    28
    3
    4❯ tap 3+5
    58
    6
    7  >> [Integer] <<
    88

VIII. Built-in Function Library
#

Lumesh includes a large number of practical function libraries to facilitate convenient functional programming, such as:

  • Collection Operations: List.reduce, List.map
  • File System: Fs.ls, Fs.read, Fs.write
  • String Processing: String.split, String.join, regex module, formatting module
  • Time Operations: Fs.now, Fs.format
  • Data Conversion: Into module, From module
  • Mathematical Calculations: Complete mathematical function library
  • Logging: Log module
  • UI Operations: Ui.pick, Ui.confirm

You can view available modules and functions using the help command. You can view specific module functions using the help String command.

Built-in functions support three calling methods:

1String.red(msg)
2String.red msg
3String.red! msg

And also support chained calls and pipeline method calls:

1msg.red()
2msg | .red()

For detailed content, please continue reading:

Related