﻿---
title: Programming Languages Cheat Sheet
date: 2025-05-19
excerpt: Lua, JavaScript, Go, Python, Java 数据结构、基本语法和重要API的快速参考
tags:
  - Lua
  - JavaScript
  - Go
  - Python
  - Java
cover: https://assets.vluv.space/cover/Lang/Python/AnimeChillPool.webp
---

<script data-swup-reload-script type="module" src="/js/components/tab.js"></script>

> [!tldr] Cheat Sheet
>
> 多语言数据结构、基本语法和重要API的快速参考指南。

## Data Structures

<x-tabs>

<x-tab title="Python" sync-id="python" active>

| 特性         | List | Tuple | Set  | Dict     | Queue     | Stack  |
| ------------ | ---- | ----- | ---- | -------- | --------- | ------ |
| Syntax       | `{python} []` | `{python} ()`  | `{python} {}` | `{python} {k: v}` | `{python} Queue()` | `{python} list` |
| Mutability   | ✅    | ❌     | ✅    | ✅        | ✅         | ✅      |
| Ordered      | ✅    | ✅     | ❌    | ✅        | ✅         | ✅      |
| Duplicates   | ✅    | ✅     | ❌    | ❌        | ✅         | ✅      |
| Index access | ✅    | ✅     | ❌    | ❌        | ❌         | ✅      |
| Slicing      | ✅    | ✅     | ❌    | ❌        | ❌         | ✅      |

```python
# List - 可变列表
my_list = [1, 2, 3]           # 创建列表
my_list.append(4)             # 添加元素到末尾
my_list[1] = 10               # 修改索引为1的元素
subset = my_list[1:3]         # 切片：获取索引1到3的子列表（不包含3）

# Tuple - 不可变元组
my_tuple = (1, 2, 3)          # 创建元组
item = my_tuple[0]            # 索引访问

# Set - 集合，自动去重
my_set = {1, 2, 3}            # 创建集合
my_set.add(4)                 # 添加元素
union = set1 | set2           # 并集
intersection = set1 & set2    # 交集

# Dict - 字典，键值对
my_dict = {"a": 1, "b": 2}    # 创建字典
value = my_dict.get("c", 0)   # 获取键值，不存在时返回默认值0
my_dict["d"] = 4              # 添加或修改键值对
keys = my_dict.keys()         # 获取所有键
```

</x-tab>

<x-tab title="Go" sync-id="go">

| 特性         | Slice | Array | Map       | Queue/Stack |
| ------------ | ----- | ----- | --------- | ----------- |
| Syntax       | `{go} []T` | `{go} [n]T`| `{go} map[K]V` | `{go} slice`    |
| Mutability   | ✅    | ✅    | ✅        | ✅          |
| Ordered      | ✅    | ✅    | ❌        | ✅          |
| Duplicates   | ✅    | ✅    | ❌        | ✅          |
| Index access | ✅    | ✅    | ❌        | ✅          |

> [!NOTE] Go 数据结构语法说明
> - `{go} []T`: Slice（切片），动态数组，长度可变，T 为元素类型
> - `{go} [n]T`: Array（数组），固定长度数组，n 为长度，T 为元素类型
> - `{go} map[K]V`: Map（哈希表），K 为键类型，V 为值类型

```go
// Slice - 动态数组，长度可变
slice := []int{1, 2, 3}        // 创建并初始化 slice
slice = append(slice, 4)       // 添加元素到末尾
slice[1] = 10                  // 修改索引为1的元素
subset := slice[1:3]           // 切片操作，获取索引1到3的子切片（不包含3）

// Array - 固定长度数组，长度不可变
arr := [3]int{1, 2, 3}         // 创建长度为3的 int 数组
arr[0] = 5                     // 修改元素

// Map - 哈希表，键值对存储
m := map[string]int{"a": 1, "b": 2}  // 创建并初始化 map
value, exists := m["c"]              // 通过键获取值和存在状态
m["d"] = 4                           // 添加或修改键值对
delete(m, "a")                       // 删除键值对

// Stack 操作（使用 slice 实现）
stack := []int{}               // 创建空 stack
stack = append(stack, 1)       // push：入栈
top := stack[len(stack)-1]    // peek：查看栈顶元素
stack = stack[:len(stack)-1]  // pop：出栈

// Queue 操作（使用 slice 实现）
queue := []int{}              // 创建空 queue
queue = append(queue, 1)       // enqueue：入队
front := queue[0]             // peek：查看队首元素
queue = queue[1:]             // dequeue：出队
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

| 特性         | Array | Object | Set   | Map      | Queue  | Stack  |
| ------------ | ----- | ------ | ----- | -------- | ------ | ------ |
| Syntax       | `{javascript} []`  | `{javascript} {}`   | `{javascript} new Set()` | `{javascript} new Map()` | `{javascript} array` | `{javascript} array` |
| Mutability   | ✅    | ✅     | ✅    | ✅        | ✅      | ✅      |
| Ordered      | ✅    | ❌     | ✅    | ✅        | ✅      | ✅      |
| Duplicates   | ✅    | ❌     | ❌    | ❌        | ✅      | ✅      |
| Index access | ✅    | ❌     | ❌    | ❌        | ❌      | ✅      |

```javascript
// Array - 数组
const arr = [1, 2, 3];                 // 创建数组
arr.push(4);                          // 添加元素到末尾
arr[1] = 10;                          // 修改索引为1的元素
const subset = arr.slice(1, 3);       // 切片：获取索引1到3的子数组（不包含3）
arr.forEach(x => console.log(x));     // 遍历数组
const mapped = arr.map(x => x * 2);   // 映射：对每个元素操作
const filtered = arr.filter(x => x > 1); // 过滤：筛选符合条件的元素

