Lua 基本语法
Lua - 基本语法
Section titled “Lua - 基本语法”Lua 的语法相对简单且一致,易于学习。让我们开始编写您的第一个 Lua 程序!
第一个 Lua 程序
Section titled “第一个 Lua 程序”交互模式编程 (Interactive Mode Programming):
Section titled “交互模式编程 (Interactive Mode Programming):”Lua 提供了一种交互模式,也称为 REPL (读取-求值-打印循环, Read-Eval-Print Loop)。您可以在其中逐行输入 Lua 语句并立即查看结果。要启动交互模式,请打开您的终端或命令提示符,然后输入 lua:
$ luaLua 5.4.6 Copyright (C) 1994-2023 Lua.org, PUC-Rio>然后您可以在 > 提示符下直接输入 Lua 代码:
> print("Hello from interactive Lua!")按下 Enter 后,您将看到输出:
Hello from interactive Lua!要退出交互模式,通常可以输入 os.exit() 或按下 Ctrl+D (在类 Unix 系统上) 或 Ctrl+Z 然后按 Enter (在 Windows 上)。
脚本模式编程 (Script Mode Programming):
Section titled “脚本模式编程 (Script Mode Programming):”对于较大的程序,您会将 Lua 代码写入文件 (通常以 .lua 为扩展名),然后告诉 Lua 解释器执行该文件。
- 创建一个名为
myscript.lua的文件,并添加以下内容:
print("Hello from a Lua script!")- 保存文件。打开您的终端或命令提示符,导航到保存
myscript.lua的目录,然后运行:
$ lua myscript.lua输出将是:
Hello from a Lua script!可执行脚本 (类 Unix 系统):
Section titled “可执行脚本 (类 Unix 系统):”在类 Unix 系统 (如 Linux, macOS) 上,您可以通过在文件开头添加一行 “shebang” 并设置执行权限,来使您的 Lua 脚本成为可执行文件。
#!/usr/bin/env lua
print("Hello from an executable Lua script!")#!/usr/bin/env lua 这一行告诉系统使用在用户环境路径中找到的 lua 解释器。然后,使脚本可执行:
$ chmod +x myscript.lua并直接运行它:
$ ./myscript.lua输出:
Hello from an executable Lua script!Lua 中的记号 (Tokens)
Section titled “Lua 中的记号 (Tokens)”Lua 程序由各种记号 (tokens) 组成。记号是一系列具有集体意义的字符。记号可以是关键字 (keywords)、标识符 (identifiers)、常量 (literals)、运算符 (operators) 或标点符号 (punctuators)。例如,语句:
local message = "Hello, " .. _VERSION .. "!"io.write(message, "\n")单独的记号包括:local、message、=、"Hello, "、..、_VERSION、..、"!"、io、.、write、(、message、,、"\n"、)。
注释 (Comments)
Section titled “注释 (Comments)”注释是 Lua 解释器会忽略的解释性文本。它们用于使代码更易于理解。
- 单行注释 (Single-line comments): 以
--开头,并持续到行尾。 - 多行 (块) 注释 (Multi-line (block) comments): 以
--[[开头,以]]结尾。它们可以跨越多行,也可以用于临时禁用代码块。
-- 这是一个单行注释。
local x = 10 -- 这个注释在行尾。
--[[这是一个多行注释。它可以跨越多行。]]
-- 您甚至可以在其中嵌套单行注释,或轻松注释掉代码:--[[-- You can even nest single-line comments inside, or easily comment out code:local y = 20print(y)--]]
-- 提示:为了轻松切换块注释,您可以使用 `--[=[ ... ]=]`-- 要注释掉:--[=[ 代码块--]=]-- 要取消注释,只需去掉一个连字符:-[=[-- To uncomment, just remove one hyphen: -[=[标识符 (Identifiers)
Section titled “标识符 (Identifiers)”标识符 (或名称) 用于标识变量 (variables)、函数 (functions) 或表格 (table) 的字段 (fields)。Lua 中的标识符可以由字母 (a-z, A-Z)、数字 (0-9) 和下划线 (_) 组成。它们不能以数字开头。Lua 是区分大小写的,因此 myVar 和 myvar 是不同的标识符。
有效标识符示例:
name userName _temp count1 MAX_VALUE isValid关键字 (Keywords)
Section titled “关键字 (Keywords)”关键字是 Lua 中具有特殊含义的保留词,不能用作标识符。以下是 Lua 的一些关键字:
| and | break | do | else |
|---|---|---|---|
| elseif | end | false | for |
| function | if | in | local |
| nil | not | or | repeat |
| return | then | true | until |
| while |
Lua 中的空白符 (Whitespace)
Section titled “Lua 中的空白符 (Whitespace)”空白符是指空格、制表符和换行符。Lua 使用空白符来分隔记号,但通常会忽略额外的空白符。空行也会被忽略。
例如,在 local age 中,local 和 age 之间的空格是必需的,以便将它们区分为两个单独的记号。
local age -- 这里需要空白符然而,在像 fruit = apples + oranges 这样的赋值语句中,= 和 + 周围的空白符是可选的,但通常用于提高可读性。
fruit=apples+oranges -- 有效,但可读性较差fruit = apples + oranges -- 带有空白符时可读性更好