Lua没有内置的三元运算符,但可以使用and
和or
来模拟:
-- 这种写法只在 a 不为 false 或 nil 时完全等同于三元 result = condition and a or b -- 一个更通用的写法,避免了当 a 为 false 时不等效于三元的情况 result = (condition and {a} or {b})[1]
参考Lua 中的三目运算符 | 菜鸟教程这篇文章理解
使用起来总感觉别扭,不如Python的a if condition else b
直观。
-- 全局变量: 默认情况下,所有变量都是全局的globalVar = 10-- 局部变量: 使用 local 关键字声明local localVar = 20-- 多重赋值a, b = 1, 2
if condition1 then -- codeelseif condition2 then -- codeelse -- codeend
-- 1. while loopwhile condition do -- codeend-- 2. repeat until. Similar to do-while in other languagesrepeat -- codeuntil condition-- 3.1 numeric for loopfor i = start, end, step do -- codeendarr = {1, 2, 3}for i = 1, #arr do -- codeend-- 3.2. generic for looparr = {1, 2, 3}for index, value in ipairs(arr) do -- codeenddict = {a = 1, b = 2}for key, value in pairs(dict) do -- codeend
Lua中的函数是一等公民(first-class citizens),可以像其他值一样被操作和传递
Lua提供了多种定义函数的方式:
-- 标准函数定义function functionName(parameters) -- 函数体 return returnValueend-- 局部函数定义local function localFunction(parameters) -- 函数体 return returnValueend-- 匿名函数赋值给变量local functionVar = function(parameters) -- 函数体 return returnValueend-- 函数调用result = functionName(arguments)
存储在变量中:
local greet = function(name) return "Hello, " .. nameendprint(greet("World")) -- 输出: Hello, World
作为参数传递给其他函数:
local function operate(x, y, operation) return operation(x, y)endlocal add = function(x, y) return x + y endlocal multiply = function(x, y) return x * y endprint(operate(5, 3, add)) -- 输出: 8print(operate(5, 3, multiply)) -- 输出: 15
可以作为其他函数的返回值:
local function createMultiplier(factor) return function(n) return n * factor endendlocal double = createMultiplier(2)local triple = createMultiplier(3)print(double(10)) -- 输出: 20print(triple(10)) -- 输出: 30
匿名函数是没有名称的函数,通常在需要一个简单、一次性使用的函数时定义。它们经常用于赋值给变量或作为参数传递。类似于 Java 中的 lambda 表达式。
-- 赋值给变量local square = function(x) return x * x endprint(square(5)) -- 输出: 25-- 作为参数传递 (常见于 table.sort)local numbers = {5, 1, 9, 3}table.sort(numbers, function(a, b) return a < b end)
闭包是计算机科学中的一个重要概念,特别是在函数式编程和面向对象编程中,这里不展开介绍
闭包可以理解成是函数和其相关变量的组合体,通常包含函数本身和函数创建时的环境(变量和作用域)。在[[#First-Class Functions]]例子中的double
就是一个Closure
(闭包),携带了创建时的环境(factor
变量)。
Lua 函数可以返回多个结果,和Python类似。
local function getCoordinates() return 10, 20, "center"endlocal x, y, label = getCoordinates()-- 如果接收变量少于返回值,多余的返回值会被丢弃local xOnly = getCoordinates()print(xOnly) -- 输出: 10-- 如果接收变量多于返回值,多余的变量会被赋值为 nillocal a, b, c, d = getCoordinates()print(d) -- 输出: nil
Lua Cheat Sheet