// Object - 对象
const obj = {a: 1, b: 2};             // 创建对象
const value = obj.c || 0;             // 获取属性，不存在时返回默认值
obj.d = 4;                            // 添加或修改属性
const keys = Object.keys(obj);        // 获取所有键
const values = Object.values(obj);    // 获取所有值

// Set - 集合，自动去重
const set = new Set([1, 2, 2, 3]);    // 创建集合
set.add(4);                           // 添加元素
set.has(1);                           // 检查元素是否存在
set.delete(1);                        // 删除元素

// Map - 键值对映射
const map = new Map([['a', 1], ['b', 2]]); // 创建 map
map.set('c', 3);                       // 设置键值对
map.get('a');                          // 获取值
map.has('a');                          // 检查键是否存在
```

</x-tab>

<x-tab title="Java" sync-id="java">

| 特性         | List | Array | Set  | Map       | Queue | Stack |
| ------------ | ---- | ----- | ---- | --------- | ----- | ----- |
| Syntax       | `{java} List` | `{java} T[]`| `{java} Set`| `{java} Map`     | `{java} Queue`| `{java} Stack`|
| Mutability   | ✅    | ❌     | ✅    | ✅        | ✅     | ✅     |
| Ordered      | ✅    | ✅     | ❌    | ❌        | ✅     | ✅     |
| Duplicates   | ✅    | ❌     | ❌    | ❌(key)   | ✅     | ✅     |
| Index access | ✅    | ✅     | ❌    | ❌        | ❌     | ✅     |

```java
// List (ArrayList)
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.set(1, 10);
List<Integer> subList = list.subList(0, 2);
list.remove(Integer.valueOf(1));

// Set (HashSet)
Set<Integer> set = new HashSet<>();
set.add(1);
set.contains(1);
set.remove(1);

// Map (HashMap)
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.getOrDefault("c", 0);
map.containsKey("a");
Set<String> keys = map.keySet();

// Queue (LinkedList)
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
Integer front = queue.poll();

// Stack (Stack)
Stack<Integer> stack = new Stack<>();
stack.push(1);
Integer top = stack.pop();
Integer peek = stack.peek();
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

| 特性         | Table(Array) | Table(Dict) |
| ------------ | ------------ | ----------- |
| Syntax       | `{lua} {}`         | `{lua} {}`        |
| Mutability   | ✅           | ✅          |
| Ordered      | ✅           | ❌          |
| Duplicates   | ✅           | ❌(key)     |
| Index access | ✅           | ❌          |

```lua
-- Table as Array
arr = {1, 2, 3}
table.insert(arr, 4)
arr[2] = 10
table.remove(arr, 1)

-- Table as Dictionary
dict = {a = 1, b = 2}
dict["c"] = 3
dict.d = 4
value = dict.a or 0

-- Common table operations
count = #arr
for i, v in ipairs(arr) do
    print(i, v)
end
for k, v in pairs(dict) do
    print(k, v)
end
```

</x-tab>

</x-tabs>

## Basic Syntax

### Common Syntax

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Variables - 变量声明
x = 10                      # 整数
name = "Python"             # 字符串
is_active = True            # 布尔值

# Operators - 运算符
+, -, *, /, //, %, **       # 加减乘除、整除、取模、幂运算
==, !=, >, <, >=, <=        # 比较运算符
and, or, not                # 逻辑运算符
in, is                      # 成员检测、身份检测

# Functions - 函数定义
def greet(name):
    return f"Hello, {name}"
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Variables - 变量声明
var x int = 10                           // 完整声明
var name string = "Go"
isActive := true                        // 短变量声明（自动推导类型）

// Operators - 运算符
+, -, *, /, %                           // 算术运算符
==, !=, >, <, >=, <=                   // 比较运算符
&&, ||, !                               // 逻辑运算符

// Functions - 函数定义
func greet(name string) string {         // 参数类型和返回值类型
    return fmt.Sprintf("Hello, %s", name)
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Variables - 变量声明
let x = 10;                           // 可变变量
const name = "JavaScript";             // 不可变常量
let isActive = true;                   // 布尔值

// Operators - 运算符
+, -, *, /, %                         // 算术运算符
==, ===, !=, !==, >, <, >=, <=       // 比较运算符（== 值比较，=== 类型+值比较）
&&, ||, !                             // 逻辑运算符
in, instanceof                        // 成员检测、类型检测

// Functions - 函数定义
function greet(name) {
    return `Hello, ${name}`;
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Variables - 变量声明
int x = 10;                      // int 类型
String name = "Java";             // 字符串类型
boolean isActive = true;          // 布尔类型

// Operators - 运算符
+, -, *, /, %                    // 算术运算符
==, !=, >, <, >=, <=            // 比较运算符
&&, ||, !                        // 逻辑运算符
instanceof                       // 类型检测

// Methods - 方法定义
public String greet(String name) {
    return "Hello, " + name;
}
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Variables - 变量声明
globalVar = 10              -- 全局变量
local localVar = 20         -- 局部变量（推荐使用）
local name = "Lua"
local isActive = true

-- Operators - 运算符
+, -, *, /, %, ^            -- 算术运算符（^ 为幂运算）
==, ~=, >, <, >=, <=        -- 比较运算符（~= 为不等于）
and, or, not                -- 逻辑运算符

-- Functions - 函数定义
function greet(name)
    return "Hello, " .. name   -- .. 为字符串拼接
end
```

</x-tab>

</x-tabs>

## Control Flow

### Conditional Statements

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# If-elif-else
if condition:
    pass
elif condition2:
    pass
else:
    pass

# Ternary operator
result = "yes" if condition else "no"

# Nested conditions
if outer_condition:
    if inner_condition:
        pass
    else:
        pass
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// If-else if-else
if condition {
} else if condition2 {
} else {
}

// If with initialization
if x := getValue(); x > 0 {
    fmt.Println("positive")
} else {
    fmt.Println("non-positive")
}

// Switch statement
switch value {
case 1:
    fmt.Println("one")
case 2:
    fmt.Println("two")
default:
    fmt.Println("other")
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// If-else if-else
if (condition) {
} else if (condition2) {
} else {
}

// Ternary operator
result = condition ? "yes" : "no";

// Switch statement
switch (value) {
    case 1:
        console.log("one");
        break;
    case 2:
        console.log("two");
        break;
    default:
        console.log("other");
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// If-else if-else
if (condition) {
} else if (condition2) {
} else {
}

// Ternary operator
result = condition ? "yes" : "no";

// Switch statement
switch (value) {
    case 1:
        System.out.println("one");
        break;
    case 2:
        System.out.println("two");
        break;
    default:
        System.out.println("other");
}

// Switch expressions (Java 14+)
String message = switch (value) {
    case 1 -> "one";
    case 2 -> "two";
    default -> "other";
};
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- If-elseif-else
if condition then
elseif condition2 then
else
end

-- Nested conditions
if outer_condition then
    if inner_condition then
    else
    end
end

-- No ternary operator in Lua
-- Use if-else or logical operators
result = condition and "yes" or "no"
```

</x-tab>

</x-tabs>

### Loop Statements

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# For loop with range
for i in range(10):         # 0 to 9
    pass

for i in range(1, 11):     # 1 to 10
    pass

for i in range(0, 10, 2):  # 0, 2, 4, 6, 8
    pass

# For loop over iterable
for item in items:
    pass

for index, item in enumerate(items):
    pass

# While loop
while condition:
    pass

# Loop control
for i in range(10):
    if i == 5:
        break    # Exit loop
    if i == 3:
        continue # Skip to next iteration
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Traditional for loop
for i := 0; i < 10; i++ {
}

// For range over slice/array
for index, item := range items {
}

// For range over map
for key, value := range m {
}

// While loop (Go only has for)
for condition {
}

// Infinite loop
for {
}

// Loop control
for i := 0; i < 10; i++ {
    if i == 5 {
        break    // Exit loop
    }
    if i == 3 {
        continue // Skip to next iteration
    }
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Traditional for loop
for (let i = 0; i < 10; i++) {
}

// For...of loop (iterables)
for (const item of items) {
}

// For...in loop (object properties)
for (const key in obj) {
}

// While loop
while (condition) {
}

// Do-while loop
do {
} while (condition);

// Loop control
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;    // Exit loop
    }
    if (i === 3) {
        continue; // Skip to next iteration
    }
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Traditional for loop
for (int i = 0; i < 10; i++) {
}

// Enhanced for loop
for (int item : items) {
}

// While loop
while (condition) {
}

// Do-while loop
do {
} while (condition);

// Loop control
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;    // Exit loop
    }
    if (i == 3) {
        continue; // Skip to next iteration
    }
}

// Labeled loops (for nested loops)
outer: for (int i = 0; i < 3; i++) {
    inner: for (int j = 0; j < 3; j++) {
        if (i == 1 && j == 1) {
            break outer; // Exit outer loop
        }
    }
}
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Numeric for loop
for i = 1, 10 do          -- 1 to 10
end

for i = 1, 10, 2 do       -- 1, 3, 5, 7, 9
end

-- Generic for loop (ipairs for arrays)
for i, v in ipairs(arr) do
end

-- Generic for loop (pairs for dictionaries)
for k, v in pairs(dict) do
end

-- While loop
while condition do
end

-- Repeat until loop (like do-while)
repeat
until condition

-- Loop control
for i = 1, 10 do
    if i == 5 then
        break    -- Exit loop
    end
    if i == 3 then
        -- No continue in Lua, use if
    end
end
```

</x-tab>

</x-tabs>

### Language-Specific Syntax

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Lambda - 匿名函数
add = lambda x, y: x + y

# Classes - 类定义
class Person:
    def __init__(self, name):   # 构造函数
        self.name = name

    def greet(self):             # 实例方法
        return f"Hello, {self.name}"

# List Comprehension - 列表推导式
squared = [x**2 for x in range(10)]  # 生成0-9的平方数列表
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Multiple return values - 多返回值
func divide(a, b int) (int, error) {     // 返回结果和错误
    if b == 0 {
        return 0, errors.New("division by zero")  // 返回错误
    }
    return a / b, nil                   // 返回结果，错误为 nil
}

// Structs - 结构体
type Person struct {
    Name string                          // 结构体字段
    Age  int
}

func (p Person) Greet() string {        // 方法（值接收者）
    return fmt.Sprintf("Hello, %s", p.Name)
}

// Goroutines - 协程
go func() {                             // go 关键字启动协程
    fmt.Println("goroutine")
}()

// Channels - 通道（协程间通信）
ch := make(chan int)                    // 创建通道
go func() {
    ch <- 1                             // 发送数据到通道
}()
value := <-ch                           // 从通道接收数据
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Ternary - 三元运算符
result = condition ? a : b;

// Arrow Function - 箭头函数
const greet = (name) => `Hello, ${name}`;

// Objects - 对象定义
const person = {
    name: "John",
    greet() {                         // 对象方法
        return `Hello, ${this.name}`;
    }
};

// Array methods - 数组方法
items.forEach(item => console.log(item)); // 遍历数组
const mapped = items.map(x => x * 2);     // 映射数组
const filtered = items.filter(x => x > 1); // 过滤数组
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Ternary - 三元运算符
result = condition ? a : b;

// Classes - 类定义
public class Person {
    private String name;

    public Person(String name) {   // 构造方法
        this.name = name;
    }

    public String greet() {
        return "Hello, " + name;
    }
}

// Lambda - Lambda 表达式
Runnable r = () -> System.out.println("Hello");
Predicate<Integer> isEven = x -> x % 2 == 0;
List<Integer> evens = list.stream()
    .filter(isEven)                // Stream API 过滤
    .collect(Collectors.toList()); // 收集为 List
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
local greet = function(name)    -- 匿名函数
    return "Hello, " .. name
end

-- Multiple return values - 多返回值
function getCoordinates()
    return 10, 20
end

local x, y = getCoordinates()   -- 接收多个返回值

-- Tables as objects - table 作为对象使用
local person = {
    name = "John",
    greet = function(self)
        return "Hello, " .. self.name
    end
}
person:greet()                  -- 调用方法
```

</x-tab>

</x-tabs>

## Functions & Parameter Passing

### Function Definition & Calling

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Function definition
def greet(name, age=25):
    return f"Hello {name}, you are {age} years old"

# Positional arguments
result = greet("Alice", 30)

# Keyword arguments
result = greet(name="Bob", age=35)

# Default arguments
result = greet("Charlie")  # Uses default age=25

# Variable arguments
def func(*args, **kwargs):
    print(args)      # Tuple of positional args
    print(kwargs)    # Dict of keyword args

func(1, 2, 3, name="Alice", age=25)
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Function definition
func greet(name string, age int) string {
    return fmt.Sprintf("Hello %s, you are %d years old", name, age)
}

// Named return values
func calculate(a, b int) (sum, diff int) {
    sum = a + b
    diff = a - b
    return  // Returns named variables
}

// Variadic function
func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

result := greet("Alice", 30)
total := sum(1, 2, 3, 4, 5)
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Function declaration
function greet(name, age = 25) {
    return `Hello ${name}, you are ${age} years old`;
}

// Arrow function
const greetArrow = (name, age = 25) => `Hello ${name}, you are ${age} years old`;

// Rest parameters
function func(...args) {
    console.log(args);  // Array of arguments
}

// Destructuring parameters
const greetPerson = ({name, age}) => `Hello ${name}, age ${age}`;

result = greet("Alice", 30);
func(1, 2, 3, "hello");
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Method definition
public String greet(String name, int age) {
    return String.format("Hello %s, you are %d years old", name, age);
}

// Method overloading
public String greet(String name) {
    return greet(name, 25);  // Calls other method with default age
}

// Varargs method
public int sum(int... numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}

String result = greet("Alice", 30);
int total = sum(1, 2, 3, 4, 5);
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Function definition
function greet(name, age)
    age = age or 25  -- Default value
    return "Hello " .. name .. ", you are " .. age .. " years old"
end

-- Multiple return values
function getPerson()
    return "Alice", 30
end

-- Variable arguments
function sum(...)
    local total = 0
    for i, v in ipairs({...}) do
        total = total + v
    end
    return total
end

result = greet("Alice", 30)
name, age = getPerson()  -- Multiple assignment
total = sum(1, 2, 3, 4, 5)
```

</x-tab>

</x-tabs>

### Parameter Passing Mechanisms

<x-tabs>

<x-tab title="Python" sync-id="python" active>

| Type | Passing Mechanism | Behavior |
|------|------------------|----------|
| Immutable (int, str, tuple) | **Pass by object reference** | Cannot modify original |
| Mutable (list, dict, set) | **Pass by object reference** | Can modify original content |
| Objects | **Pass by object reference** | Can modify object attributes |

```python
# Immutable types - cannot modify original
def modify_int(x):
    x = 10  # Only modifies local copy
    return x

num = 5
result = modify_int(num)  # num is still 5

# Mutable types - can modify original
def modify_list(lst):
    lst.append(4)  # Modifies original list
    return lst

my_list = [1, 2, 3]
modify_list(my_list)  # my_list is now [1, 2, 3, 4]

# To avoid modifying mutable types
def safe_modify(lst):
    new_lst = lst.copy()  # Create copy
    new_lst.append(4)
    return new_lst
```

</x-tab>

<x-tab title="Go" sync-id="go">

| Type | Passing Mechanism | Behavior |
|------|------------------|----------|
| All types | **Pass by value** | Copies value to function |
| Pointers | **Pass by reference** | Can modify original via pointer |
| Slices/Maps/Channels | **Pass by value (reference types)** | Copy header, can modify underlying data |

```go
// Value types - pass by copy
func modifyInt(x int) {
    x = 10  // Only modifies local copy
}

num := 5
modifyInt(num)  // num is still 5

// Pointer types - pass by reference
func modifyIntPtr(x *int) {
    *x = 10  // Modifies original value
}

num := 5
modifyIntPtr(&num)  // num is now 10

// Reference types (slice, map, channel)
func modifySlice(s []int) {
    s[0] = 10  // Modifies underlying array
    s = append(s, 4)  // Only modifies local slice header
}

slice := []int{1, 2, 3}
modifySlice(slice)  // slice[0] is now 10, but length unchanged
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

| Type | Passing Mechanism | Behavior |
|------|------------------|----------|
| Primitives (number, string, boolean) | **Pass by value** | Copies value to function |
| Objects (including arrays, functions) | **Pass by reference** | Can modify original object |

```javascript
// Primitive types - pass by value
function modifyNum(x) {
    x = 10;  // Only modifies local copy
    return x;
}

let num = 5;
modifyNum(num);  // num is still 5

// Object types - pass by reference
function modifyArray(arr) {
    arr.push(4);  // Modifies original array
    return arr;
}

let myArray = [1, 2, 3];
modifyArray(myArray);  // myArray is now [1, 2, 3, 4]

// To avoid modifying objects
function safeModifyArray(arr) {
    const newArr = [...arr];  // Create copy
    newArr.push(4);
    return newArr;
}
```

</x-tab>

<x-tab title="Java" sync-id="java">

| Type | Passing Mechanism | Behavior |
|------|------------------|----------|
| Primitives (int, double, boolean, etc.) | **Pass by value** | Copies value to method |
| Objects (including arrays) | **Pass by value (reference)** | Copies reference, can modify object |

```java
// Primitive types - pass by value
public void modifyInt(int x) {
    x = 10;  // Only modifies local copy
}

int num = 5;
modifyInt(num);  // num is still 5

// Object types - pass by reference value
public void modifyArray(List<Integer> list) {
    list.add(4);  // Modifies original list
    list = new ArrayList<>();  // Only modifies local reference
}

List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3));
modifyArray(myList);  // myList is now [1, 2, 3, 4]

// To avoid modifying objects
public void safeModifyArray(List<Integer> list) {
    List<Integer> newList = new ArrayList<>(list);  // Create copy
    newList.add(4);
}
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

| Type | Passing Mechanism | Behavior |
|------|------------------|----------|
| All types | **Pass by reference** | Tables passed by reference, others by value |

```lua
-- Numbers/strings - pass by value
function modifyNum(x)
    x = 10  -- Only modifies local copy
    return x
end

local num = 5
modifyNum(num)  -- num is still 5

-- Tables - pass by reference
function modifyTable(tbl)
    tbl.value = 10  -- Modifies original table
    return tbl
end

local myTable = {value = 5}
modifyTable(myTable)  -- myTable.value is now 10

-- To avoid modifying tables
function safeModifyTable(tbl)
    local newTbl = {}
    for k, v in pairs(tbl) do
        newTbl[k] = v
    end
    newTbl.value = 10
    return newTbl
end
```

</x-tab>

</x-tabs>

### Higher-Order Functions & Closures

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
# Higher-order function
def apply_operation(func, numbers):
    return [func(x) for x in numbers]

# Lambda functions
square = lambda x: x ** 2
result = apply_operation(square, [1, 2, 3, 4])

# Closures
def make_multiplier(factor):
    def multiplier(x):
        return x * factor  # Captures factor from outer scope
    return multiplier

times_three = make_multiplier(3)
result = times_three(5)  # Returns 15

# Decorators (higher-order functions)
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"Function took {time.time() - start} seconds")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "Done"
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Higher-order function
func applyOperation(func func(int) int, numbers []int) []int {
    result := make([]int, len(numbers))
    for i, num := range numbers {
        result[i] = func(num)
    }
    return result
}

// Function literals (closures)
func main() {
    square := func(x int) int { return x * x }
    result := applyOperation(square, []int{1, 2, 3, 4})

    // Closure capturing outer variable
    factor := 3
    multiplier := func(x int) int { return x * factor }
    result2 := applyOperation(multiplier, []int{1, 2, 3, 4})
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Higher-order function
function applyOperation(func, numbers) {
    return numbers.map(func);
}

// Arrow functions
const square = x => x ** 2;
const result = applyOperation(square, [1, 2, 3, 4]);

// Closures
function makeMultiplier(factor) {
    return function(x) {
        return x * factor;  // Captures factor from outer scope
    };
}

const timesThree = makeMultiplier(3);
const result2 = timesThree(5);  // Returns 15

// Function methods (bind, call, apply)
const person = {name: "Alice"};
function greet(greeting) {
    return `${greeting}, ${this.name}`;
}

const boundGreet = greet.bind(person);
boundGreet("Hello");  // "Hello, Alice"
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Functional interfaces (Java 8+)
import java.util.function.*;
import java.util.stream.Collectors;

// Higher-order function using streams
List<Integer> applyOperation(Function<Integer, Integer> func, List<Integer> numbers) {
    return numbers.stream()
        .map(func)
        .collect(Collectors.toList());
}

// Lambda expressions
Function<Integer, Integer> square = x -> x * x;
List<Integer> result = applyOperation(square, Arrays.asList(1, 2, 3, 4));

// Closures (effectively final variables)
public Function<Integer, Integer> makeMultiplier(int factor) {
    return x -> x * factor;  // Captures factor (must be effectively final)
}

Function<Integer, Integer> timesThree = makeMultiplier(3);
int result2 = timesThree.apply(5);  // Returns 15

// Method references
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Integer> nameLengths = names.stream()
    .map(String::length)  // Method reference
    .collect(Collectors.toList());
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Higher-order function
function applyOperation(func, numbers)
    local result = {}
    for i, num in ipairs(numbers) do
        result[i] = func(num)
    end
    return result
end

-- Anonymous functions
local square = function(x) return x * x end
local result = applyOperation(square, {1, 2, 3, 4})

-- Closures
function makeMultiplier(factor)
    return function(x)
        return x * factor  -- Captures factor from outer scope
    end
end

local timesThree = makeMultiplier(3)
local result2 = timesThree(5)  -- Returns 15

-- Functions as first-class citizens
local functions = {
    add = function(a, b) return a + b end,
    multiply = function(a, b) return a * b end
}

local sum = functions.add(5, 3)
```

</x-tab>

</x-tabs>

## Important APIs

### String Operations

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
s = "hello"
s.upper()                    # 转大写
s.lower()                    # 转小写
s.strip()                    # 去除首尾空格
s.split(',')                 # 分割字符串
s.startswith('prefix')       # 检查前缀
s.endswith('suffix')         # 检查后缀
s.replace('old', 'new')      # 替换子串
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
s := "hello"
strings.ToUpper(s)           // 转大写
strings.ToLower(s)           // 转小写
strings.TrimSpace(s)         // 去除首尾空格
strings.Split(s, ",")        // 分割字符串
strings.HasPrefix(s, "prefix")  // 检查前缀
strings.HasSuffix(s, "suffix")  // 检查后缀
strings.Replace(s, "old", "new", -1)  // 替换子串
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
const s = "hello";
s.toUpperCase();              // 转大写
s.toLowerCase();              // 转小写
s.trim();                     // 去除首尾空格
s.split(',');                 // 分割字符串
s.startsWith('prefix');       // 检查前缀
s.endsWith('suffix');         // 检查后缀
s.replace('old', 'new');      // 替换子串
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
String s = "hello";
s.toUpperCase();              // 转大写
s.toLowerCase();              // 转小写
s.trim();                     // 去除首尾空格
s.split(",");                 // 分割字符串
s.startsWith("prefix");       // 检查前缀
s.endsWith("suffix");         // 检查后缀
s.replace("old", "new");      // 替换子串
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
s = "hello"
string.upper(s)              -- 转大写
string.lower(s)              -- 转小写
string.gsub(s, "pattern", "replacement")  -- 替换模式
string.find(s, "pattern")    -- 查找模式
string.sub(s, 1, 3)          -- 截取子串
string.format("%s %d", "hello", 42)  -- 格式化字符串
```

</x-tab>

</x-tabs>

### File I/O

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
with open('file.txt', 'r') as f:
    content = f.read()       # 读取文件

with open('file.txt', 'w') as f:
    f.write('content')       # 写入文件

from pathlib import Path
path = Path('file.txt')
path.exists()                # 检查路径
path.read_text()             # 读取文件内容
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
content, err := os.ReadFile("file.txt")          // 读取文件
os.WriteFile("file.txt", []byte("content"), 0644)  // 写入文件

os.Stat("file.txt")          // 获取文件信息
os.ReadDir(".")              // 列出目录内容
os.Mkdir("dir", 0755)        // 创建目录
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
fetch('file.txt')
    .then(res => res.text()) // 读取文件

// 写入文件需要使用 File API
const file = new File(["content"], "file.txt");
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
Files.readString(Path.of("file.txt"));           // 读取文件
Files.writeString(Path.of("file.txt"), "content");  // 写入文件
Files.exists(Path.of("file.txt"));                // 检查文件是否存在
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
local file = io.open("file.txt", "r")  -- 打开文件读取
local content = file:read("*a")        -- 读取全部内容
file:close()

local file = io.open("file.txt", "w")  -- 打开文件写入
file:write("content")                  -- 写入内容
file:close()

os.remove("file.txt")                  -- 删除文件
```

</x-tab>

</x-tabs>

### JSON Processing

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import json
json.dumps(obj)               # 对象转 JSON 字符串
json.loads(json_str)          # JSON 字符串转对象
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
json.Marshal(obj)             // 对象转 JSON 字节
json.Unmarshal(data, &obj)     // JSON 字节转对象
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
JSON.stringify(obj);          // 对象转 JSON 字符串
JSON.parse(jsonStr);          // JSON 字符串转对象
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// Jackson
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);  // 对象转 JSON
MyClass obj = mapper.readValue(json, MyClass.class);  // JSON 转对象
```

</x-tab>

</x-tabs>

### HTTP Requests

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import requests
response = requests.get('https://api.example.com')
data = response.json()        # 解析 JSON 响应
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
resp, err := http.Get("https://api.example.com")
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
fetch('https://api.example.com')
    .then(res => res.json())
    .then(data => console.log(data));
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com"))
    .build();
HttpResponse<String> response = client.send(request,
    HttpResponse.BodyHandlers.ofString());
```

</x-tab>

</x-tabs>

### Date/Time

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
from datetime import datetime
now = datetime.now()
formatted = now.strftime('%Y-%m-%d')  # 格式化日期
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
now := time.Now()
formatted := now.Format("2006-01-02")  // 格式化日期（Go 特殊格式）
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
const now = new Date();
const formatted = now.toISOString();   // 转为 ISO 字符串
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
LocalDateTime now = LocalDateTime.now();
String formatted = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
os.time()                     -- 获取当前时间戳
os.date()                     -- 格式化日期
```

</x-tab>

</x-tabs>

### Random & Math

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import random
random.randint(1, 10)         # 随机整数 [1, 10]
random.choice(['a', 'b', 'c'])  # 随机选择
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
rand.Intn(10)                // 随机整数 [0, 10)
rand.Intn(len(arr))          // 随机索引
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
Math.random();               // 随机数 [0, 1)
Math.floor(Math.random() * 10);  // 随机整数 [0, 10)
Math.max(1, 2, 3);           // 最大值
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
math.random(1, 10)           -- 随机整数 [1, 10]
math.floor(3.14)             -- 向下取整
math.ceil(3.14)              -- 向上取整
math.max(1, 2, 3)            -- 最大值
```

</x-tab>

</x-tabs>

### Collections (Array/List/Table)

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
arr = [1, 2, 3]
arr.append(4)                # 添加到末尾
arr.remove(1)                # 删除元素
1 in arr                     # 检查元素是否存在
arr.index(2)                 # 查找元素索引
[x for x in arr if x > 1]    # 列表推导
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
// Slice
arr := []int{1, 2, 3}
arr = append(arr, 4)         // 添加到末尾

// Map
m := make(map[string]int)
m["key"] = 1                 // 添加键值对
val, ok := m["key"]          // 获取值
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
arr = [1, 2, 3]
arr.push(4);                 // 添加到末尾
arr.pop();                   // 删除末尾元素
arr.shift();                 // 删除首元素
arr.includes(2);             // 检查元素是否存在
arr.indexOf(2);              // 查找元素索引
arr.filter(x => x > 1);      // 过滤数组
arr.map(x => x * 2);         // 映射数组
arr.reduce((acc, x) => acc + x, 0);  // 归约
```

</x-tab>

<x-tab title="Java" sync-id="java">

```java
// ArrayList
List<Integer> list = new ArrayList<>();
list.add(1);                 // 添加元素
list.remove(Integer.valueOf(1));  // 删除元素（按值）
list.contains(1);            // 检查元素是否存在
list.get(0);                 // 获取元素

// HashMap
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);           // 添加键值对
map.get("key");              // 获取值
map.containsKey("key");     // 检查键是否存在
```

</x-tab>

<x-tab title="Lua" sync-id="lua">

```lua
-- Table
arr = {1, 2, 3}
table.insert(arr, 1, value)  -- 在索引1处插入值
table.remove(arr, 1)         -- 删除索引1的元素
table.sort(arr)              -- 排序
table.concat(arr, ",")       -- 连接为字符串
table.unpack(arr)            -- 解包
```

</x-tab>

</x-tabs>

### Async Operations

<x-tabs>

<x-tab title="Python" sync-id="python" active>

```python
import asyncio

async def fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get('url') as response:
            return await response.json()

asyncio.run(fetch_data())
```

</x-tab>

<x-tab title="Go" sync-id="go">

```go
ch := make(chan int)
go func() {
    ch <- 1                   // 发送数据到通道
}()

select {                      // 多路复用
case v := <-ch:
    fmt.Println(v)           // 接收数据
case <-time.After(time.Second):
    fmt.Println("timeout")   // 超时
}
```

</x-tab>

<x-tab title="JavaScript" sync-id="javascript">

```javascript
// Promise
Promise.resolve(1).then(x => console.log(x));

// Async/Await
async function fetchData() {
    const res = await fetch('url');
    const data = await res.json();
    return data;
}

// setTimeout
setTimeout(() => console.log('delayed'), 1000);
```

</x-tab>

</x-tabs>